Compare commits

...
Author SHA1 Message Date
Codeman maintainer 14e5320762 chore: version packages
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 11:18:06 +01:00
Codeman maintainer 1cff252277 chore: the release changeset says both new views are opt-in
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:55:44 +01:00
Codeman maintainer 5f4951884f fix(web): the Codex in-pane file click is behind the Codex files setting too
Owner decision for 1.52.1: #850 left a click on a file name Codex
underlined in the pane ungated, so it opened the preview for everyone.
_handleDesktopTerminalClick() now asks _codexFilePreviewsEnabled() first;
off, every click in a Codex pane goes on to Codex as before (main
terminal, split pane and tiles share that handler). The setting now
gates four behaviours: the chip's tooltip (and its zh-CN), the wiki,
src/web/CLAUDE.md and the off-state test say so. The new test fails
without the gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:55:34 +01:00
Codeman maintainer 3994196341 fix(web): the Chat / Terminal switch is off by default
Owner decision for 1.52.1: the chat view's switch must not appear for
every desktop user on every local Claude session. showChatViewSwitch now
shows it only when true (an absent key means hidden), on both the reader
(_chatViewSwitchShown) and the App Settings checkbox. The chat view
itself was already off by default; Alt+Shift+C still switches views with
the switch hidden. Docs and tests follow; the two default tests fail
with the old !== false reader.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:54:17 +01:00
Codeman maintainer 15ea44e5c1 chore: the release changeset names the Mac app tab fix
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:45:42 +01:00
Codeman maintainer bc1a97eee2 fix(desktop): a server tab can be dragged into the last place
Dragging a tab as far right as it goes left it one place short of the
end (4 tabs: the first one landed third, the move posted to: 2). The
clamp stops the dragged tab with its centre exactly on the last tab's
centre, and the comparison was strict. A tab after the dragged one now
counts as passed once the centres meet; one before it still needs the
centre to cross, so a press that does not move stays in place.

Found while integrating #852 with #816 (shipped in 1.52.0). The strip
walk in test/desktop-tabs-pages.browser.test.ts drags past the end; that
check fails without the fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:45:42 +01:00
Codeman maintainer 63af255726 chore: one release changeset for the next release
Replaces the four PR changesets (claude-starts-under-root,
installer-headless-sudo, trusted-proxy-sign-in, upload-html-documents)
and names #850, #859, #860 and #866, which brought none. Patch:
#854's changeset asked for minor, which is the owner's call at COM.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:22:23 +01:00
Codeman maintainer 17e66d50c0 docs: the review items of #860 that go on top
- README.ja.md: the link under the Mac download badge pointed at the
  English anchor; it now uses the translated heading's.
- Eleven bold and italic markers GitHub printed as literal characters
  (CommonMark: '_' inside a word never opens emphasis, and '**' between
  punctuation and a letter cannot open or close bold): '*' inside words,
  <strong> where the punctuation rule bites.
- The Japanese for the rate-limit sentence the English README gained
  after the branch was cut (a request with no credentials is never
  counted).
- The chat view's Alt/Option+Shift+C row (#859, this release) in the
  Japanese and Chinese shortcut tables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:22:23 +01:00
Codeman maintainer c3eb9cad22 docs: the review items of #859 that go on top
- docs/chat-view-plan.md still said a Docker case with working hooks
  updates only at the start and end of a turn; since hostTranscriptPath()
  maps the container path to the host's copy, it gets mid-turn updates.
- The captureIntentPrompt comment said only hook-fed sessions have a
  transcript watcher; statusline reports and full reads start one too.

The third item (the SSE header count) needs no change on the merged tree:
master already had 164 constants under a header that said 163, and with
transcript:update the header's 165 is right.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:22:23 +01:00
Codeman maintainer 4be36b0404 fix(auth): the review items of #854 that go on top
- The strip removed the proxy headers from req.headers only, while
  req.raw.rawHeaders and req.raw.headersDistinct still held the secret.
  takeTrustedProxyHeaders() now takes the raw message and removes them
  from both. A plain splice is not enough on a real IncomingMessage: its
  headers and headersDistinct getters are lazy and walk rawHeaders up to
  the count stored at parse time, so one that first runs after the splice
  throws. Both are read (cached) first. Two tests, each caught by its
  mutation: the stripping test checks the raw list, and a real http
  request checks all three views and that the getters still answer.
- CLAUDE.md's Rate limit row names the trusted-proxy secret's own bucket.
- The wiki lists the loopback addresses the check accepts, as the
  contributor offered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:22:23 +01:00
Codeman maintainer a117955490 fix(web): the review item of #850 that goes on top
The Dock button's hidden attribute was set only when a preview opened, so
with a preview open, switching Codex files off left a Dock button that did
nothing and switching it on showed none until the next preview.
applyHeaderVisibilitySettings() now sets it beside the Response files
button, and a test flips the setting with a preview open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:16:05 +01:00
Codeman maintainer d3d1f7cde1 docs: the review item of #869 that goes on top
The Prompt uploads paragraph said the server keeps out what it "would
run"; the scope exclusion keeps out what an agent could run, the phrase
docs/api-reference.md and docs/architecture-invariants.md already use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:16:05 +01:00
Codeman maintainer 3397d11859 Merge #859: a chat view shows a Claude session's conversation, rendered and live (chat view 1/5)
# Conflicts:
#	docs/architecture-invariants.md
#	src/web/CLAUDE.md
#	src/web/public/settings-ui.js
2026-12-03 10:15:29 +01:00
Codeman maintainer ab5f197dcc Merge #850: Open Codex file links in a docked preview (COD-152) 2026-12-03 10:15:14 +01:00
Codeman maintainer 01380d8b26 Merge #854: feat(auth): sign in through a trusted reverse proxy in multi-user mode (experimental) 2026-12-03 10:15:13 +01:00
Codeman maintainer 95ad7f2d00 Merge #863: fix: a server running as root starts Claude, and a headless install gets past sudo 2026-12-03 10:15:12 +01:00
Codeman maintainer ef730de240 Merge #860: docs: add Japanese README 2026-12-03 10:15:12 +01:00
Codeman maintainer 7df0f11892 Merge #869: feat(uploads): prompt uploads accept .html and .htm as documents 2026-12-03 10:15:11 +01:00
Codeman maintainer 111fb323ee Merge #866: fix(web): a markdown table column no longer shrinks to one letter per line 2026-12-03 10:15:10 +01:00
Ludo FourrageandClaude Opus 5.5 5374d020d7 docs(uploads): the last three places describing the html refusal
api-reference limits the refused example to scripts and says html/htm are
admitted and inert, leaving svg as the markup type kept out.
architecture-invariants lists html/htm in the text family and drops html from
the scope exclusion, as CLAUDE.md does. The wiki says the File Viewer shows an
uploaded page's source, which is what a click on its path does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 13:28:58 -08:00
Ludo FourrageandClaude Opus 5.5 85c0f35972 feat(uploads): prompt uploads accept .html and .htm as documents
AI tools write specifications, reports and plans as HTML as often as
Markdown, and handing one to a session as context is the same job as
attaching a .md. Paste, drop and every Attach picker refused them with
"Unsupported file type".

.html/.htm join the text family (UTF-8, no NUL byte) on the server and in
every browser copy the parity test pins. An upload is stored to be read,
never rendered on Codeman's origin: file-raw serves it as octet-stream with
nosniff and html-view refuses a page under .codeman-uploads, both now pinned
by tests. Scripts (.sh, .py, .js) are still refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 10:32:25 -08:00
Michael GrundbergandClaude Opus 5.5 691ea6c87a fix(web): inline code and links in a table cell break anywhere
Chromium never breaks a line after `/`, so under the cells' `break-word` a
URL, an identifier or a hash in backticks set its column's width, and the
whole table scrolled sideways on a phone. Inline code and links in a cell
now break anywhere, and a cell holding one gets the 6em floor that cells
with a linked path had. In a 360 px column in Chromium and Firefox, URL,
identifier and hash tables fit as they did on master.

Two costs remain. A code-only column such as `-v` grows from 52 px to
80 px. CSS cannot tell an autolink from a link with a prose label, so a
long word in a label can break mid-word in a narrow column.

The test's selector lookup now splits a selector list only on commas
outside parentheses, so it can find the `:is()` and `:has()` rules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 15:37:05 +01:00
Michael GrundbergandClaude Opus 5.5 5588a54e3f fix(web): a table column of linked paths keeps a readable width
The first commit left one case of the same squeeze. Codeman turns the
paths in an answer into links, and a linked path keeps
`word-break: break-all` so that it can wrap anywhere. That lets the
browser count every letter as a break point when it sizes the column,
so in a table whose headers fill the width, a column of paths shrank
to three or four letters per line. A cell that holds a linked path now
has a minimum width of 6em. Other cells keep their natural width, so a
narrow column such as row numbers stays narrow.

On a 390 px view in Firefox and Chromium, a path column went from 48 px
to 83 px, and a `#` column kept its 32 px.

The comment on the cell rule also said wrongly that a cell breaks a word
wider than its column. In automatic table layout a column is never
narrower than its longest word, so that never happens, and the comment
now says that.

The test reads every rule that names a selector, in styles.css and
mobile.css, with comments removed first, so a later override fails it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:50:00 +01:00
Michael GrundbergandClaude Opus 5.5 2ea593c2e2 fix(web): a markdown table column no longer shrinks to one letter per line
Rendered markdown sets `overflow-wrap: anywhere` so that a long path in
prose wraps, and table cells inherited it. With `anywhere`, the browser
counts every letter as a break point when it computes a cell's minimum
width. The header cells never wrap, so in a table whose headers fill the
width, the column under an empty header got only its minimum width, and
its labels stood one letter per line.

Table cells now use `overflow-wrap: break-word`. A cell still breaks a
word that is wider than its column, but its minimum width is its longest
word. In Chromium, the label column of a five-column table went from
36 px to 74 px and wraps between words. A table with an unbreakable
cell wider than the view scrolls sideways inside its wrapper, which the
wrapper already allows.

The Response Viewer and the File Viewer's markdown view share these
rules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:01:47 +01:00
Aamer Akhter e3c156e6e8 fix(preview): COD-152 put Codex file extras behind a per-device setting
The Response files header button, taking a click on a Codex sidebar file
tab (and the link suppression on those rows) and the Dock control on file
previews now sit behind one per-device setting, codexFilePreviewsEnabled
(App Settings > Header buttons > Codex files), default off. With it off
none of the three exists, and Response files stays off phones even with
it on.

Also from the second review: the docked preview is z-index auto so it
sits under modals and the response viewer, a double-click no longer
opens the preview, the parsed conversation is cached per idle session
until its next turn, the Response files rows are buttons, and the two
tests that failed at the previous head pass. Documented in
Settings-Reference, Working-With-Files and src/web/CLAUDE.md.
2026-11-27 12:58:48 -05:00
Codeman maintainer c51a7134eb fix(install): a headless run with a passwordless sudo gets past the sudo step
A non-root account with a working passwordless sudo and no controlling
terminal (su - user -c, cron, a CI runner, cloud-init) ended on "Failed to
obtain sudo privileges". The /dev/tty node exists there and cannot be opened;
install.sh tested [[ -e /dev/tty ]] and then ran sudo -v < /dev/tty, whose
redirect fails before sudo starts. Measured 2026-11-27 in a fresh ubuntu:24.04
container: node present, open refused, sudo -n true fine, install dead at
"Installing Git via apt".

- tty_openable() opens the node, the probe has_tty() already used, and every
  redirect from /dev/tty now sits behind it instead of a file test:
  ensure_sudo, sudo_session_try, the message choice in sudo_session_start,
  and the three sites with the same shape (Homebrew, the Tailscale installer,
  tailscale up). With no terminal they fall back to the plain command.
- ensure_sudo returns as soon as sudo -n true works. sudo -v is no substitute
  for that test: it asks for a password as soon as one sudoers entry of the
  account asks for one, so an account in the sudo group with a NOPASSWD entry
  of its own (the cloud-image layout) runs sudo <command> freely and is
  refused by sudo -v (measured on sudo 1.9.15).

test/install-sh-invariants.test.ts fails for a file test on /dev/tty and for
a redirect from it that is not directly under the probe, and drives the sudo
helpers in a real bash with no controlling terminal against a stub sudo.

Checked in a throwaway ubuntu:24.04 container, through su - user -c with
CODEMAN_NONINTERACTIVE=1: the installer before this change stops at the sudo
step, this one installs git, tmux, Node.js and the build tools, clones and
was building when the check was stopped. The helpers were also run under
bash 3.2.57. The Homebrew branch could not be run here (no macOS).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 17:54:43 +01:00
Codeman maintainer d9fce03444 fix(launch): a server running as root starts Claude without the bypass flag
Installed and started as root (a VPS, an LXC container), every local Claude
session died at once: the default permission mode launches Claude Code with
--dangerously-skip-permissions, and Claude Code refuses that flag under uid 0
("cannot be used with root/sudo privileges for security reasons", pane dead
with status 1). Shell sessions were fine. Measured 2026-11-27 with the public
installer in a fresh ubuntu:24.04 container.

Docker cases already answer the same refusal for a root container with
overlays.docker.rootCommand. This is the host-level form, as registry data:

- An enum launch param may declare rootValue, a map from a value to the value
  it takes when the server process runs as uid 0 and the launch is local.
  Claude declares claudeMode: dangerously-skip-permissions -> normal. The
  schema holds keys and replacements to the param's values.
- applyRootValues() (config/cli-registry/root-launch.ts, pure) rewrites the
  param values before the argv engine sees them and hands back the object it
  was given when nothing changes, so a launch that is not root is
  byte-identical (the spawn goldens are untouched).
- serverRunsAsRoot() (utils/server-uid.ts) reads the uid at call time. Under
  vitest it answers false unless a test stubs it.
- The uid is asked in two places only. serverRootSpawnOptions() feeds the two
  tmux launches (createSession, respawnPane), which every local tmux launch
  goes through: new session, resume, dead-pane respawn, restartCli(), cron,
  quick-start, reboot restore. buildPermissionArgs() covers the two launches
  with no tmux, the direct-PTY fallback and the one-shot run.
- Remote and Docker pane commands never read it, and auto, allowedTools and
  normal are passed through unchanged. IS_SANDBOX is not set.
- Each swap is logged once per launch, naming the cause and the way out.

Checked end to end in a throwaway ubuntu:24.04 container running this tree's
server as root with Claude Code 2.1.332: the pane command carries no bypass
flag, the pane stays alive on Claude's first-run screen, and the log line is
there. The same run as an ordinary user keeps the flag.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 17:54:43 +01:00
Michael GrundbergandClaude Opus 5.5 c6fff5e6a8 feat(web): a chat view shows a Claude session's conversation, rendered and live
A local or Docker Claude session can show its conversation as rendered text,
the way the Response Viewer draws it, in place of the terminal. The terminal
stays attached and sized underneath, so switching views never resizes the pane,
and the user still types in the terminal. Discussion #858 has the background.

- A Chat / Terminal switch and Alt+Shift+C change the view, and each session
  remembers its choice on this device until the session is gone. Two per-device
  settings pick the default view and hide the switch. Phones, remote and
  adopted sessions keep the terminal.
- The server broadcasts `transcript:update`, at most one per 750 ms per session,
  and the view re-reads the conversation on it, so an answer fills in mid-turn.
- The server keeps each transcript's parse and the byte offset it reached, so a
  read parses only the bytes appended since the last one, in chunks with an await
  between them. Overlapping reads of one file share one pass. The Response
  Viewer and the Discord bridge read through it too.
- A full conversation read starts a transcript watcher for a session that has
  none, such as one picked up after a server restart.
- A Docker session's hook reports the container's transcript path, and the
  server watches the host's copy of that file.
- After `/clear`, Claude Code runs the statusline command with the new
  conversation's id and transcript path. The statusline exporter posts them, and
  the server follows the new conversation the way it follows a hook's report.
- Keep-warm turns are hidden, long prompts fold, a "Working" line shows the turn's
  running time, and a pending dialog shows a notice that opens the terminal.

The design note, docs/chat-view-plan.md, covers this and the four steps that
follow it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:18:29 +01:00
Ikko Eltociear AshimineandClaude Opus 5.5 58b923f2e5 docs: fix README.ja.md anchors and paste wording, guard translated READMEs in test
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:24:25 +09:00
Ikko Eltociear Ashimine fd2b232efe docs: add Japanese README 2026-11-27 15:41:40 +09:00
13768039+zomby1 a69ceef4f0 docs(auth): say which requests the proxy example still redirects
The rule answers a request with a non-navigation Sec-Fetch-Mode with 401. A
client that sends no such header is redirected as before, and a WebSocket
handshake never followed the redirect.
2026-11-26 18:34:40 +01:00
13768039+zomby1 029adccb83 docs(auth): the two dead-capability requests with no route status to copy
A WebSocket upgrade and GET /webview/<cap> without the trailing slash get the
hook's 403 under a dead web-tab capability. Say so in section 10a, next to the
statuses.
2026-11-26 18:34:40 +01:00
13768039+zomby1 992819ba98 test(auth): pin the hook's 403 for the two dead web-tab requests
Under a dead web-tab capability, GET /webview/<cap> without the trailing
slash and a WebSocket upgrade have no route status to copy (the route
alone redirects, or accepts and closes with 4003). With trusted-proxy
sign-in on, the hook answers both with 403, no challenge and no count.
The refusal test sends each of them more often than the per-IP failure
limit, before its final Basic sign-in, so a counted one turns that
sign-in into a 429.
2026-11-26 18:34:40 +01:00
13768039+zomby1 dcfa76125f docs(auth): send only page navigations to the proxy sign-in
Background requests from an open page followed the redirect to the sign-in
start, and each one replaced oauth2-proxy's CSRF cookie, so a real sign-in
could end on its CSRF error page. The example now answers them with 401 and
uses one CSRF cookie per sign-in.
2026-11-26 08:53:20 +01:00
13768039+zomby1 17b885f5da docs(auth): the base-path refusal judges both forms of the path 2026-11-25 10:49:37 +01:00
13768039+zomby1 d620b7b194 docs(api): the hook-path 401 carries no Basic challenge 2026-11-25 10:36:36 +01:00
13768039+zomby1 aabd71ee98 fix(auth): keep the capability prefix on a mount named like it
The server strips the literal mount prefix before the auth hook runs, so
under a base path named /webview, /html-view or starting with one of
them, /webview/webview/x arrives as /webview/x. Removing the base path
again in capabilityPrefixOf() then took the capability prefix itself,
and such paths reached the Basic check and its failure count.

The normalised path is now judged as it is first, and only when that is
no capability path, once more with the base path removed once. Either
match counts, so this can only add refusals, never an exemption.
2026-11-25 10:36:36 +01:00
13768039+zomby1 bb68915384 docs(auth): the capability refusal also covers re-spelled base paths 2026-11-25 09:38:13 +01:00
13768039+zomby1 7e199f1fac docs(auth): trusted-proxy review points: claim trust, SameSite, hook replies
The walkthrough now says the app registration is single-tenant, that email and
preferred_username are mutable, and that a logon name with a dot needs the map.
oauth2-proxy gets cookie_samesite = lax, and its identity headers are removed on
the way to Codeman. The API reference lists the hook's plain-text replies for a
proxy sign-in and the 404 for an unknown HTML-view capability.
2026-11-25 09:38:13 +01:00
13768039+zomby1 3658dc516f fix(auth): refuse capability paths under any spelling of the base path
Under CODEMAN_BASE_URL the server strips the mount prefix only in its
literal spelling, so /CODEMAN/webview/x, /%63odeman/webview/x,
//codeman/webview/x or /x/../codeman/webview/x reached the credential
checks with the prefix still in front. A proxy's path matcher lets
those through without its sign-in, so they got a Basic challenge and
filled the per-IP failure bucket. capabilityPrefixOf() now takes the
base path and, after its normalisation, removes the lower-cased base
path once when the path starts with it. The exemptions are unchanged.

The secret file's real path is now resolved once, when the secret is
read, instead of on every sensitive-path check.

Tests for behaviour that had none: the last-login throttle for proxy
sign-ins, the 503 for an unreadable user store with a valid cookie or
Basic credentials, removal of X-Codeman-User when another username
header is configured, the normal challenge on capability paths with
the feature off, the secret file reached through a symlink, and the
reserved username header names.
2026-11-25 09:36:56 +01:00
13768039+zomby1 8480bba908 feat(auth): sign in through a trusted reverse proxy in multi-user mode (experimental)
Multi-user mode only accepted Codeman passwords over HTTP Basic, so a team with an
identity provider (Entra ID, Google, Keycloak, ...) had to sign in twice, with no link
between the two identities.

With a shared secret configured (CODEMAN_TRUSTED_PROXY_SECRET_FILE, or
CODEMAN_TRUSTED_PROXY_SECRET; at least 32 printable ASCII characters), an authenticating
reverse proxy on the same host (oauth2-proxy behind Caddy or nginx, mod_auth_openidc,
Authelia) forwards X-Codeman-Proxy-Secret and X-Codeman-User, and the request signs in
as that existing, enabled account. CODEMAN_TRUSTED_PROXY_USER_HEADER renames the
username header. The feature is experimental (docs/versioning-policy.md): its settings,
headers and the viaTrustedProxy field may change until promoted.

- Accepted only from a loopback socket (isLoopbackIp, now shared with the hook-secret
  bypass) with a timing-safe secret match.
- The secret is read once at the start of WebServer.start(), before sessions are spawned
  or restored, and both variables are then removed from process.env, since every
  session inherits Codeman's environment. The secret file's resolved path stays in the
  module for the sensitive-path blocklist.
- A configured setup that cannot be used stops the start, like the first boot without
  users, with a message that says why and never contains the secret: both variables
  set; a secret file that is unreadable, empty, or readable by group or others (not
  checked on Windows); a short or non-ASCII secret; a secret with multi-user mode off;
  a rejected username header name. getTrustedProxyConfig() returns null for the same
  cases as a second layer.
- Both headers are read and deleted from every request by the first auth hook, in every
  auth mode, so no exemption or route (e.g. the web-tab relay) can forward the secret.
  The relay's drop list names them too, including a configured username header.
- Fails closed once the secret header is present, even empty: a wrong secret or a
  non-loopback source is 401; a missing username, or one with no enabled account, is a
  plain 403 with no challenge. None of these falls through to cookie or Basic. A
  username header without the secret is ignored.
- The username is matched exactly: normalizeUsername(), then the user store's username
  rule, no other transformation. A header sent twice arrives joined ("alice, bob") and
  is refused.
- The secret is compared before the failure bucket, so a correct secret always passes;
  only failures are throttled, in their own per-IP bucket.
- Checked before the session cookie; a cookie on the same request is neither used nor
  refreshed, and no cookie is minted: the proxy authorizes every new request and
  WebSocket upgrade.
- mustChangePassword does not gate a proxy sign-in, and GET /api/me reports
  mustChangePassword: false and viaTrustedProxy: true. Proxy sign-ins update the
  last-login time at most every 15 minutes.
- The username header is removed from every request, so its name is validated by shape
  (an X-... extension header or Remote-User; standard and reserved headers refused).
- With the feature configured, a /webview/ or /html-view/ request the capability
  exemptions don't let through is refused with the route's own 403/404 before the
  credential checks, by prefix on a path normalised the way a proxy's matcher sees it
  (case-insensitive, percent-decoded, dot segments resolved), whatever the token looks
  like: the proxy has to let these paths through without its sign-in, so they must not
  reach the Basic check, prompt or failure bucket. Without a proxy they keep the normal
  401.
- The configured secret file is on the isSensitivePath blocklist.
- The startup log says "Trusted-proxy sign-in enabled (experimental)".
- Single-user mode, the Host/Origin guard and the hook-secret bypass are otherwise
  unchanged.

Docs: security-architecture §10a, architecture-invariants, versioning-policy (new
experimental subsection), Settings-Reference, web-tabs and its wiki page, multi-user-plan,
the CLAUDE.md summary line, and a Caddy + oauth2-proxy walkthrough in the Multi-User Mode
wiki page (web tabs and HTML view bypass the sign-in and never get the secret; the proxy
removes its own session cookie; hook endpoints and their /api/v1 aliases are blocked;
optional username from an IdP claim; what the secret does not protect against).
Changeset included.
2026-11-24 21:41:53 +01:00
Aamer Akhter b02816c1cc fix(preview): COD-152 address upstream review 2026-11-23 18:06:30 -05:00
Aamer Akhter ac4ab8cf23 fix(preview): COD-152 declare mobile response files visibility 2026-11-23 13:41:41 -05:00
Aamer Akhter 1835b39e2c fix(preview): COD-152 resolve abbreviated Codex file tabs 2026-11-23 13:20:32 -05:00
Aamer Akhter 6de846ba9a feat(preview): COD-152 open Codex files in a docked preview 2026-11-23 13:06:33 -05:00
101 changed files with 10274 additions and 391 deletions

No files matched your search

+1 -1
View File
@@ -10,7 +10,7 @@
"name": "codeman",
"source": "./plugins/codeman",
"description": "Drive Codeman from inside a Claude Code session: spawn worker sessions, prompt them, wait for them, read their answers, clean up. Acts inside a Codeman-managed session; outside one it only reads saved Codex conversations offline.",
"version": "1.52.0",
"version": "1.52.1",
"author": {
"name": "Ark0N",
"url": "https://github.com/Ark0N"
+30
View File
@@ -1,5 +1,35 @@
# aicodeman
## 1.52.1
### Patch Changes
- 63af255: ### Thanks
- @irisitymichaelgrundberg for the first part of the chat view (#859) and for the markdown table fix (#866), each with careful measurements in two browsers.
- @zomby1 for single sign-on through a reverse proxy (#854, proposed in #846), run behind Caddy and oauth2-proxy for days before it landed.
- @aakhter for Codex file previews (#850), three review rounds.
- @ludovicfourrage for HTML uploads (#869, from #868).
- @eltociear for the Japanese README (#860), a first contribution.
**Claude sessions start when Codeman runs as root (#863).** On a VPS or in a Proxmox LXC container the server often runs as root, and Claude Code refuses `--dangerously-skip-permissions` there, so every local Claude tab was a dead pane. A server running as root now starts Claude without the bypass (Claude asks for permission instead) and says so in the server log. Shell sessions, Docker cases and remote sessions are unchanged.
**Multi-user mode can sign people in through a reverse proxy (#854, experimental).** With `CODEMAN_TRUSTED_PROXY_SECRET_FILE` set, an authenticating proxy on the same host (oauth2-proxy behind Caddy or nginx, Authelia, Apache mod_auth_openidc) signs people in with Entra ID, Google Workspace, Keycloak and others. Codeman accepts the proxy's `X-Codeman-User` only from a loopback connection that also presents the secret, and only for an existing, enabled account. The headers are removed from every request before anything else sees them. Off by default. The wiki's Multi-User Mode page has a Caddy and oauth2-proxy walkthrough.
**A chat view for Claude sessions (#859, first part, opt-in).** A local or Docker Claude session can show its conversation as rendered text instead of the terminal. Alt+Shift+C switches a session between Chat and Terminal, and each session remembers its choice on the device. Answers fill in while the turn runs, long prompts fold, and a notice with a button to the terminal appears while Claude waits on a permission prompt or a question. You still type in the terminal for now; the message box follows in a later release. Nothing changes until you choose it: Settings > Header & Panels has "Open Claude sessions in Chat view" and "Show the Chat / Terminal switch" (a switch at the top right of the session), both off by default. Phones, remote and adopted sessions, tiles and the split's second pane keep the terminal.
**Codex sessions can open the files they link in Codeman's preview (#850, opt-in).** With the new per-device Codex files setting on (Settings > Header & Panels, off by default), clicking a file name Codex underlined in its answer, or a file tab in Codex's own sidebar, opens that file in the file preview when the conversation names exactly one such file; anything else still goes to Codex. The setting also adds a Response files button listing the files of the last answer, and a Dock button that places the preview beside the terminal on a wide screen. With it off, every click goes to Codex as before.
**Prompt uploads take `.html` and `.htm` (#869, from #868).** AI tools write specs and reports as HTML as often as Markdown, and attaching one is now the same as attaching a `.md`: paste, drop and every Attach picker take it, it is checked like the rest of the text family, and it is saved to `.codeman-uploads/`. It is stored to be read, never rendered on Codeman's own origin. Scripts (`.sh`, `.py`, `.js`) are still refused.
**Fixes.**
- **Markdown table columns no longer shrink to one letter per line (#866).** In the response viewer and the file preview, a narrow column next to a long one wrapped its text a letter at a time. Cells now wrap between words, while inline code, links and paths in a cell still break where needed.
- **The installer gets past sudo in a headless run (#863).** With a working passwordless sudo and no terminal (`su - user -c`, cron, a CI runner, cloud-init), the installer stopped at "Failed to obtain sudo privileges". It now checks that `/dev/tty` can be opened before reading from it.
- **Mac app: a server tab can be dragged into the last place.** Dragging a tab as far right as it goes left it one place short of the end.
**Fixes applied while landing.** The proxy secret is also removed from Node's raw header list, not only from the parsed headers (#854). With a preview open, switching Codex files on or off now shows or hides its Dock button at once, and the click on an underlined file name is behind that setting too (#850). The Chat / Terminal switch is off by default (#859).
**Docs.** A Japanese README (#860), linked from the English and Chinese ones; an npm release moves every translated README aside so npmjs.com keeps showing the English one.
## 1.52.0
### Minor Changes
+5 -5
View File
@@ -52,7 +52,7 @@ Uses [Semantic Versioning](https://semver.org/) (`MAJOR.MINOR.PATCH`) via `@chan
When the user says **COM** (`COM` = patch, `COM minor`, `COM major`): **Read [`docs/releasing.md`](docs/releasing.md) and follow every step in order**; never improvise a release from memory. It covers the changeset, `npm run version-packages`, the `**Version**` line below, the branch check and explicit-path commit, deploy, the getcodeman.com badge, watching BOTH CI workflows, the MCP registry publish, and the Discussions announcement.
**Version**: 1.52.0 (must match `package.json`)
**Version**: 1.52.1 (must match `package.json`)
## Project Overview
@@ -186,7 +186,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
**Docker Compose deployment** (`docker/`): Codeman runs in a container and spawns Docker cases as **SIBLING** containers via the host socket, never nested. `resolveDockerDaemonMountSource()` maps HOME bind sources into the daemon's namespace (`CODEMAN_DOCKER_HOST_HOME`); `CODEMAN_CASES_PATH` makes workspaces resolve to the same absolute path on both sides. ⚠️ `CODEMAN_CASES_PATH` must move every consumer: resolve it only via `config/cases-dir.ts`. ⚠️ `.dockerignore` matches whole paths: keep `**/.env` or `docker/.env` secrets ship in the image. ⚠️ Long-form binds create missing sources ROOT-OWNED: `Start-Codeman.sh` pre-creates them, and `docker/entrypoint.sh` (root, `cap_add: [CHOWN, DAC_OVERRIDE, KILL, SETGID, SETUID]` against `cap_drop: ALL`, `KILL` for tini; pinned by the test) fixes ownership then drops to `PUID:PGID` via `setpriv`, never re-owning foreign dirs. ⚠️ Append `/opt/codeman-cli` and `~/.local/bin` to `PATH`, never prepend. ⚠️ `server.Dockerfile`, the compose file and `.env.example` feed the self-updater's environment gate (`docs/docker-self-update.md`). → [architecture-invariants#docker-compose-deployment](docs/architecture-invariants.md#docker-compose-deployment), `docs/docker-compose.md`
**CLI registry** (`src/config/cli-registry/`): every run mode is a `CliEntry` (discovery, launch argv template, env handling, `capabilities`, and the `overlays` behind remote/docker pane commands). **No code outside `stock.ts` may branch on a CLI id**: use a capability field or a NAMED PROFILE (`profiles.ts`); `test/cli-registry-no-id-branching.test.ts` and `test/frontend-cli-no-id-branching.test.ts` enforce it. ⚠️ Config holds typed argv tokens, never shell text; literals are validated at LOAD time and a bad one rejects the whole entry. ⚠️ Keep `external`, `hooks` and `altScreen` independent; never derive one from another. ⚠️ Config regexes (`discovery.version.regex`, `capabilities.workDetect.workingLine`, `capabilities.workDetect.watchingLine`, `capabilities.workDetect.awaitingLine`, `capabilities.workDetect.blockedLine`, `capabilities.workDetect.composerFooterLine`, `capabilities.workDetect.composerPopupLine`, `capabilities.modelDetect.screenLine`) must compile through `compileVersionRegex()`. ⚠️ `privilegedParams[].param` names a LAUNCH PARAM, not the legacy `<Mode>Config` field (bridged only by `launch.legacyConfigAliases`); a wrong name silently clamps nothing. ⚠️ Resolve the registry AT CALL TIME, never in a module-level const. ⚠️ Remote claude/omp arms of `buildRemoteLaunchCommand` are not covered by the pane-command golden. `~/.codeman/clis.json` overrides entries. It is WRITTEN only by the opt-in CLI management routes (`cliManagementEnabled`, default OFF; `/api/clis`, `cli-registry-routes.ts`), and only through `mutateRegistryFile()` in `registry-writer.ts` (the one exception: a config-backup restore of `clis.json`, which then calls `reloadCliRegistry()`), which serializes mutations and refuses (409) a file that does not parse or has group/world permission bits rather than overwriting it. Importing the registry still writes nothing. → [architecture-invariants#cli-registry](docs/architecture-invariants.md#cli-registry), `docs/cli-registry.md`
**CLI registry** (`src/config/cli-registry/`): every run mode is a `CliEntry` (discovery, launch argv template, env handling, `capabilities`, and the `overlays` behind remote/docker pane commands). **No code outside `stock.ts` may branch on a CLI id**: use a capability field or a NAMED PROFILE (`profiles.ts`); `test/cli-registry-no-id-branching.test.ts` and `test/frontend-cli-no-id-branching.test.ts` enforce it. ⚠️ Config holds typed argv tokens, never shell text; literals are validated at LOAD time and a bad one rejects the whole entry. ⚠️ Keep `external`, `hooks` and `altScreen` independent; never derive one from another. ⚠️ Config regexes (`discovery.version.regex`, `capabilities.workDetect.workingLine`, `capabilities.workDetect.watchingLine`, `capabilities.workDetect.awaitingLine`, `capabilities.workDetect.blockedLine`, `capabilities.workDetect.composerFooterLine`, `capabilities.workDetect.composerPopupLine`, `capabilities.modelDetect.screenLine`) must compile through `compileVersionRegex()`. ⚠️ `privilegedParams[].param` names a LAUNCH PARAM, not the legacy `<Mode>Config` field (bridged only by `launch.legacyConfigAliases`); a wrong name silently clamps nothing. ⚠️ Resolve the registry AT CALL TIME, never in a module-level const. ⚠️ Remote claude/omp arms of `buildRemoteLaunchCommand` are not covered by the pane-command golden. ⚠️ A server that runs as root (uid 0) starts a LOCAL claude without the bypass flag, which Claude Code refuses under root (a dead pane on every session): the swap is the enum param's `rootValue` (`root-launch.ts`, pure), asked through `serverRunsAsRoot()` at call time by `serverRootSpawnOptions()` (both tmux launches) and `buildPermissionArgs()` (direct PTY, one-shot) only, logged once per launch; never an id branch, never `IS_SANDBOX`, never for a remote or Docker launch, and not root stays byte-identical (`test/root-launch.test.ts`). `~/.codeman/clis.json` overrides entries. It is WRITTEN only by the opt-in CLI management routes (`cliManagementEnabled`, default OFF; `/api/clis`, `cli-registry-routes.ts`), and only through `mutateRegistryFile()` in `registry-writer.ts` (the one exception: a config-backup restore of `clis.json`, which then calls `reloadCliRegistry()`), which serializes mutations and refuses (409) a file that does not parse or has group/world permission bits rather than overwriting it. Importing the registry still writes nothing. → [architecture-invariants#cli-registry](docs/architecture-invariants.md#cli-registry), `docs/cli-registry.md`
**External CLI modes (OpenCode, Codex, Gemini, Antigravity, Pi, Grok, DeepSeek, OMP, Copilot, jcode)**: `isExternalCliMode()` in `session.ts` gates Claude-specific behavior off (Ralph tracker, BashToolParser, token parsing, ❯ readiness; readiness is output stabilization); work detection is per-CLI `capabilities.workDetect` data, not this gate. All ten **require tmux, no direct PTY fallback** (secrets go via socket-scoped `tmux setenv`, never the command line). ⚠️ `run*()` in `session-ui.js` MUST unwrap the `{success,data}` envelope. ⚠️ **Codex uses predictive write-through echo, never the buffer overlay**: `_predictHookOnData` must never `return` (wire path stays byte-identical), and flushed text and a bracketed paste must go out as separate delayed writes. ⚠️ **Pi**: no bypass flag, never invent one; `approveProjectTrust` executes repo code, so it is in the clamp's **materialize** branch; never wire `--api-key`. ⚠️ **Grok**: `alwaysApprove` is stripped for non-granted owners (only-if-sent). ⚠️ **DeepSeek**: the agent is a PROFILE (Run gates on `isDeepSeekRunnable()`); the permission switch is the `DSH_PERMISSION_MODE` env var, so `clampEnvOverridesForOwner()` must DROP `DSH_PERMISSION_MODE`, `DSH_HOME` and `DEEPSEEK_BASE_URL` for non-granted owners; `hooksAvailableForMode()` is per-SESSION for it (pass `sessionHookOptions(session)`) and is never a stand-in for `mode === 'claude'`; answers come from `deepseek-transcript.ts`, paired by header `cwd` + boot window, never newest-mtime. ⚠️ **OMP**: `OMP_AUTH_BROKER_URL`/`_TOKEN` are clamped the same way. ⚠️ **Copilot**: `allowAll` (`--yolo`) is a `privilegedParam` and `COPILOT_HOME`/`COPILOT_ALLOW_ALL`/`COPILOT_PROVIDER_*`/`COPILOT_MODEL` are privileged env keys, and so is every other `COPILOT_*` variable the CLI reads that switches approvals, runs code with no approval row or sends its sign-in token elsewhere (the 1.0.98 list is in `stock.ts`; the prefix admits whatever a later release adds, so re-read the bundle whenever the measured version moves); the resume id must start with a letter or digit (`path-segment`), since `--resume`'s value is optional and `--resume --yolo` would otherwise make `--yolo` its own flag; `--name` is dropped next to `--resume`/`--continue` (Copilot refuses the pair); its mouse DECSETs are stripped (`strip-mux-and-mouse`) so a drag selects and the wheel is forwarded by `_shouldForwardWheelToApp` while `cliMouseTracking` is on; `composerReadyMark` is the footer hint `/ commands · ? help`, NOT `❯` (the folder-trust dialog draws `❯ 1. Yes`); `last-response` reads the pane's visible screen (`transcriptNeedsScreenCapture`) through a per-CLI `PANE_DIALECTS` row, because its stream is cursor moves, not lines (a prompt row scrolled off by a tall answer reads as the answer's tail unless a banner/trust dialog is on screen, and typed composer text is not a prompt); Docker seeds no Copilot credential (`config.json` holds a plain-text token without a keyring). ⚠️ **jcode**: every pane is a client of ONE shared per-user daemon and the tools run in the daemon with ITS env, so jcode gets no agent skill and no `JCODE_*` envOverrides prefix (a per-session value would act as another session or reach every one); `last-response` is an honest empty (external + `transcript: 'none'`, never the segmenter or the Claude scan); ⚠️ that daemon is a descendant of whichever pane started it, so `capabilities.sharedDaemon` makes `killSession` spare descendants outside the pane's process group (`descendantsInPaneGroup()`, `proc-tree.ts`), or closing that one tab cuts every other jcode session off; it resolves through the generic registry resolver, with no per-CLI resolver module (`docs/jcode-integration.md`). → [architecture-invariants#external-cli-modes-opencode-codex-gemini-antigravity-pi-grok-deepseek-omp](docs/architecture-invariants.md#external-cli-modes-opencode-codex-gemini-antigravity-pi-grok-deepseek-omp)
@@ -239,7 +239,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
**Attachments** (live external document references; all wiring in `file-routes.ts`): a **registry** maps a stable `attachmentId` to a realpath-resolved, extension-allowlisted absolute path, so browser requests never carry arbitrary absolute paths. ⚠️ The **magic-link scanner** (`codeman://attach?...` in terminal output) is **prompt-injectable**, so its scan path is force-confined to the session workspace; a hostile prompt could otherwise exfiltrate arbitrary host files over SSE. The security gate is an extension **allowlist**, not a blocklist. `document-conversion-limiter.ts` caps converter spawns globally: without it, N large docs detected at once fork N multi-minute processes, which is a resource-exhaustion vector. → [architecture-invariants#attachments](docs/architecture-invariants.md#attachments)
**Prompt uploads** (`POST /api/sessions/:id/paste-image`: clipboard paste, drop, the Compose Attach key and the phone toolbar's Attach button; client wiring in `image-input.js` and `keyboard-accessory.js`): a pick is written to `<workspace>/.codeman-uploads/` and its path lands on the prompt as unsent text. The folder is IN the workspace because that is the only path identical for a local and a container agent, FLAT because `<workspace>/.codeman/` would BE the data dir when the workspace is the home directory, and self-ignoring through a `.gitignore` of `*` written ONCE with `wx` (a file already there is the user's and is never overwritten; the user's own ignore file is never touched). ⚠️ The directory names live ONLY in `paste-image-gc.ts` (`UPLOAD_DIR_NAMES`): the pre-move `.claude-images/` receives nothing but stays readable for one release, so the GC sweep and the delete cleanup (through `uploadDirs()`) and the image watcher's ignore filter (reading the names) cover BOTH; retire the legacy entry there, never by hand elsewhere. ⚠️ `uploadDirs()` is async and probes the workspace BOUNDED first (`probePathKind()`, the #516 rule: an `unknown` path is skipped, never touched; the sweep keeps the stall cap and the delete passes `pastCap`), then returns only REAL directories (lstat, so a planted symlink is never one), none that is or contains `getDataDir()` (one strictly inside it only holds uploads and is listed), and none for a remote session, since both consumers delete; the check is made at list time, and the same-user race after it is accepted. Images are buffered in memory under `MAX_PASTE_IMAGE_BYTES` (50MB) after a client-side canvas re-encode; a DOCUMENT (pdf, docx, pptx, xlsx, zip and the text family txt/md/csv/tsv/json/log/yaml/yml/xml; the curated `ALLOWED_DOCUMENT_EXTS`, never `SUPPORTED_ATTACHMENT_EXTENSIONS` or `EDITABLE_EXTENSIONS`, which carry sh/py/js/html) is admitted by its name's extension alone, buffered like an image, judged on its bytes by the same fail-closed `imageMagicMatchesExt` (`%PDF-`, `PK\x03\x04` for the OOXML trio and zip, UTF-8 without a NUL byte for text: a SIGNATURE or ENCODING check, never a structure or content check, so generic zip bytes pass as `.docx` and a script renamed `.txt` is text; the sh/py/js/html exclusion is a SCOPE choice by extension, keeping the server from storing what it would serve or run, not a content filter: the agent can already write any of those) and saved as `paste-<ts>-<hex>-<stem><ext>` with a sanitized stem (`[A-Za-z0-9._-]`, 40 chars, a wholly non-ASCII name leaves no stem; the `paste-` prefix is what the GC matches). A VIDEO is never buffered: `?kind=video` streams it to disk under `MAX_PASTE_VIDEO_BYTES` (1GB, env `CODEMAN_MAX_PASTE_VIDEO_BYTES`), judges the container on the first 12 bytes as they arrive (ISO BMFF / QuickTime atom, EBML for webm, Ogg for ogv; a mislabeled body is drained unwritten from there, never parked on disk first) and unlinks on any failure, a dead transfer included. ⚠️ The flag is the ONLY way onto that path and admits video types alone (the registry's `VIDEO_ATTACHMENT_EXTENSIONS`, single-sourced: mp4/webm/mov/m4v/ogv, so an uploaded video is one the file viewer can also play; 3gp/mkv are out, since a phone's camera roll produces neither and neither previews), so an image can never ride the larger cap through memory; without it the route is byte-identical to the image-only version. Busboy takes its size limit before the part is seen, which is why the choice rides the URL and not the file. ⚠️ A video draws on its OWN per-(IP, session) rate bucket (`consumeVideoToken`, 3/min) beside the image bucket (`consumePasteToken`, 30/min): at 1GB each, 30/min would be 30GB of disk a minute, so the lower rate bounds it to 3GB; the image path keeps the 30/min bucket and is unchanged without the flag. A remote (SSH) session is refused (400) before any disk touch: its `workingDir` is the remote path, so the file would land on THIS host where the agent cannot read it (Docker is fine, the workspace is bind-mounted at the same absolute path). ⚠️ A live session's workspace can still sit on a network mount that stopped answering, so the route probes it BOUNDED (`probePathKind(session.workingDir, { pastCap: true })`, the #516 rule) before the first disk touch and refuses an `unknown` mount through `describeUnknownPath()` (OPERATION_FAILED), the way session create does, so a mount already unreachable cannot freeze a libuv worker on every upload (a mount that dies after the probe is the same residual race create accepts). ⚠️ Dispatch mirrors the client: an `image/*` MIME takes the IMAGE path whatever the name says (a GIF named `animation.txt` stays a GIF), a document extension takes the document branch, and anything else takes the image path exactly as before, where the HEIC sniff still recovers a HEIC under a generic name; a foreign extension with no image MIME gets its `Unsupported file type` 400 only AFTER that sLine truncated
**Prompt uploads** (`POST /api/sessions/:id/paste-image`: clipboard paste, drop, the Compose Attach key and the phone toolbar's Attach button; client wiring in `image-input.js` and `keyboard-accessory.js`): a pick is written to `<workspace>/.codeman-uploads/` and its path lands on the prompt as unsent text. The folder is IN the workspace because that is the only path identical for a local and a container agent, FLAT because `<workspace>/.codeman/` would BE the data dir when the workspace is the home directory, and self-ignoring through a `.gitignore` of `*` written ONCE with `wx` (a file already there is the user's and is never overwritten; the user's own ignore file is never touched). ⚠️ The directory names live ONLY in `paste-image-gc.ts` (`UPLOAD_DIR_NAMES`): the pre-move `.claude-images/` receives nothing but stays readable for one release, so the GC sweep and the delete cleanup (through `uploadDirs()`) and the image watcher's ignore filter (reading the names) cover BOTH; retire the legacy entry there, never by hand elsewhere. ⚠️ `uploadDirs()` is async and probes the workspace BOUNDED first (`probePathKind()`, the #516 rule: an `unknown` path is skipped, never touched; the sweep keeps the stall cap and the delete passes `pastCap`), then returns only REAL directories (lstat, so a planted symlink is never one), none that is or contains `getDataDir()` (one strictly inside it only holds uploads and is listed), and none for a remote session, since both consumers delete; the check is made at list time, and the same-user race after it is accepted. Images are buffered in memory under `MAX_PASTE_IMAGE_BYTES` (50MB) after a client-side canvas re-encode; a DOCUMENT (pdf, docx, pptx, xlsx, zip and the text family txt/md/csv/tsv/json/log/yaml/yml/xml/html/htm; the curated `ALLOWED_DOCUMENT_EXTS`, never `SUPPORTED_ATTACHMENT_EXTENSIONS` or `EDITABLE_EXTENSIONS`, which carry sh/py/js) is admitted by its name's extension alone, buffered like an image, judged on its bytes by the same fail-closed `imageMagicMatchesExt` (`%PDF-`, `PK\x03\x04` for the OOXML trio and zip, UTF-8 without a NUL byte for text: a SIGNATURE or ENCODING check, never a structure or content check, so generic zip bytes pass as `.docx` and a script renamed `.txt` is text; the sh/py/js exclusion is a SCOPE choice by extension, keeping the server from storing what an agent could run, not a content filter: the agent can already write any of those; html/htm are admitted as AI-written specs and reports, the same job as a .md, and stay inert because file-raw serves them as `application/octet-stream` + `nosniff` and html-view refuses a page under a dot-directory such as `.codeman-uploads`) and saved as `paste-<ts>-<hex>-<stem><ext>` with a sanitized stem (`[A-Za-z0-9._-]`, 40 chars, a wholly non-ASCII name leaves no stem; the `paste-` prefix is what the GC matches). A VIDEO is never buffered: `?kind=video` streams it to disk under `MAX_PASTE_VIDEO_BYTES` (1GB, env `CODEMAN_MAX_PASTE_VIDEO_BYTES`), judges the container on the first 12 bytes as they arrive (ISO BMFF / QuickTime atom, EBML for webm, Ogg for ogv; a mislabeled body is drained unwritten from there, never parked on disk first) and unlinks on any failure, a dead transfer included. ⚠️ The flag is the ONLY way onto that path and admits video types alone (the registry's `VIDEO_ATTACHMENT_EXTENSIONS`, single-sourced: mp4/webm/mov/m4v/ogv, so an uploaded video is one the file viewer can also play; 3gp/mkv are out, since a phone's camera roll produces neither and neither previews), so an image can never ride the larger cap through memory; without it the route is byte-identical to the image-only version. Busboy takes its size limit before the part is seen, which is why the choice rides the URL and not the file. ⚠️ A video draws on its OWN per-(IP, session) rate bucket (`consumeVideoToken`, 3/min) beside the image bucket (`consumePasteToken`, 30/min): at 1GB each, 30/min would be 30GB of disk a minute, so the lower rate bounds it to 3GB; the image path keeps the 30/min bucket and is unchanged without the flag. A remote (SSH) session is refused (400) before any disk touch: its `workingDir` is the remote path, so the file would land on THIS host where the agent cannot read it (Docker is fine, the workspace is bind-mounted at the same absolute path). ⚠️ A live session's workspace can still sit on a network mount that stopped answering, so the route probes it BOUNDED (`probePathKind(session.workingDir, { pastCap: true })`, the #516 rule) before the first disk touch and refuses an `unknown` mount through `describeUnknownPath()` (OPERATION_FAILED), the way session create does, so a mount already unreachable cannot freeze a libuv worker on every upload (a mount that dies after the probe is the same residual race create accepts). ⚠️ Dispatch mirrors the client: an `image/*` MIME takes the IMAGE path whatever the name says (a GIF named `animation.txt` stays a GIF), a document extension takeLine truncated
**File-path links (terminal + chat)**: a path an agent prints is clickable on BOTH surfaces and opens the file-preview overlay. ⚠️ ONE pattern (`FILE_PATH_LINK_PATTERN` / `absoluteFilePathPattern()` in constants.js) feeds the xterm link provider AND `_linkifyFilePaths()`, a fresh instance per call (`lastIndex`). Both call `findFilePathLinks()`, which reserves spaced-path spans first (an unlinkable one only while its last word holds a `/`; any label, before an absolute or relative path, must be an explicit path label, prose after that label stays out, and an earlier connective or verb such as `and` or `has` (`SPACED_PATH_PROSE_WORD`) makes any candidate prose; rules and trade-offs in the architecture-invariants paragraph linked below), then adds rooted, `~/`, relative and folder paths without overlapping a reservation, earlier match or URL; a relative path resolves against the pane's live directory `SessionState.paneCwd` when known, else `workingDir` (`relativeResolutionBase()` + `resolveLinkedFilePath`; `paneCwd` is only a BASE, never a confinement root: routing and the file routes still judge against `workingDir`, or against a followed worktree for an absolute path inside it, and remote/docker/direct-PTY/rediscovered sessions never get one, scoped by `paneExitApplies`), `~/` only server-side on the session's host (attachment route), and `terminalPathLine()` joins a path a program hard-wrapped short of the edge. ⚠️ A folder link opens the **folder grid**: `POST /api/sessions/:id/folders` guards + GRANTS the folder (`folder-listing.ts`, own registry, never the 200-capped attachment registry), files come by bare name via `…/folders/:folderId/files/:name/*` through `resolveServableAttachmentPath` plus the same extension/regular-file gate on the symlink's resolved target, so no browser request carries a path; `~/` is refused in a Docker case (the container's home is not this host's). The chat linkifier walks TEXT NODES with DOM APIs, never rebuilds sanitized markup as a string. ⚠️ An out-of-workspace path goes through the ATTACHMENT routes (`POST /api/sessions/:id/attachments` with `notify: false`), never by widening `file-content`/`file-raw` or `file-stream-manager`'s `tail -f` allowlist. The one exception is an absolute path inside a followed worktree outside `workingDir` (`SessionState.outsideWorktree`), which the file routes serve as a second root (see Files panel in a worktree). An ambiguous parenthesised hard wrap is checked only on activation, original first: only a 404 permits a spaced-path lookup, and only a registered alternative is opened; every other original result uses the normal opener, never an attachment-policy gate on workspace files, and hover performs no lookup. ⚠️ `TEXT_ATTACHMENT_EXTENSIONS` IS `EDITABLE_EXTENSIONS` (never a second list), and widening READ must never widen RUN: `html`/`htm`/`svg` stay download-only, other text is inert `text/plain`+`nosniff`. ⚠️ The ONE place HTML renders is `/html-view/<cap>/...` (`html-view-routes.ts`, `html-view-capabilities.ts`): `POST /api/sessions/:id/html-view` mints a capability for the file's own directory, every response carries `Content-Security-Policy: sandbox` WITHOUT `allow-same-origin` (opaque origin even as a top-level tab, so the page can never read Codeman or drive its API) and with NO fetch directive (open network, owner decision 2026-10-13: never restrict it or add `allow-same-origin` without the owner), and only non-dot, asset-allowlisted files under that directory are served (GET/HEAD only; capabilities revoked with the web-tab ones on logout). That tree is served recursively, so minting is refused for a hidden directory or a broad root (`isBroadHtmlViewRoot`); the preview renders by default and the **Page** pill (or a refused mint) falls through to the source view and its Edit button. Never serve HTML same-origin anywhere else. Tests: `test/routes/html-view-routes.test.ts`. Media extensions are single-sourced in `attachment-registry.ts`. ⚠️ **XLSX previews parse in the BROWSER**, never on the server; the admission limits that keep a hostile workbook from freezing the worker live in `src/web/CLAUDE.md` (Spreadsheet preview). → [architecture-invariants#file-path-links-terminal--response-viewer](docs/architecture-invariants.md#file-path-links-terminal--response-viewer)
@@ -273,7 +273,7 @@ The terminal provider scans `terminalLinkLine()`, which extends `terminalPathLin
**Web tabs** (dashboard URLs as tabs): a saved URL renders as a tab beside sessions, **NOT a `SessionMode`**, and is proxied through Codeman's own origin (`/webview/<cap>/...`). ⚠️ The proxy is NOT an API surface: its capability-based auth exemption stays fenced to safe methods and non-route paths (`test/webview-auth-exemption.test.ts`). ⚠️ Iframes omit `allow-same-origin` unless `trusted`, and `Authorization`/`codeman_session` are stripped upstream in both modes. ⚠️ **Egress guard**: link-local and cloud-metadata targets are refused at save time, by a sync hostname check at each connect (IP literals skip DNS), AND on the resolved address (`webview-egress.ts`); use the `undici` package's own `fetch` + `Agent`, never Node's global fetch. ⚠️ Loopback links in agent output auto-open as proxied web tabs (`openLinkThroughWebTabIfLoopback`), but never auto-route `*.localhost` (prompt-injectable DNS). Capabilities are revoked on logout (`revokeOwner`). → [architecture-invariants#web-tabs](docs/architecture-invariants.md#web-tabs), `docs/web-tabs.md`
**Multi-user mode** (opt-in `--multiuser` / `CODEMAN_MULTIUSER=1`, OFF by default): named users with scrypt-hashed passwords in `~/.codeman/users.json`. Gated everywhere by `isMultiUserMode()`; when OFF, behavior is byte-identical to single-user because every scoping helper short-circuits. ⚠️ **Not a security boundary at the agent layer**: every session still runs as the SAME OS account. This separates WORKSPACES; it does not sandbox users (Docker cases are the isolation story). Ownership threads through `Session.owner` and is enforced in `findSessionOrFail`, list endpoints, SSE routing (fail-closed), WS, search, and file-preview. ⚠️ `settings.json` is ONE server-wide file, so every write to it is admin-only (`PUT /api/settings`, `/api/execution/model-config`, `/api/cases/order`, plus `PUT /api/config`: 403 `FORBIDDEN` before parsing), a non-admin's quick-start/Ralph start skips `lastUsedCase`, its GET hides `voiceSettings.apiKey`/`caseOrder`/`lastUsedCase`/`lastPickedCase`/`caseSettings` from a non-admin (`settingsForNonAdmin`), and the browser skips those writes for a non-admin via `_settingsReadOnly()` (settings-ui.js; also true once a write came back 403 `FORBIDDEN`, since `/api/me` can be slow or fail; their run mode and respawn presets stay per-device, `_applyOwnSettings`) (`test/routes/system-routes-settings-admin-only.test.ts`). System ops are admin-only too (`/api/system/update`, `/api/system/span-displays`, `/api/tunnel/qr/regenerate`, `/api/cleanup-state`), and a non-admin's `/api/auth/revoke` revokes only their own logins (`test/routes/system-routes-system-ops-admin-only.test.ts`). → [architecture-invariants#multi-user-mode](docs/architecture-invariants.md#multi-user-mode), `docs/multi-user-plan.md`
**Multi-user mode** (opt-in `--multiuser` / `CODEMAN_MULTIUSER=1`, OFF by default): named users with scrypt-hashed passwords in `~/.codeman/users.json`. Gated everywhere by `isMultiUserMode()`; when OFF, behavior is byte-identical to single-user because every scoping helper short-circuits. ⚠️ **Not a security boundary at the agent layer**: every session still runs as the SAME OS account. This separates WORKSPACES; it does not sandbox users (Docker cases are the isolation story). Ownership threads through `Session.owner` and is enforced in `findSessionOrFail`, list endpoints, SSE routing (fail-closed), WS, search, and file-preview. ⚠️ `settings.json` is ONE server-wide file, so every write to it is admin-only (`PUT /api/settings`, `/api/execution/model-config`, `/api/cases/order`, plus `PUT /api/config`: 403 `FORBIDDEN` before parsing), a non-admin's quick-start/Ralph start skips `lastUsedCase`, its GET hides `voiceSettings.apiKey`/`caseOrder`/`lastUsedCase`/`lastPickedCase`/`caseSettings` from a non-admin (`settingsForNonAdmin`), and the browser skips those writes for a non-admin via `_settingsReadOnly()` (settings-ui.js; also true once a write came back 403 `FORBIDDEN`, since `/api/me` can be slow or fail; their run mode and respawn presets stay per-device, `_applyOwnSettings`) (`test/routes/system-routes-settings-admin-only.test.ts`). System ops are admin-only too (`/api/system/update`, `/api/system/span-displays`, `/api/tunnel/qr/regenerate`, `/api/cleanup-state`), and a non-admin's `/api/auth/revoke` revokes only their own logins (`test/routes/system-routes-system-ops-admin-only.test.ts`). **Trusted reverse-proxy sign-in** (experimental, opt-in `CODEMAN_TRUSTED_PROXY_SECRET_FILE`, `src/config/trusted-proxy.ts`): a same-host authenticating proxy signs requests in via `X-Codeman-Proxy-Secret` + `X-Codeman-User`. ⚠️ Never read or forward request headers ahead of the first auth hook (it deletes those two from every request), and never re-read the secret from the environment (the settings are read once and both variables deleted, since sessions inherit Codeman's env; a setup that cannot be used stops the start). → [architecture-invariants#multi-user-mode](docs/architecture-invariants.md#multi-user-mode), `docs/multi-user-plan.md`
**Away digest**: `GET /api/away-digest` aggregates what happened while you were away from the lifecycle log, run-summary events, live sessions, token stats, and recent subagents. Pure aggregator in `web/away-digest.ts`. ⚠️ Returns `{success:true,digest}`, a legacy raw-ish shape consistent with the other raw GET handlers in `system-routes.ts`; frontend and tests read `.digest`. → [architecture-invariants#away-digest](docs/architecture-invariants.md#away-digest)
@@ -303,7 +303,7 @@ The terminal provider scans `terminalLinkLine()`, which extends `terminalPathLin
| **CSRF / Origin** | Always-on cross-site Origin guard on state-changing requests. **A missing Origin is allowed** so curl/CLI and hooks keep working. ⚠️ The body parser keeps `text/plain` RAW; auto-JSON-parsing it enabled simple-request CSRF |
| **QR Auth** | Single-use 6-char tokens (60s TTL) for tunnel login. See `docs/qr-auth-plan.md` |
| **Sessions** | 24h cookie (`codeman_session`), auto-extend, device context audit |
| **Rate limit** | 10 failed auth/IP → 429 (15min decay). Multi-user mode instead checks 50/IP (`AUTH_IP_FAILURE_MAX`) and 10 per (username, IP) BEFORE the password, so past either even a correct password from that IP waits (the account still logs in from another IP), plus 10 per username AFTER it (429 to wrong guesses from any IP, never to a correct password). A request with NO `Authorization` header (or an empty one, which carries no guess either) is never counted and always gets the 401 challenge (a 429 never re-prompts a browser); a malformed one is counted. QR and hook-secret have separate buckets, so neither can lock out login |
| **Rate limit** | 10 failed auth/IP → 429 (15min decay). Multi-user mode instead checks 50/IP (`AUTH_IP_FAILURE_MAX`) and 10 per (username, IP) BEFORE the password, so past either even a correct password from that IP waits (the account still logs in from another IP), plus 10 per username AFTER it (429 to wrong guesses from any IP, never to a correct password). A request with NO `Authorization` header (or an empty one, which carries no guess either) is never counted and always gets the 401 challenge (a 429 never re-prompts a browser); a malformed one is counted. QR, hook-secret and the trusted-proxy secret (multi-user, opt-in) have separate buckets, so none of them can lock out login |
| **Hook bypass** | `/api/hook-event` + `/api/status-telemetry` skip Basic auth (localhost-only, schema-validated), but when auth is active the loopback bypass requires `X-Codeman-Hook-Secret` **unconditionally** (Codeman cannot detect a user's own loopback reverse proxy) |
| **Lost-frame page** | The THIRD unauthenticated 200, beside the two hook routes, and the only one decided by request headers alone: a `GET`/`HEAD` carrying `Sec-Fetch-Dest: iframe\|frame`, `Accept: text/html` and mode `navigate` (or none), for a path that is NOT a registered route (never `/api/`, `/ws/`, `/q/`), is answered BEFORE the credential checks with the static web-tab recovery page (`lostWebviewFramePage`: no reflected input, `default-src 'none'` plus its own script hash, `no-store`). `/` is the one registered route also admitted, only when the request carries neither `codeman_session` nor `Authorization` (nothing in Codeman frames its own root; a sandboxed frame has neither), since the landing page masks to exactly `/` and its reload otherwise rendered Codeman inside the web tab. ⚠️ A non-browser client can set those headers, so an unauthenticated caller can tell a registered route (401) from a non-route (200) and enumerate the route table; accepted, the routes are public in `docs/api-reference.md`. Pinned by `test/webview-auth-exemption.test.ts` + `test/webview-lost-root-frame.test.ts` |
| **Tunnel** | Enabling a tunnel **refuses** without a login (`CODEMAN_PASSWORD` or multi-user mode) unless exposure is acknowledged via `CODEMAN_ALLOW_UNAUTHENTICATED_TUNNEL=1` / `--allow-unauthenticated-tunnel` or the per-request `acknowledgeUnauthTunnel:true` action field (never persisted). `CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK` acknowledges the BIND only and never satisfies this guard (#706: `install.sh` writes it for every passwordless LAN install). The authorization is decided ONCE per request, running or not, and required again at the `start()` site: the settings-file awaits between them let a concurrent stop land, and an unauthorized enable never writes `tunnelEnabled:true`. With no login the browser asks before every enable (welcome link, tunnel panel, App Settings save that turns it on) through ONE helper, `_confirmTunnelEnable()` (settings-ui.js), which reads `loginConfigured` from `GET /api/tunnel/status` (computed in the route by the guard's own test, never in `TunnelManager`); the 403 handler is the fallback when that read fails |
+1323
View File
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -26,7 +26,7 @@
</p>
<p align="center">
<strong>English</strong> &bull; <a href="README.zh-CN.md">简体中文</a>
<strong>English</strong> &bull; <a href="README.zh-CN.md">简体中文</a> &bull; <a href="README.ja.md">日本語</a>
</p>
<p align="center">
@@ -765,6 +765,7 @@ The web UI remains the primary surface; see **[docs/tui.md](docs/tui.md)** for t
| `Alt/Option+[` / `Alt/Option+]` | Previous / next session |
| `Alt/Option+1`-`Alt/Option+9` | Switch to tab N (physical keys, so macOS Option layouts work) |
| `Alt/Option+B` | Collapse / expand the session sidebar (sidebar layout only) |
| `Alt/Option+Shift+C` | Switch a local or Docker Claude session between Chat and Terminal view (not on phones; see [Settings Reference](docs/wiki/Settings-Reference.md)) |
| `Ctrl+Shift+{` / `Ctrl+Shift+}` | Move active tab left / right |
| `Ctrl/Cmd+C` | Copy selection, or interrupt when nothing is selected |
| `Ctrl+Shift+C` | Copy selection (never interrupts) |
+2 -1
View File
@@ -15,7 +15,7 @@
</p>
<p align="center">
<a href="README.md">English</a> &bull; <strong>简体中文</strong>
<a href="README.md">English</a> &bull; <strong>简体中文</strong> &bull; <a href="README.ja.md">日本語</a>
</p>
<p align="center">
@@ -762,6 +762,7 @@ Web UI 仍是主要界面;完整指南见 **[docs/tui.md](docs/tui.md)**(英
| `Alt/Option+[` / `Alt/Option+]` | 上一个 / 下一个会话 |
| `Alt/Option+1`–`Alt/Option+9` | 切换到第 N 个标签(按物理键位,macOS Option 布局也适用) |
| `Alt/Option+B` | 折叠 / 展开会话侧边栏(仅侧边栏布局) |
| `Alt/Option+Shift+C` | 在聊天视图和终端视图之间切换本地或 Docker 的 Claude 会话(手机上不可用;见 [Settings Reference](docs/wiki/Settings-Reference.md)) |
| `Ctrl+Shift+{` / `Ctrl+Shift+}` | 将当前标签左移 / 右移 |
| `Ctrl/Cmd+C` | 复制选中内容;未选中时中断代理 |
| `Ctrl+Shift+C` | 复制选中内容(永不中断) |
+2 -2
View File
@@ -3,7 +3,7 @@
"name": "io.github.Ark0N/codeman",
"title": "Codeman",
"description": "Start, prompt and read AI coding agent sessions (Claude Code, Codex, Gemini CLI and more) in Codeman",
"version": "1.52.0",
"version": "1.52.1",
"websiteUrl": "https://getcodeman.com",
"repository": {
"url": "https://github.com/Ark0N/Codeman",
@@ -13,7 +13,7 @@
{
"registryType": "npm",
"identifier": "aicodeman",
"version": "1.52.0",
"version": "1.52.1",
"transport": {
"type": "stdio"
},
+59 -8
View File
@@ -59,10 +59,13 @@ payload return `{ "success": true, "data": {} }`.
> to 600 s. Proxy operators and HTTP clients with a global read timeout need to know
> that before pointing them at Codeman.
⚠️ **A `401` is the one status that is not an envelope.** Authentication is rejected
⚠️ **A `401` is not an envelope.** Authentication is rejected
in a request hook, before any handler runs, and it replies with the bare string
`Unauthorized` (`Unauthorized: hook secret required` on the hook path) plus
`WWW-Authenticate: Basic realm="Codeman"`. There is no `success`, no `error`, and no
`Unauthorized` plus `WWW-Authenticate: Basic realm="Codeman"` (on the hook path it is
`Unauthorized: hook secret required`, without that header). With trusted-proxy sign-in on (experimental,
see [Authentication](#authentication)) the same hook has more plain-text replies: a `401`
without `WWW-Authenticate`, a `403` and a `503` for a refused proxy identity, and a `403`
or `404` for a `/webview/` or `/html-view/` path without a live capability. There is no `success`, no `error`, and no
`errorCode`, because the wrapping hook only wraps object payloads. So a client that
pipes every response straight into a JSON parser dies with a parse error rather than
reporting an auth failure, which is a confusing way to discover that a password is
@@ -601,6 +604,26 @@ request returns. The capture runs synchronous tmux calls on the server; the
| `lines=<n>` | With `full=1` only: read at most `<n>` lines of tmux history above the visible frame. An integer of at least 1, clamped to the configured history limit; absent or malformed, the whole limit (100,000 lines by default), as before. When a bound below the configured limit left older lines in tmux (its `history_size` is deeper), `truncated` is true with `truncationReason: 'tail'`; a byte cap still reports `'capped'`. Without it a full capture reads all of that history before `tail` cuts it, so a client that keeps a fixed number of lines (the tile grid sends its xterm's scrollback plus its rows) should send it. |
| `alt=recording` | With `full=1` only: if the pane is in the alternate screen (a nested tmux, where tmux keeps no history, or any full-screen app such as vim or less while it is open), answer with the visible frame over the byte recording instead (`source: 'mux-visible'`, `tail` applied as without `full=1`). Shells' automatic loads send it. |
## Conversation reads for the chat view
### `GET /api/v1/sessions/:id/last-response?context=full`
With `context=full`, the response carries the whole conversation as `messages`. Each
message read from a Claude transcript has `kind`, `label`, `role`, `text`, `turn` and,
when known, `timestamp`. A prompt the user typed while Claude was working also carries
`queued: true`. That reader also marks the turns that Codeman's prompt-cache
keep-warm sent. The nudge prompt and the reply to it both carry `keepAlive: true`, so a
client can leave them out as the chat view does. A prompt the user queued during that
turn makes the turn theirs, and its later messages carry no flag.
A full read of a Claude transcript also starts a transcript watcher when none runs for
the session. A watcher normally starts at the session's first hook or statusline report,
so a session picked up after a server restart has none until one of those arrives. The
read starts one from the file it found, and the session's `transcript:*` events then flow
mid-turn. After a `/clear`, a read moves a watcher it started itself to the conversation's
new file. It never replaces or moves a watcher that a hook or a statusline report started,
and it starts none for a remote SSH session, whose transcript is not on this host.
## Experimental bounded agent inspection and guarded input
**Experimental:** `codeman agent inspect`, `stage` and `submit`, and their
@@ -892,18 +915,20 @@ Beyond images, the route also accepts documents a user hands an agent to read,
admitted by the name's extension (the Content-Type a phone attaches to a `.md`
or `.csv` is unreliable): the office formats `.pdf`, `.docx`, `.pptx`, `.xlsx`,
`.zip` and the text family `.txt`, `.md`, `.csv`, `.tsv`, `.json`, `.log`,
`.yaml`, `.yml`, `.xml`. A document is buffered under the same 50 MB image cap,
`.yaml`, `.yml`, `.xml`, `.html`, `.htm`. A document is buffered under the same 50 MB image cap,
its bytes are checked against the extension (a magic-number signature, or UTF-8
with no NUL byte for text) and answered 415 on a mismatch (for text, an `error`
saying the file is not UTF-8 text, or UTF-16 text when it opens with a UTF-16
byte order mark, and to save it as UTF-8), and it is saved under
a sanitized stem of its name, so `Q3 report.pdf` is findable as
`paste-<ms>-<hex>-Q3-report.pdf`. A named type that is neither an image nor a
document (a script, an HTML page, a `.sh`) is refused 400 `Unsupported file
document (a script: `.sh`, `.py`, `.js`) is refused 400 `Unsupported file
type`. That refusal is a scope choice, not a security property: `file-raw`
already serves non-media text inert (`text/plain`, `nosniff`), so this just
keeps the server from storing what it would serve or an agent could run, and
html and svg are the ones deliberately kept out.
keeps the server from storing what an agent could run. `.html` and `.htm` are
admitted and stay inert: `file-raw` serves them as `application/octet-stream`
with `nosniff`, and `html-view` refuses a page under a dot-directory such as
`.codeman-uploads`. That leaves svg as the markup type still kept out.
## Listing a directory (`GET /api/v1/sessions/:id/files?lazy=1`)
@@ -1019,7 +1044,8 @@ by the owner's decision the page may load from and send requests to any host), `
`Referrer-Policy: no-referrer` and `Access-Control-Allow-Origin: *`. A `Range`
request is answered with `206` + `Content-Range` (`416` past the end), like
`file-raw`. Every refusal is a plain-text `404 Not found`; with a password set, an
unknown or revoked capability is the auth hook's `401` instead.
unknown or revoked capability is the auth hook's `401` instead. With trusted-proxy sign-in
on it is the hook's plain-text `404`, with no challenge.
## Session lineage (`parentSessionId`)
@@ -1937,6 +1963,24 @@ Optional HTTP Basic (`CODEMAN_USERNAME`/`CODEMAN_PASSWORD`) → opaque
`401 UNAUTHORIZED`; rate-limited requests get `429 RATE_LIMITED`. See
[`security-architecture.md`](security-architecture.md).
**Trusted-proxy sign-in (experimental, multi-user mode, off unless a secret is
configured).** An authenticating reverse proxy on the same host sends
`X-Codeman-Proxy-Secret` and `X-Codeman-User` over loopback, and the request runs as that
existing, enabled account. No cookie is issued, and `GET /api/me` reports
`viaTrustedProxy: true`. The hook's refusals on this path are plain text, not envelopes:
| Status | When |
|---|---|
| `401`, no `WWW-Authenticate` | the secret is wrong, or the request did not arrive over loopback |
| `403` | the secret is right, but there is no username or no enabled account with that name |
| `503` | the user store cannot be read |
| `429` | too many wrong secrets from one address |
With the feature on, a path under `/webview/` or `/html-view/` without a live capability is
answered by the hook before any credential is looked at: plain-text `403` for a web tab,
`404` for an HTML view, no challenge. See
[`security-architecture.md` §10a](security-architecture.md).
## SSE event channel
`GET /api/events` is a Server-Sent Events stream (`text/event-stream`); each
@@ -1946,6 +1990,13 @@ the stable contract — event names are not renamed without a major bump. An
optional `?sessions=<id,...>` filter suppresses only the high-volume terminal
stream; lifecycle/metadata events are delivered to all clients regardless.
### `transcript:update` (the chat view's re-read)
The server broadcasts `transcript:update` (`{ sessionId, timestamp }`) for a session whose
transcript watcher runs, whenever new lines arrive in its transcript. It throttles the event
to one per 750 ms per session. The first update after a quiet spell goes out at once, and a
burst after it collapses into one trailing event.
### `sse:heartbeat` (liveness)
Every 15s the server writes a `sse:heartbeat` frame to every connected client:
+5 -3
View File
@@ -640,6 +640,8 @@ Further detail: the refused egress targets are `169.254.0.0/16`, `fe80::/10`, `f
**Multi-user mode** (opt-in `--multiuser` / `CODEMAN_MULTIUSER=1`, OFF by default; shipped 1.5.0 via PR #161, design `docs/multi-user-plan.md`): named users with individually scrypt-hashed passwords in `~/.codeman/users.json` (via `src/user-store.ts`: atomic 0600 write, short-TTL cache, SERIALIZED read-modify-write so a fire-and-forget `touchLastLogin` can't clobber a concurrent route write, last-admin invariants). Gated everywhere by `isMultiUserMode()` (`src/config/multiuser.ts`); when OFF, behavior is byte-identical to single-user (all scoping helpers short-circuit). ⚠️ **Not a security boundary at the agent layer** — every session still runs as the SAME OS account; this separates WORKSPACES, it does not sandbox users (Docker cases are the isolation story). Auth: a PARALLEL async branch in `middleware/auth.ts` (single-user branch untouched) verifies `username:password` against the store, mints identity-carrying cookies (`AuthSessionRecord` gains `username`/`role`/`mustChangePassword`), decorates `req.authUser` (Fastify augmentation; single-user leaves it undefined and the ownership helpers default to a synthetic admin), enforces a per-username failure bucket + the `mustChangePassword` lockbox. Ownership threads through `Session.owner` (stamped from `req.authUser`/`job.owner` at every `new Session()`, round-tripped via `MuxSession.owner` on recovery); `findSessionOrFail(ctx,id,req)` does a NOT_FOUND owner check; list endpoints + `getLightState` + SSE (`deriveSseHint` routes session-scoped events by owner, fail-closed; machine-level + host-plan telemetry admin-only) + WS + search + file-preview all filter by owner. §6.3 permission policy: non-granted users are forced to `--permission-mode auto` (via `resolveClaudeModeForUser` at all spawn sites, incl. one-shots because `buildPromptArgs` now respects the session mode), and shell mode / cron `launchCommand` require the `canBypassPermissions` grant. Cases live in per-user `~/codeman-users/<name>/cases` (`resolveCasesDir`); a non-admin's `workingDir` is realpath-confined there; host CRUD is admin-only. Admin API `src/web/routes/admin-routes.ts` (`/api/admin/users*`, one-time passwords, audit log `admin-audit.jsonl`) + self-service `/api/me` + `/api/me/password` (`me-routes.ts`); frontend `public/admin-ui.js` (identity boot, change-password modal + interceptor, admin Users tab, and the header **Admin Panel** button `#adminPanelBtn`: ships `btn-admin-panel--hidden`, revealed for admins in multi-user mode, phone-hidden via mobile.css; opens the full Admin Panel modal with user CRUD, per-user permission toggles, and case-folder list/delete via `GET/DELETE /api/admin/users/:username/cases[/:caseName]`; live-refreshes on SSE `admin:usersChanged`, wired in app.js). CLI `codeman users add|passwd|list|rm`. Per-user session cap via `sessionCapacityState`/`sessionCapacityMessage`. Tests: `test/user-store.test.ts`, `test/multiuser-auth.test.ts`, `test/ownership-scoping.test.ts`, `test/admin-routes.test.ts`, `test/admin-ui.test.ts`.
**Trusted reverse-proxy sign-in** (experimental per `docs/versioning-policy.md`; opt-in `CODEMAN_TRUSTED_PROXY_SECRET_FILE` / `CODEMAN_TRUSTED_PROXY_SECRET`, multi-user only; `src/config/trusted-proxy.ts`, `registerTrustedProxyHeaderStrip` + `checkTrustedProxyIdentity` in `middleware/auth.ts`, full rules in `docs/security-architecture.md` §10a): a same-host authenticating proxy (oauth2-proxy, mod_auth_openidc, ...) presents `X-Codeman-Proxy-Secret` + `X-Codeman-User` and the request signs in as that EXISTING, enabled account. ⚠️ The headers are read and DELETED from every request by the first auth hook (right after the Host guard, every auth mode), before any exemption or route: the web-tab relay copies request headers, and must never see the secret. ⚠️ The secret is read ONCE at auth setup (before sessions are restored) and both variables are deleted from `process.env`, since every session inherits Codeman's env; don't add a code path that re-reads them from the env later (the secret file's path is kept in the module for `isSensitivePath`). ⚠️ A configured setup that cannot be used (unreadable, empty or group/other-readable file, short or non-ASCII secret, both variables, single-user mode, rejected header name) STOPS THE START; it is never silently off. The check is step 0 of the multi-user hook, BEFORE the cookie, and fail-closed: once the secret header is present (even empty), a wrong secret / non-loopback `req.ip` (401) or a missing, invalid, unknown or disabled username (403, no challenge) is refused and never falls through to cookie or Basic. The username is matched exactly (`normalizeUsername()` + the username rule, no other transformation); the loopback test is `isLoopbackIp`, shared with the hook-secret bypass. The secret is compared BEFORE the failure bucket (own per-IP `proxySecretFailures`), so a correct secret always passes and only failures are throttled. No cookie is minted. `req.authUser.viaTrustedProxy` skips the `mustChangePassword` lockbox and makes `GET /api/me` report `mustChangePassword: false`. ⚠️ The username header is removed from EVERY request, so `CODEMAN_TRUSTED_PROXY_USER_HEADER` is validated by shape (`X-…` or `Remote-User`, reserved names refused) and a rejected name stops the start; the configured name is also on the web-tab relay's drop list. With the feature configured, a `/webview/` or `/html-view/` request the capability exemptions don't let through is refused with the route's own 403/404 BEFORE the credential checks (`serveRefusedCapabilityPath`), by prefix on a normalised path (`capabilityPrefixOf`), not by token shape: the proxy lets those paths through without its sign-in, so they must never reach the Basic check, prompt or failure bucket. The configured secret file is on the `isSensitivePath` blocklist. Tests: `test/trusted-proxy-auth.test.ts`, `test/sensitive-path.test.ts`.
### Agent-created case marker
**Agent-created case marker** (`src/agent-case-marker.ts`): a case directory `POST /api/quick-start` **creates** for an agent-driven spawn gets a `.codeman-agent-case.json` marker, so the scratch workspaces a long orchestration leaves behind (one per worker, and deleting the session does not remove them) can still be told apart from the user's real projects months later. `GET /api/cases` publishes it as `agentCreated`; `GET /api/cases/agent-created` is the read-only cleanup listing, adding `inUse` (a live session's `workingDir` is that case) and `modifiedAt`; Add Case → Manage badges each one and offers a review-then-delete sweep. The signal is the skill preamble's `X-Codeman-Agent-Origin` header (or an `agentOrigin` body field), falling back to a RESOLVED `parentSessionId` — nothing in the browser UI sets lineage, so a create request naming its spawning session came from an agent by construction, and that fallback is what still labels workers spawned by a stale skill copy.
@@ -918,7 +920,7 @@ Two surfaces do not move with a worktree inside `workingDir`. The Git panel keep
⚠️ **Reads only on request, opt-in all the way down.** `server.ts` builds the `EditHistorySync` and hands it to the routes; its only own calls are `remove` (through `forgetEditHistory`, when the session's persisted record goes), `sweep` (startup) and `flushAll` (shutdown). No hook, no timer, no second watcher. The panel drives every read: `?sync=1` when it opens, and while it is open on that session a debounced (600 ms) re-read after a `transcript:tool_end` of an edit-capable tool (Edit, Write, MultiEdit, NotebookEdit, Bash, Agent, Task, SendUserFile), which the existing `TranscriptWatcher` already broadcasts, or the session's `session:idle` (the end of a turn, via `_onSessionIdle`; it also catches a background subagent that writes after the tool end that started it). Not `transcript:complete`: it fires on a `result` line, which claude's interactive transcript never has. A closed panel reads nothing and keeps no badge. Guarded by the "reads only on request" wiring test in `test/edit-history-sync.test.ts`.
⚠️ **Which transcript** (`resolveClaudeTranscript`). The main transcript is the path the session's `TranscriptWatcher` follows (the hook-reported `transcript_path`), so a session is read from where its claude really writes, whatever its `CLAUDE_CONFIG_DIR`. Without a watcher (server restarted, no hook since), `findClaudeTranscript()` looks for `<claudeSessionId|id>.jsonl` under `claudeProjectsDir(session.claudeConfigDir())`: the session's own override (#255, the same dir the relaunch pin checks), else the server's. A config dir set outside Codeman (a shell profile, a wrapper) is never guessed: until the next hook such a session answers `unavailable` / `no-transcript`, and the panel says so. Subagents are `<main path without .jsonl>/subagents/agent-<id>.jsonl`. A different main file (`/clear`, resume): the previous one, next to it in the same directory, is first read to its end with its subagents (over as many syncs as that takes), then the new one from its end with fresh cursors; the stored entries stay. "Load older" reaches back within the current conversation only, and reads the stored conversation's transcript while the switch is still pending.
⚠️ **Which transcript** (`resolveClaudeTranscript`). The main transcript is the path the session's `TranscriptWatcher` follows (the `transcript_path` a hook or the statusline reported, or the file a full `last-response?context=full` read found, which the chat view and the Response Viewer's More button both make), so a session is read from where its claude really writes, whatever its `CLAUDE_CONFIG_DIR`. Without a watcher (server restarted, and no hook, statusline report or full read since), `findClaudeTranscript()` looks for `<claudeSessionId|id>.jsonl` under `claudeProjectsDir(session.claudeConfigDir())`: the session's own override (#255, the same dir the relaunch pin checks), else the server's. A config dir set outside Codeman (a shell profile, a wrapper) is never guessed: until the next hook or statusline report such a session answers `unavailable` / `no-transcript`, and the panel says so. Subagents are `<main path without .jsonl>/subagents/agent-<id>.jsonl`. A different main file (`/clear`, resume): the previous one, next to it in the same directory, is first read to its end with its subagents (over as many syncs as that takes), then the new one from its end with fresh cursors; the stored entries stay. "Load older" reaches back within the current conversation only, and reads the stored conversation's transcript while the switch is still pending.
⚠️ **Bounded reads.** A sync is at most `MAX_FORWARD_PASSES` (3) reads, each at most `READ_BUDGET_BYTES` (8 MiB) shared by the main transcript and all subagents (main first), plus up to 8 KiB of `meta.json` per subagent seen for the first time; a first read starts that far before the end. A file whose chunk the shared budget cut short is not applied but read in a later pass (the store would take a chunk with no line end for one line longer than the budget). "Load older" reads a full-budget block of up to `MAX_OLDER_SOURCES` (3) transcripts per click; with more, they take turns. A line longer than the budget is skipped, going forward and going back, and the line after (before) it is read whole. A subagent transcript that vanished loses its cursor, not its entries. Parsing happens in the request, line by line; nothing runs on the PTY data path. One sync per session at a time, and requests during a run fold into one more run. At most `MAX_LOADED_STORES` (3) stores stay in memory: past that the least recently used one without a run in flight is written (only if it changed) and dropped, and a later request loads it again after that write.
@@ -1375,7 +1377,7 @@ Tests: `test/mobile-prompt-composer.test.ts` (in the CI gate, deliberately not u
### Z-index layers
**Z-index layers**: subagent windows (1000), split picker menu (1000, `.split-picker-menu`), Tiles count menu (1000, `.tile-count-menu`), the closing grid's still copy (`.tile-grid-ghosts`, z-index 3 inside `.main`, over the single view coming back; hidden under `.main.webview-active`), mobile/tablet fixed header (1200, `mobile.css`), modals on ≤768px (1300 — must beat the fixed header or the modal close button is buried), log viewers (2000), connection-loss overlay (2500, above the fixed header and modals), image popups (3000), response viewer (5000, backdrop 4999), folder grid (5090, `#folderGridOverlay` — above the response viewer a folder link opens it from, below the file preview its tiles open, so a tile's preview and its ←/→ paging sit on top of the grid), file-preview overlay (5100 — must outrank the response viewer, which can launch it; at its old 2000 a path clicked in the chat opened BEHIND the chat), toasts/path picker (10000+, deliberately above the preview), the custom-model center-status banner (10001, `.center-status-banner` — `[hidden]` must re-assert `display: none` over its own `display: flex`, same trap as `.home-sessions[hidden]`, or `dismiss()` leaves an invisible click-blocker dead centre on screen), the swap-confirm and context-warning modals (10010, `#customModelSwapConfirmModal`/`#customModelContextWarningModal` — must clear both the plain `.modal` z-index of 1000 and the center-status banner it can appear over), terminal touch-selection bar (900 — above terminal content and the local-echo overlay, deliberately BELOW floating agent windows so it can never cover their controls), local echo overlay (7), iOS IME composition preview (EFFECTIVE layer depends on its home: with local echo on it is part of the local echo overlay at 7, drawn by `setComposition()` as an underlined tail after the pending text; with local echo off it is a span at z-index 6 inside `.xterm-helpers`, but `.xterm-helpers` is its own z-index 5 stacking context, so the span's effective layer is 5. That is below the overlay's 7, which is why the span cannot be used while the overlay holds text: typed text never reaches the PTY before Enter, the PTY cursor that places the span stays at the prompt start, and the overlay's opaque line div covers it).
**Z-index layers**: subagent windows (1000), split picker menu (1000, `.split-picker-menu`), Tiles count menu (1000, `.tile-count-menu`), the closing grid's still copy (`.tile-grid-ghosts`, z-index 3 inside `.main`, over the single view coming back; hidden under `.main.webview-active`), mobile/tablet fixed header (1200, `mobile.css`), modals on ≤768px (1300 — must beat the fixed header or the modal close button is buried), log viewers (2000), connection-loss overlay (2500, above the fixed header and modals), image popups (3000), response viewer (5000, backdrop 4999), folder grid (5090, `#folderGridOverlay` — above the response viewer a folder link opens it from, below the file preview its tiles open, so a tile's preview and its ←/→ paging sit on top of the grid), file-preview overlay (5100 — must outrank the response viewer, which can launch it; at its old 2000 a path clicked in the response viewer opened BEHIND the response viewer; DOCKED beside the terminal (the Codex files setting) it is `z-index: auto`, page content, since with nothing above it making a stacking context its 5100 would sit over every modal backdrop and the response viewer sheet), toasts/path picker (10000+, deliberately above the preview), the custom-model center-status banner (10001, `.center-status-banner` — `[hidden]` must re-assert `display: none` over its own `display: flex`, same trap as `.home-sessions[hidden]`, or `dismiss()` leaves an invisible click-blocker dead centre on screen), the swap-confirm and context-warning modals (10010, `#customModelSwapConfirmModal`/`#customModelContextWarningModal` — must clear both the plain `.modal` z-index of 1000 and the center-status banner it can appear over), chat view (20, `.chat-view`, covering the terminal inside `.terminal-wrap`) and its Chat / Terminal switch (21, `.chat-view-toggle`, above it), terminal touch-selection bar (900 — above terminal content and the local-echo overlay, deliberately BELOW floating agent windows so it can never cover their controls), local echo overlay (7), iOS IME composition preview (EFFECTIVE layer depends on its home: with local echo on it is part of the local echo overlay at 7, drawn by `setComposition()` as an underlined tail after the pending text; with local echo off it is a span at z-index 6 inside `.xterm-helpers`, but `.xterm-helpers` is its own z-index 5 stacking context, so the span's effective layer is 5. That is below the overlay's 7, which is why the span cannot be used while the overlay holds text: typed text never reaches the PTY before Enter, the PTY cursor that places the span stays at the prompt start, and the overlay's opaque line div covers it).
## Security layers
@@ -1399,7 +1401,7 @@ Tests: `test/mobile-prompt-composer.test.ts` (in the CI gate, deliberately not u
### Buffers, uploads, and terminal history
Target: 20 sessions, 50 agent windows at 60fps. Limits in `src/config/`: terminal 32MB (see below), text 1MB, messages 1000, max agents 500, max sessions 50 (env `CODEMAN_MAX_SESSIONS`, 1 to 462), max SSE clients 100. **Terminal history** (`src/config/terminal-history.ts`, COD-80): tmux history-limit 100k lines, PTY buffer 32MB max / 24MB trim (env `CODEMAN_MAX_TERMINAL_BUFFER`/`CODEMAN_TRIM_TERMINAL_TO`; the env-derived trim is clamped ≤75% of max — trim ≥ max would disable `BufferAccumulator` trimming entirely = unbounded memory); browser xterm scrollback stays a separate hardcoded 50k (`DEFAULT_SCROLLBACK` in constants.js — 100k/tab is a mobile-memory hazard). tmux <3.7 allocates history at pane creation, so `createSession()` sets the global default in the same command queue immediately before `new-session`; tmux 3.7+ instead creates the session and targets only that pane, because changing the global option can resize and trim unrelated live panes. A settings change resizes tracked panes only on 3.7+ and otherwise affects future panes; no version can recover lines already evicted. Settings keys `terminalScrollbackLines`/`terminalBufferMaxBytes`/`terminalBufferTrimBytes` are schema-validated but inert (only `tmuxHistoryLimit` is wired); `buffer-limits.ts` re-exports the defaults. Text/message limits are env-overridable too (`CODEMAN_MAX_TEXT_OUTPUT`/`CODEMAN_TRIM_TEXT_TO`/`CODEMAN_MAX_MESSAGES`). **Image upload** (`image-input.js` / `config/buffer-limits.ts`): up to `_maxBatchImages` 20 images/batch (bounded concurrency 3), per-file `MAX_PASTE_IMAGE_BYTES` 50MB (env `CODEMAN_MAX_PASTE_IMAGE_BYTES`); the mobile camera-roll picker auto-downscales to fit before upload. A camera-roll VIDEO (`?kind=video` on the same route, set by the client from the file's MIME type) is never buffered: it streams to disk under `MAX_PASTE_VIDEO_BYTES` 1GB (env `CODEMAN_MAX_PASTE_VIDEO_BYTES`), sniffed from the stream's first bytes (ISO BMFF / QuickTime atom, EBML for webm, Ogg for ogv) and unlinked on any failure. The client keys the flag on the MIME type, falling back to the name's extension because some Android file managers hand over a File with none; that classifier (`_promptAttachKind()`, image-input.js) is the ONE filter every pick and paste surface reads: Attach, drop, the Compose and paste-dialog pickers and the clipboard handlers. They reach it through `_admitPromptAttachments()` (same file), which also toasts what a pick skipped: the count of a mixed pick's refused files, `Unsupported file type` when none pass, and nothing for a text paste. A new surface admits through that helper, never by filtering on `_promptAttachKind()` directly, or it silently drops files with no word to the user. ⚠️ The flag is the ONLY way onto that path and admits video types alone (the registry's `VIDEO_ATTACHMENT_EXTENSIONS`, single-sourced so an uploaded video also previews: mp4/webm/mov/m4v/ogv; 3gp/mkv are out), so an image can never ride the larger cap through memory; without it the route is byte-identical to the image-only version. A DOCUMENT (the office formats pdf/docx/pptx/xlsx/zip plus the text family txt/md/csv/tsv/json/log/yaml/yml/xml, the curated `ALLOWED_DOCUMENT_EXTS`, never `SUPPORTED_ATTACHMENT_EXTENSIONS` or `EDITABLE_EXTENSIONS`) is admitted by its name's extension and buffered like an image, judged on its bytes by the same fail-closed `imageMagicMatchesExt` (a magic-number signature, or UTF-8 without a NUL byte for the text family) and saved under a sanitized `[A-Za-z0-9._-]` stem of its name; sh/py/js/html are a deliberate SCOPE exclusion by extension (the server declines to store what `file-raw` would serve or an agent could run), not a content filter, since the agent can already write any of them. `_promptAttachKind()` returns `image`, `video` or `document`, and the server's dispatch mirrors it: an image MIME wins whatever the name says, a document extension takes the document branch, and a foreign extension with no image MIME is refused `Unsupported file type` only after the image sniff fails, so nothing the image path accepted by its bytes is lost. **HEIC paste uploads** (#151): converted server-side to JPEG in a `worker_threads` worker (`web/heic-jpeg-worker.ts`, resourceLimits + 30s timeout) gated by `runWithConversionLimit()`; detection is magic-byte based (covers Android/MIUI HEIFs mislabeled as JPEG); headers declaring > 64MP are rejected 415 BEFORE decode (decompression-bomb guard). Deps: `heic-decode` + `jpeg-js`. Use `LRUMap` for bounded caches, `StaleExpirationMap` for TTL cleanup. Anti-flicker pipeline: `docs/terminal-anti-flicker.md`.
Target: 20 sessions, 50 agent windows at 60fps. Limits in `src/config/`: terminal 32MB (see below), text 1MB, messages 1000, max agents 500, max sessions 50 (env `CODEMAN_MAX_SESSIONS`, 1 to 462), max SSE clients 100. **Terminal history** (`src/config/terminal-history.ts`, COD-80): tmux history-limit 100k lines, PTY buffer 32MB max / 24MB trim (env `CODEMAN_MAX_TERMINAL_BUFFER`/`CODEMAN_TRIM_TERMINAL_TO`; the env-derived trim is clamped ≤75% of max — trim ≥ max would disable `BufferAccumulator` trimming entirely = unbounded memory); browser xterm scrollback stays a separate hardcoded 50k (`DEFAULT_SCROLLBACK` in constants.js — 100k/tab is a mobile-memory hazard). tmux <3.7 allocates history at pane creation, so `createSession()` sets the global default in the same command queue immediately before `new-session`; tmux 3.7+ instead creates the session and targets only that pane, because changing the global option can resize and trim unrelated live panes. A settings change resizes tracked panes only on 3.7+ and otherwise affects future panes; no version can recover lines already evicted. Settings keys `terminalScrollbackLines`/`terminalBufferMaxBytes`/`terminalBufferTrimBytes` are schema-validated but inert (only `tmuxHistoryLimit` is wired); `buffer-limits.ts` re-exports the defaults. Text/message limits are env-overridable too (`CODEMAN_MAX_TEXT_OUTPUT`/`CODEMAN_TRIM_TEXT_TO`/`CODEMAN_MAX_MESSAGES`). **Image upload** (`image-input.js` / `config/buffer-limits.ts`): up to `_maxBatchImages` 20 images/batch (bounded concurrency 3), per-file `MAX_PASTE_IMAGE_BYTES` 50MB (env `CODEMAN_MAX_PASTE_IMAGE_BYTES`); the mobile camera-roll picker auto-downscales to fit before upload. A camera-roll VIDEO (`?kind=video` on the same route, set by the client from the file's MIME type) is never buffered: it streams to disk under `MAX_PASTE_VIDEO_BYTES` 1GB (env `CODEMAN_MAX_PASTE_VIDEO_BYTES`), sniffed from the stream's first bytes (ISO BMFF / QuickTime atom, EBML for webm, Ogg for ogv) and unlinked on any failure. The client keys the flag on the MIME type, falling back to the name's extension because some Android file managers hand over a File with none; that classifier (`_promptAttachKind()`, image-input.js) is the ONE filter every pick and paste surface reads: Attach, drop, the Compose and paste-dialog pickers and the clipboard handlers. They reach it through `_admitPromptAttachments()` (same file), which also toasts what a pick skipped: the count of a mixed pick's refused files, `Unsupported file type` when none pass, and nothing for a text paste. A new surface admits through that helper, never by filtering on `_promptAttachKind()` directly, or it silently drops files with no word to the user. ⚠️ The flag is the ONLY way onto that path and admits video types alone (the registry's `VIDEO_ATTACHMENT_EXTENSIONS`, single-sourced so an uploaded video also previews: mp4/webm/mov/m4v/ogv; 3gp/mkv are out), so an image can never ride the larger cap through memory; without it the route is byte-identical to the image-only version. A DOCUMENT (the office formats pdf/docx/pptx/xlsx/zip plus the text family txt/md/csv/tsv/json/log/yaml/yml/xml/html/htm, the curated `ALLOWED_DOCUMENT_EXTS`, never `SUPPORTED_ATTACHMENT_EXTENSIONS` or `EDITABLE_EXTENSIONS`) is admitted by its name's extension and buffered like an image, judged on its bytes by the same fail-closed `imageMagicMatchesExt` (a magic-number signature, or UTF-8 without a NUL byte for the text family) and saved under a sanitized `[A-Za-z0-9._-]` stem of its name; sh/py/js are a deliberate SCOPE exclusion by extension (the server declines to store what an agent could run), not a content filter, since the agent can already write any of them; html/htm are admitted as AI-written specs and reports, the same job as a .md, and stay inert because file-raw serves them as `application/octet-stream` + `nosniff` and html-view refuses a page under a dot-directory such as `.codeman-uploads`. `_promptAttachKind()` returns `image`, `video` or `document`, and the server's dispatch mirrors it: an image MIME wins whatever the name says, a document extension takes the document branch, and a foreign extension with no image MIME is refused `Unsupported file type` only after the image sniff fails, so nothing the image path accepted by its bytes is lost. **HEIC paste uploads** (#151): converted server-side to JPEG in a `worker_threads` worker (`web/heic-jpeg-worker.ts`, resourceLimits + 30s timeout) gated by `runWithConversionLimit()`; detection is magic-byte based (covers Android/MIUI HEIFs mislabeled as JPEG); headers declaring > 64MP are rejected 415 BEFORE decode (decompression-bomb guard). Deps: `heic-decode` + `jpeg-js`. Use `LRUMap` for bounded caches, `StaleExpirationMap` for TTL cleanup. Anti-flicker pipeline: `docs/terminal-anti-flicker.md`.
**Prompt uploads live in `<workspace>/.codeman-uploads/`** (`POST /api/sessions/:id/paste-image`; the names live ONLY in `src/web/paste-image-gc.ts`): IN the workspace because that is the only path that resolves identically for a local agent and a container (only the workspace is bind-mounted, at the same absolute path; `~/.codeman` is not); hidden so it stays out of `git status` and the agent's view of the repository; FLAT because a nested `<workspace>/.codeman/` IS the data dir (`join(homedir(), '.codeman')`, `src/config/instance.ts`) when the workspace is the home directory, which nothing refuses; and self-ignoring through a `.gitignore` of `*` written once with `wx`, so a file already there is the user's and stays. The pre-move `.claude-images/` receives nothing but stays readable for one release: `UPLOAD_DIR_NAMES` lists both, the hourly sweep and the delete cleanup in `cleanupSession()` go through `uploadDirs()`, and the image watcher's ignore filter reads the names. ⚠️ `uploadDirs()` is async: the working directory is a user-chosen path, so it is probed BOUNDED first (`probePathKind()`, the #516 rule; `unknown` is skipped and never touched, the hourly sweep keeps the stall cap and `cleanupSession()` passes `pastCap`, since it acts on one path at the user's request), and the lstat and realpath after it are `fs.promises` calls, never sync, because the sweep runs 30 s after boot and hourly over every live session and a linked case on a dead mount would otherwise freeze the whole server. It returns only REAL directories (lstat at the leaf, so a planted `.codeman-uploads -> /other-case/.codeman-uploads` is never listed: `readdir` follows a link to a directory, and the sweep would otherwise age out the other case's uploads through it), none that is or contains `getDataDir()` (contrived, `CODEMAN_INSTANCE=uploads` makes `~/.codeman-uploads` the data dir of a home workspace and `CODEMAN_DATA_DIR` can point inside one, but it is one check next to a recursive delete; one strictly INSIDE the data dir is listed, since it only ever holds uploads and a workspace like the `~/.codeman/app` that `install.sh` clones would otherwise never have its uploads collected), and nothing for a remote (SSH) session, whose `workingDir` is the remote path and would otherwise name a same-named LOCAL directory for the sweep and the delete. The check is made when the directories are listed: a same-user process that swaps a listed directory for a link during the sweep's awaits is accepted (Node has no `openat()`, and that actor already writes anywhere this process can). The route refuses a remote (SSH) session with 400 before any disk touch: its `workingDir` is the remote path, so the file would land on THIS host where the agent cannot read it. ⚠️ And because a live session's workspace can go onto a network mount that later stops answering, the route probes `session.workingDir` BOUNDED (`probePathKind(..., { pastCap: true })`) before the first disk touch, refusing an `unknown` mount through `describeUnknownPath()` (OPERATION_FAILED) exactly as `POST /api/sessions` does, so a mount already unreachable cannot freeze a libuv worker on every upload (`ensureUploadDir()`'s own lstat/mkdir then start on a reachable path; a mount that dies between the probe and that write is the same residual race `POST /api/sessions` accepts, since a pre-check cannot bound the write that follows it). Tests: `test/paste-image-gc.test.ts`, `test/paste-image-dir-shared.test.ts`, the paste-image block of `test/routes/session-routes.test.ts`, `test/routes/session-create-unreachable-path.test.ts`.
+329
View File
@@ -0,0 +1,329 @@
# Chat view: a rendered conversation as the main session view
## Goal
A Claude session should be readable the way the Claude Code web and desktop apps
are: prose in a proportional font, markdown rendered, code in boxed blocks, and the
page's own light or dark colours. Codeman should keep managing the session exactly
as it does today. The agent still runs in its tmux pane, and only the way the
browser shows that pane changes.
The Response Viewer already renders a conversation this way, and its output is the
look to keep. Its problem is placement: it is a sheet the user opens on demand,
it does not update while the agent works, and it cannot send a prompt. The chat
view moves that same rendering into the main area, keeps it live, and puts a
message box under it.
## What the user sees
Each Claude session gets two views of the same pane:
- **Chat** shows the conversation rendered by the Response Viewer's markdown
pipeline, newest message at the bottom, with a message box underneath.
- **Terminal** is today's xterm.js pane, unchanged.
A toggle switches between them, and a keyboard shortcut does the same. The choice
is remembered per session on this device. The toggle floats at the top right of the
terminal. A second per-device setting shows or hides it. It is hidden by default
(owner decision for 1.52.1), so nobody sees the toggle without choosing it, and a user
who wants it turns it on. The shortcut still switches views while the toggle is hidden. A per-device setting picks the view for every session
this browser has no choice for yet, so a user who prefers chat never has to switch by
hand. The setting defaults to Terminal. Chat replaces the main view and still sends
some dialogs to the terminal in phase 1, so nobody gets it without choosing it.
Your own prompts show in full when they are short. A prompt longer than about 12
lines, typically a pasted log or spec, shows its first 6 lines followed by
"Show all (N lines)", so a long paste does not fill the screen between two
answers. Keep-warm nudges are hidden, as Read My Mind already drops them, because
Codeman sent them and you did not.
While the agent works, the chat view shows a status line under the last message.
It names what the running tool works on, such as "Reading src/session.ts" or
"Running npm test". A Bash call with a description shows the description, with the
command on a second `$ …` line, as the CLI does. The status line can say this because
`transcript:tool_start` carries `detail` and `command`, which `summarizeToolCall()` and
`toolCallCommand()` in `src/tool-call-summary.ts` pick out of the call's input. Each
block of Claude's answer appears as a rendered message as soon as Claude writes it to
the transcript, so a long turn fills in while it runs.
While Claude Code compacts the conversation, the status line says "Compacting
conversation". A compaction runs for a minute or more and writes nothing to the
transcript until it ends. Claude Code then draws `✻ Compacting conversation… (12s)` as
its working line, for `/compact` and for its own auto-compaction alike. The terminal
stays attached under the chat view, so the chat view reads that line from the
terminal's own buffer on each tick of the status line. Only Claude's newest row above
its message box counts, so an answer that quotes the line does not.
Between turns, Claude can still run work in the background, such as a background
shell or a monitor. The server reads that off Claude's screen as the session's
`watching` value, and the status line then says so, for example "1 shell still
running".
The chat view always shows the session's current conversation. After `/clear` it
starts empty, as Claude itself does. Claude Code runs the statusline command about a
second after a `/clear`, and its input names the new conversation and its transcript
file. The statusline exporter posts that input to the server, which moves the session
to the new conversation, so the chat view follows before the next prompt. A session
without the exporter, such as a Docker session or any session while Plan Usage Limits
is off, moves with its next prompt's hook. A session with neither moves when the chat
view next reads its conversation, as described under How the view stays live.
## Where the conversation comes from
Claude Code writes every session to a transcript file, one JSON object per line.
`GET /api/sessions/:id/last-response?context=full` already reads that file and
returns the whole conversation as prompt and response messages, each tagged with
its turn number. The Response Viewer's "More" button uses it today, so the chat
view needs no new reader for its first version.
That reader keeps only text. It drops tool calls, tool results and thinking blocks,
so in phase 1 the conversation shows prompts and answers only.
Phase 2 adds a turn's tool activity as one muted summary line, such as
"Read 9 files · edited 2 · ran 3 commands". A busy turn makes dozens of calls, and
a line per call would push the answer far down the page. Clicking the summary
expands it to one line per call ("Read src/session.ts", "Ran npm test"), and each
of those expands to show the call's input. For edits, the Edit history panel also
shows the diffs.
The summary needs every call, so in phase 2 the parser emits a `tool` message for
each `tool_use` block. The message type already exists: the DeepSeek transcript
reader and the readers for the CLIs whose conversation Codeman reads from the pane
emit it.
Parsing the whole file on every update would hold the server's event loop for over a
second on a long conversation. So the server keeps each transcript's parse and the
byte offset it reached, and a read parses only the bytes appended since the last one
(`src/web/claude-response-transcript.ts`). Phase 3 adds a cursor, so the browser asks
only for messages after the last one it has.
## How the view stays live
The server watches a Claude session's transcript. A watcher starts at the session's
first hook or statusline report, and either one reports the transcript's path.
Codeman installs those hooks in every Claude workspace unless `workspaceHooksEnabled`
is off.
A session that sends neither a hook nor a statusline report has no watcher:
- a session the server picked up after a restart, until either one arrives;
- a session with hooks switched off and no statusline exporter;
- a Docker case whose hooks cannot reach the server.
For those, any full read of the conversation starts a watcher from the transcript that
read found. A full read is `GET /api/sessions/:id/last-response?context=full`, which
both the chat view and the Response Viewer's More button make. So these sessions
also update mid-turn. After a `/clear`, a read moves a watcher it started itself to
the conversation's new file, because no hook or statusline report will move it. The
read never replaces or moves a watcher that a hook or a statusline report started,
and it starts none for a remote session.
The watcher emits `transcript:update` whenever new lines arrive. The server
broadcasts it as an SSE event, throttled to one per 750 ms per session, so the
browser learns of each new message while a turn is still running.
The chat view also listens for these events:
- `transcript:tool_start` drives the status line, because it carries the tool's
`detail` and, for a described Bash call, its `command`. With parallel tool calls,
the matching `transcript:tool_end` fires once, so the status line shows the most
recent tool rather than counting calls.
- `session:working` and `session:idle` mark the start and end of a turn. They come
from Codeman's idle detection, not from hooks, so they also work where no
transcript watcher runs.
`transcript:complete` does not help here. It fires only for a `result` row, and an
interactive Claude transcript has none.
A Docker case reports the transcript's path inside the container
(`/home/agent/.claude/projects/...`), which does not exist on the host. The case mounts the
host's `~/.claude/projects` at that folder, so `hostTranscriptPath()`
(`claude-conversation-report.ts`) maps the reported path to the host's copy before the
watcher starts, and such a session gets the same mid-turn `transcript:update` events as a
local one. A reported path outside that folder, or one with a `..` segment, is kept as
reported. The host cannot open it, so that session refetches on `session:working` and
`session:idle` alone and updates only at the start and end of each turn.
## How the user sends a prompt
The message box is a multiline text area. On a desktop, Enter sends and
Shift+Enter adds a line. On a touch device the Send button sends, and so does
Ctrl+Enter or Cmd+Enter from a hardware keyboard. Plain Enter adds a line there, as
in the phone's Compose dialog.
A send posts the text and its Enter as one input to `POST /api/sessions/:id/input`
with `useMux: true`. The server then pastes the text through tmux, presses Enter,
and arms its submit check. That check re-presses Enter while the prompt still sits
in Claude's composer, which Claude 2.1.277 and later cause by ignoring Enter for 30
to 50 seconds after the composer appears.
The browser's WebSocket input channel cannot do this. It writes raw bytes straight
into the pane and never reaches the tmux path, whatever the frame asks for. So the
chat view does not use it for prompts, even though that channel queues input
across a dropped connection.
Each request carries a client id, made once per page load, and a sequence number.
A request that fails on the network, or that the server answers with a 5xx error,
is retried with the same pair, so the server applies it once. A request the server
refuses with a 4xx status is not retried, and the text stays in the message box.
The submit check cannot always recognise a multi-line prompt in the composer. So a
long paste sent in the 30 to 50 seconds after Claude's composer appears can still
strand.
Claude Code stores a pasted prompt inside a `<pasted_content>` tag, and every
multi-line prompt sent through tmux is a paste. The chat view unwraps that tag
before rendering, or the markdown renderer would run the lines together.
The box also gets these controls:
- A stop button sends Esc, which interrupts the current turn.
- An attach button, drag-and-drop and pasting a screenshot or file into the message
box all reuse the existing prompt upload route. The uploaded files' paths go into
the chat message box, using the upload code's existing option to return paths
instead of typing them into the pane. A paste that carries no file the attach rules
admit stays a plain text paste.
- A slash command is sent as text, and the conversation shows it as typed
(`/dual-review`), not as the tags Claude Code records it with. A skill's body,
which Claude Code adds as a hidden row, stays out. Claude Code records `/compact`
only when its turn ends, so the sent copy stays drawn while that turn runs. A
skill's row arrives as its turn starts, followed at once by the hidden body row,
and that row takes the sent copy's place then. A command that runs no turn and is
never recorded goes from the thread after four seconds.
- Some slash commands typed with nothing after them get special handling in the chat view:
- `/quit` and `/exit` close the session at once, as the tab's close button does,
rather than waiting for the agent to exit and the server to notice.
- `/clear` empties the thread at once. Claude Code starts a new conversation file,
and the server moves to it when the statusline reports it, about a second later.
A session without the exporter moves later, as described at the end of What the
user sees. Until then the chat view leaves out every message no newer than the
newest one it drew before `/clear`.
- A built-in that opens a picker or a panel inside Claude's interface, such as a
bare `/model` or `/config`, shows the terminal, with a note that Alt+Shift+C
goes back. The session's remembered choice of view does not change. The server
marks those commands (`opensTerminal` in the `/` menu's list).
The terminal stays mounted and attached while Chat shows. The chat view is a layer
over the terminal's area, so the terminal keeps its size and switching views never
resizes the pane. The stop button uses the terminal's connection to send Esc. Any
focus that lands on the hidden terminal moves to the message box, so keys never
reach the pane unseen.
## What else the message box shows
The message box also carries three things the terminal shows around Claude's
composer.
- **A `/` menu.** Typing `/` at the start of the box opens a menu of slash commands,
fed by `GET /api/sessions/:id/slash-commands`. The list merges three sources:
Claude Code's built-in commands, the skills and prompt commands that the
transcript's `skill_listing` rows name, and the skills and commands on disk. The server reads those files from
the workspace's `.claude` folder and the user's Claude config folder, and every
read is bounded. For a Docker session it reads only the workspace's `.claude`
folder, because that session's config folder is the container's. Picking a row
puts `/<name> ` in the box and sends nothing.
- **The statusline.** Claude Code draws the user's statusline under its composer,
and the chat view draws the same text under the message box. Codeman's statusline
exporter wraps the user's own statusline command. Its V5 script prints that
command's output unchanged and posts a base64 copy of it as `rendered`. The server
keeps only the text, line breaks and colours, and broadcasts each change as
`session:statusLine`. A user without a statusline of their own sees Codeman's footer.
Claude Code does not run the statusline command while a session sits idle, so the
server restores the last text after a restart, and an idle session keeps its statusline.
- **The suggested next prompt.** After a turn ends, Claude Code may draw a predicted
next prompt, faint, in its empty composer. It writes that prediction nowhere else,
so `src/web/prompt-suggestion-reader.ts` reads it off the pane three times, at
about 1.5, 4 and 10 seconds after the turn ends. It reads nothing while no browser
is connected to the server. The chat view shows it as the box's placeholder, and Tab in
the empty box fills it in. A suggestion is never sent without the user.
Each read is a synchronous tmux capture that blocks the server's event loop, and
so are the reads of the submit verifier, the idle probe and keep-warm. Moving every
one of those screen reads to an async capture is a follow-up.
## Dialogs and questions
Claude sometimes stops to ask: a permission prompt, an AskUserQuestion with
options, a plan approval. The question appears in the transcript as a tool call,
but the dialog that answers it exists only in the pane.
Codeman's Approvals Inbox already detects these through Claude's hooks, reads the
options from the pane, and answers them with `POST /api/approvals/:id/answer`.
Its store runs even while the inbox setting is off. In phase 2 the chat view shows a
pending item for its session as a card at the bottom of the conversation, with one
button per option. A click goes through the same answer route, which re-reads the pane
before it types anything.
The pane can also need attention in ways the inbox cannot parse. For those, the
chat view shows a notice that says "Claude is waiting for your answer in the
terminal." and offers a button that switches to the terminal view.
In phase 1, the `permission_prompt` and `elicitation_dialog` hooks raise that notice,
and the answer cards follow in phase 2. While the notice shows, the message box sends
nothing and keeps its text. A send then would type into the dialog, and its Enter could
pick the highlighted option. A session without working hooks gets neither the notice
nor the send block: its hooks are switched off, or it is a Docker case whose hooks
cannot reach the server. A send there can still type into a dialog. Covering those
sessions needs a read of the screen, because the Approvals Inbox behind the phase 2
cards is fed by the same hooks. Dialogs are rare enough for this order. Codeman starts
Claude with `--dangerously-skip-permissions` by default, so a session stops only for
Claude's own questions and plan approvals. A session started in another
permission mode stops for every permission prompt and sends each one to the
terminal until phase 2.
## Scope
The first version covers local and Docker Claude sessions in the single main view.
Remote (SSH) and adopted sessions keep the terminal, even an adopted session that
runs on this machine, because Codeman cannot name an adopted session's transcript.
Tiles in the tile grid and the second pane of a split stay terminals. Phones keep
the terminal until phase 3. The chat view is not offered on a handheld device, whatever
its orientation, so a phone turned to landscape keeps the terminal too.
Docker Claude sessions read their transcripts through the same route, because
the container bind-mounts the host's `~/.claude/projects`. That works only when the
folder existed when the container was created. It also works only while the server
runs without `CLAUDE_CONFIG_DIR`. With that variable set, the route reads
`$CLAUDE_CONFIG_DIR/projects`, which the container does not mount. A Docker session
whose hooks cannot reach the server updates mid-turn once a full read has started its
watcher. That read comes from the chat view or the Response Viewer's More button, as
described under "How the view stays live".
Remote SSH sessions are not covered. The route reads the local projects folder,
and a remote session's transcript lives on the remote host. The Edit history panel
already reads remote transcripts over its bounded ssh path, and phase 3 can reuse
it.
Codex and DeepSeek Harness also write structured transcripts, which Codeman
already reads, so they can follow in phase 3. OMP writes a structured transcript as
well, and Codeman reads it for the session history list. The conversation route has
no OMP reader yet, so OMP can follow once that route reads its transcript. Every
other CLI keeps the terminal view for now, and its toggle is hidden. For the CLIs without a structured transcript, Codeman reads the conversation
off the screen, which is too coarse for a main view, or cannot read it at all.
The agent keeps running in its tmux pane, and respawn, Ralph, auto-compact and the
other server features work as they do now. The chat view adds no hook to the
workspaces Codeman installs hooks in, and changes nothing in a session whose chat view
is off.
## Phases
1. **Live chat view**, in five steps that each work on their own:
1. **Read.** Add the Chat/Terminal toggle, the setting that hides it and the
default-view setting. Broadcast transcript updates as a throttled SSE event,
render the full conversation with the Response Viewer's pipeline, and refetch it
on transcript and session events. Show a working status line, the "waiting for
your answer in the terminal" notice with its switch button, and follow `/clear`
through the statusline. Typing still happens in the terminal.
2. **Write.** Add the message box with send, stop and attach.
3. **Slash commands.** Add the `/` menu, draw a typed slash command as typed, and
handle `/clear`, `/quit`, `/exit` and the picker commands.
4. **What Claude is doing.** Name the running tool in the status line, say when
Claude compacts or still runs background work, and show the suggested next
prompt as the message box's placeholder.
5. **The statusline** under the message box.
2. **Dialogs and tool activity.** Show approval cards inline. Extend the transcript
parser with tool messages and render each turn's calls as one expandable
summary line.
3. **Scale and reach.** Add incremental fetching with a cursor. Extend the view to
remote SSH sessions, Codex and DeepSeek Harness, and lay it out for phones,
where the chat view could replace the terminal and accessory bar entirely.
+6
View File
@@ -298,6 +298,12 @@ The allowlist is not a formality. If a branch is about what a CLI can DO it belo
This matters because it is invisible when it is wrong. `capabilities.privilegedParams[].param` is the multi-user bypass clamp's only handle on a CLI's privilege switch, and a name from the wrong namespace clamps **nothing**: no load error, no failing test, the clamp simply stops running. Codex is the entry where the two names differ (`bypassApprovals` as the param, `dangerouslyBypassApprovals` on the wire), so it is the one that catches a regression. `schema.ts` rejects any entry naming a param it never declared, on both `configSetenv.fromParam` and `privilegedParams.param`.
## A server that runs as root (`rootValue`)
An `enum` launch param may declare `rootValue`: a map from a value to the value it takes instead when the Codeman **server process** runs as uid 0 and the launch is **local**, where the CLI is the server's child and so runs as root too. Claude declares the one entry there is, `claudeMode: { 'dangerously-skip-permissions': 'normal' }`, because Claude Code exits on `--dangerously-skip-permissions` under root and that mode is the default: on a server installed as root (a VPS, an LXC container) every local Claude session was a dead pane. It is the host-level form of `overlays.docker.rootCommand`, which answers the same refusal by the container's uid.
`applyRootValues()` (`root-launch.ts`, pure) rewrites the param values before the argv engine sees them and hands back the object it was given when nothing changes, so a launch that is not root is byte-identical. The uid is asked at call time through `serverRunsAsRoot()` (`utils/server-uid.ts`; under vitest it answers `false` unless a test stubs it), and only by the local launch sites: `serverRootSpawnOptions()` for the two tmux launches (`createSession`, `respawnPane`) and `buildPermissionArgs()` for the direct-PTY fallback and the one-shot run. Remote and Docker pane commands never read it. Each swap is logged once per launch. The schema requires every key and every replacement to be one of the param's `values`, and refuses a replacement that is itself replaced. Tests: `test/root-launch.test.ts`.
## Fields declared for later
`accent`, `capabilities.echo`, `capabilities.keyboardAccessory` and `capabilities.maxFrameBytes` are **declared but not yet read**. (`shortBadge` was on this list until the CLI management list in Settings started showing it, and `capabilities.wheelForward` until the browser's wheel gate started reading it, see below.) They all describe frontend behaviour, and the frontend is deliberately untouched here: `app.js`, `terminal-ui.js` and `styles.css` keep their own hand-authored per-CLI rules, and moving them is its own piece of work verified by a browser/mobile suite the CI gate cannot see.
+3 -3
View File
@@ -184,11 +184,11 @@ All handlers: multi-user mode only (404 otherwise), `requireAdmin`, Zod schemas
| `GET /api/admin/users` | List users + stats: role, disabled, createdAt, lastLoginAt, live session count, case count, space disk usage (best-effort async walk, cached 60s), active cookie-session count |
| `POST /api/admin/users` | Create: `{ username, role, password? }`. No password given: generate a one-time password, return it ONCE in the response, set `mustChangePassword` |
| `PATCH /api/admin/users/:username` | `{ role?, disabled?, canBypassPermissions? }`. Demoting/disabling the last enabled admin: 409 `LAST_ADMIN`. Disable also revokes cookie sessions. `canBypassPermissions` is the section 6.3 grant (default false) |
| `POST /api/admin/users/:username/reset-password` | Generates one-time password (returned once), sets `mustChangePassword`, revokes cookie sessions |
| `POST /api/admin/users/:username/logout` | Revoke all cookie sessions for that user. Honest limit under Basic auth: the browser silently re-sends cached credentials and gets a fresh cookie on the next request, so logout only truly ends QR-issued sessions; to actually lock someone out, disable the account or reset the password. Say so in the panel tooltip until Phase 6 |
| `POST /api/admin/users/:username/reset-password` | Generates one-time password (returned once), sets `mustChangePassword`, revokes cookie sessions. Does not end a trusted-proxy sign-in, which uses no password and holds no cookie |
| `POST /api/admin/users/:username/logout` | Revoke all cookie sessions for that user. Honest limit under Basic auth: the browser silently re-sends cached credentials and gets a fresh cookie on the next request, so logout only truly ends QR-issued sessions; to actually lock someone out, disable the account or reset the password. For a person who signs in through a trusted reverse proxy, neither logout nor a reset ends access (no cookie, no password): disable or delete the account. Say so in the panel tooltip until Phase 6 |
| `DELETE /api/admin/users/:username` | `{ deleteSpace?: boolean }` (default false). Refuses last admin. Kills the user's live sessions first (normal kill flow, incl. docker/remote teardown per case), revokes cookies, removes from store. With `deleteSpace`: guarded recursive delete of `~/codeman-users/<username>` (realpath must be inside `USER_SPACES_DIR`, top-level dir must not be a symlink), plus their registry entries and push subscriptions |
| `POST /api/admin/cases/assign` | Move a legacy `~/codeman-cases/<case>` into a user's space (`fs.rename`) |
| Self-service `GET /api/me` | `{ username, role, mustChangePassword }` (works in single-user mode too: synthetic admin; the frontend uses it to decide whether to render admin UI) |
| Self-service `GET /api/me` | `{ username, role, mustChangePassword, multiUser, viaTrustedProxy }` (works in single-user mode too: synthetic admin without `viaTrustedProxy`; the frontend uses it to decide whether to render admin UI). For a trusted-proxy sign-in `viaTrustedProxy` is `true` and `mustChangePassword` is reported as `false` |
| Self-service `POST /api/me/password` | `{ currentPassword, newPassword }`, verifies current, min length 8, revokes other sessions, clears `mustChangePassword` |
**Audit log**: append-only `~/.codeman/admin-audit.jsonl` (same idiom as `session-lifecycle.jsonl`): timestamp, acting admin, action, target, request IP. User management without an audit trail is not acceptable even for a homelab tool.
+153
View File
@@ -600,6 +600,156 @@ Full feature guide: [`docker-cases.md`](docker-cases.md).
- **Clone Repo does not lend the server's git sign-in to non-admins.** A clone writes only inside the caller's own case space, so it is not admin-gated, but the server account's git credential helpers (the Docker image's opt-in `gh`/`az` helpers, or any `gh auth setup-git`) are shared by every user. A non-admin's clone and preflight therefore run with `git -c credential.helper=`, which empties the helper list including the URL-scoped entries (`cloneWithoutCredentialHelpers` in `case-routes.ts`, argv pinned in `test/git-clone.test.ts`). This closes the Clone Repo path only: the account's SSH keys still apply to an `ssh://` URL, and a non-admin's agent sessions run as the same account, consistent with the first bullet above. Docker cases are a second route to the same sign-in: with `CODEMAN_AGENT_IMAGE_INSTALL_GH`/`_AZ` on, a non-admin's Docker case with credential seeding on (the default) receives a copy of the server account's `gh`/`az` sign-in, exactly as it receives the Claude and Codex credentials.
- **Admin actions are audited** append‑only to `~/.codeman/admin-audit.jsonl` (acting admin, action, target, IP). Passwords set by an admin create/reset are one‑time (returned once, force change). Under Basic auth, `logout` only truly ends QR‑issued sessions — to lock someone out, disable the account or reset the password (a proper login form is a deferred Phase 6).
### Trusted reverse‑proxy sign‑in (opt‑in, multi‑user only)
A shared secret lets an authenticating reverse proxy on the same host (oauth2‑proxy behind
Caddy or nginx, Apache `mod_auth_openidc`, Authelia, …) sign people in through an identity
provider such as Entra ID, Google or Keycloak, in place of the Basic prompt. Source:
`src/config/trusted-proxy.ts`, `checkTrustedProxyIdentity` and
`registerTrustedProxyHeaderStrip` in `middleware/auth.ts`; tests in
`test/trusted-proxy-auth.test.ts`; a worked Caddy + oauth2‑proxy setup in
[`docs/wiki/Multi-User-Mode.md`](wiki/Multi-User-Mode.md#single-sign-on-through-a-reverse-proxy).
**Experimental** ([versioning-policy.md](versioning-policy.md)): the three settings, the two
headers and the `viaTrustedProxy` field of `GET /api/me` may change until they are promoted
by an explicit decision.
"Trusted proxy" names this sign-in only. It is not forwarded-address trust: Codeman still
does not read `X-Forwarded-For`, `trustProxy` stays `false`, and `req.ip` stays the socket
peer (§3).
- **What the proxy sends.** After it has authenticated the person, the proxy adds
`X-Codeman-Proxy-Secret: <secret>` and `X-Codeman-User: <codeman username>`. It must
delete both headers from the incoming client request first. The username header can be
renamed with `CODEMAN_TRUSTED_PROXY_USER_HEADER`, but only to an `X-…` extension header
or `Remote-User`, never a reserved one (`X-Forwarded-For/Host/Proto/…`, `X-Real-IP`,
`X-Codeman-*`, CSRF/method-override headers; `X-Forwarded-User/Email/Preferred-Username`
are allowed): the header is removed from every request, so it must not be one anything
else needs. A rejected name stops the start (see below), so it is never removed.
- **The secret.** At least 32 printable ASCII characters, from
`CODEMAN_TRUSTED_PROXY_SECRET_FILE` (preferred: a 0600 file, so only a path is in the
environment, like the hook secret's `CODEMAN_HOOK_SECRET_FILE`) or
`CODEMAN_TRUSTED_PROXY_SECRET`. It is read once at auth setup, before any session is
spawned or restored, and both variables are then deleted from `process.env`, because
every session inherits Codeman's environment. That keeps them out of child processes
and nothing more: an inline secret stays visible in `/proc/<pid>/environ` for the life
of the server. A tmux server
that an earlier Codeman started with the variable set keeps its own copy of that
environment until it is restarted. A configured setup that cannot be used stops the start
with a message that says why, as the first boot without users does: a secret file that
is unreadable, empty, or readable by group or others (the mode is not checked on
Windows); a short or non-ASCII secret; both
variables set; a secret set in single-user mode; a rejected username header name. The
length floor matters because a correct secret is never refused, so the limiter only
turns a `401` into a `429` and the secret's entropy is what slows a guesser. The configured file (any name) and
`~/.codeman*/proxy-secret` are on the `isSensitivePath` blocklist, so downloads and
attachments refuse them.
- **What the secret separates.** Every local process reaches the loopback port, so
loopback alone proves nothing; the secret is what a local process lacks. It is not a
boundary against code that can read the secret file or Codeman's memory, i.e. anything
running as Codeman's OS account, which includes every agent session (the multi‑user
threat model at the top of §10a: sessions share that account). Said plainly: any session that
runs as Codeman's OS account can read the secret and sign in as anyone, an admin
included, over loopback. That is the same class as editing `users.json`, which that
account can also do.
- **When Codeman believes it.** Only when ALL hold: multi‑user mode is on; a valid secret
is configured; the request arrives on a **loopback socket** (`req.ip`, which ignores
`X‑Forwarded‑For`, §3); and the presented secret matches
(`timingSafeEqual` on equal lengths, like the hook secret). The loopback test is one
function, `isLoopbackIp`, shared with the hook-secret bypass, so the two secret-gated
loopback paths cannot drift apart.
- **The headers never travel further.** The first auth hook, right after the Host guard
and in every auth mode, reads both headers and deletes them from the request, before
any exemption (QR, web‑tab and HTML‑view capabilities) or route runs. They go from all
three views Node keeps of a request: `headers`, the raw `rawHeaders` list and
`headersDistinct`. So the web‑tab
relay cannot forward the secret to a dashboard (as a second layer the relay also drops both default names and
the configured username header; its WebSocket leg sends only `origin` and `cookie`).
- **No auto‑provisioning.** The username must name an existing, enabled account, so an
admin still decides who has an account. Unknown or disabled → `403`. The value is matched
exactly: `normalizeUsername()` (trimmed, lower-cased, as for Basic logins), then the
username rule, and nothing else. No domain is cut off and no character replaced, so an
email address names no account, and a header that arrives twice (Node joins it as
`admin, bob`) is refused, never split. Mapping the IdP's identity onto a Codeman
username is the proxy's job.
- **Fails closed once the secret header is present, even empty.** A wrong or empty secret,
a non‑loopback source, or a missing username is refused outright and never falls
through to the cookie or Basic paths, so a misconfigured proxy cannot degrade into
another identity. A username header WITHOUT the secret header is ignored, and normal
auth applies. With a valid secret, a missing username or an unknown or disabled account
gets a plain `403` with no `WWW-Authenticate`.
- **Rate limiting.** The secret is compared first, like the hook secret: a correct secret
always passes, so junk requests from other local processes (which share `127.0.0.1`
with the proxy) cannot lock sign‑in out. Only failures are counted, per IP, in their
own bucket (`AUTH_FAILURE_MAX` per `AUTH_FAILURE_WINDOW_MS`, then `429`), separate from
the Basic and hook buckets.
- **Precedence and lifetime.** Checked before the session cookie (the proxy's identity is
authoritative on that request; a stale cookie from an earlier Basic login in the same
browser does not override it, and is neither read nor refreshed). No `codeman_session` cookie is minted: the proxy
authorizes every new request and WebSocket upgrade. A terminal WebSocket or SSE stream
that is already open stays open until it disconnects: neither ending the proxy session
nor disabling the account closes it. Disabling the account refuses new authenticated
requests and upgrades; it does NOT revoke the account's web‑tab / HTML‑view
capabilities, which behind the proxy are reachable without its sign‑in, so to cut
someone off also use the Admin Panel **Logout** for them (it revokes both capability
stores) or delete the account. A password reset or Logout alone does not
cut off a proxy sign-in: it uses no password and holds no cookie, so the next request the
proxy vouches for signs the person in again. Proxy sign-ins update the account's
last-login time at most every 15 minutes, throttled in memory before the user store is
touched.
- **`mustChangePassword`** does not gate a proxy sign‑in (no Codeman password was used),
and `GET /api/me` reports `mustChangePassword: false` plus `viaTrustedProxy: true`, so
the browser does not force a password change. The account's Codeman password still
works wherever the loopback port is reachable without the proxy (an SSH tunnel, the
managed tunnel), and such a request is not covered by the identity provider's MFA.
Password sign-in has to stay: Codeman's own clients (`codeman agent`, `mcp`, `notify`,
`attach`, `tui`, the skill) sign in with Basic on loopback. For an account used only
through the proxy, create it without a password; the generated one-time password can be
discarded, and the pending `mustChangePassword` then only shows as a label. A user's own logout / "Revoke all" ends Codeman cookies, not the
proxy's session (`/oauth2/sign_out` does that).
- **Web tabs and rendered HTML files** authenticate by the capability in their URL,
because their sandboxed frames send no cookies, not even the proxy's. The proxy must
therefore let `/webview/*` and `/html-view/*` through without its own sign‑in (and
without adding the secret, and without forwarding `Authorization`); the wiki example
does. With trusted‑proxy sign‑in configured, a request under those prefixes that the
capability exemptions do not let through, whatever its token looks like, is refused with
the route's own answer
(`403` web tab, `404` HTML view) BEFORE the credential checks: no Basic challenge, no
password check, no failure count (`serveRefusedCapabilityPath`). Two requests under a
dead web‑tab capability have no route status to copy and get the hook's `403` as well: a
WebSocket upgrade is refused at the handshake (the route alone accepts it and closes
with `4003`), and `GET /webview/<cap>` without the trailing slash is not redirected
(the route alone answers `302`). The prefix is judged
the way a proxy's path matcher would (`capabilityPrefixOf`: case‑insensitive,
percent‑decoded, dot segments and doubled slashes resolved), since the proxy forwards
every such spelling without its sign‑in. Under a base path (`CODEMAN_BASE_URL`) the
mount prefix is judged the same way: the server strips only its literal spelling, so
the refusal looks for the capability prefix in the normalised path as it arrives and,
when that path starts with the mount prefix, once more with the mount prefix removed.
A match in either form is refused. The path as it arrives comes first, because under
a mount named like a capability prefix (`/webview`) the literal mount is already gone.
Otherwise anonymous
requests through the proxy could probe passwords and fill the per‑IP bucket, which
behind the proxy is always `127.0.0.1`, locking out Basic sign‑in from loopback.
Without a proxy configured these paths keep the normal `401` challenge. One limit
follows from the exemption being by prefix: a sandboxed frame's request that lands
outside its prefix goes through the proxy's sign-in without a cookie and fails there,
so the `Referer` form and the lost-frame recovery page (§10b) are not reachable for
sandboxed frames behind the proxy.
- **The proxy's own session cookie.** A cookie-based proxy's session cookie is a sign-in
for the whole site. Codeman does not know its name, and the web-tab relay forwards
browser cookies (all but `codeman_session`) to a dashboard opened in trusted mode. The
proxy must remove its cookie from every request it forwards to Codeman, on the
capability paths and after its own sign-in check; the wiki example does.
- **Unchanged:** the Host allowlist and Origin guard (set `CODEMAN_ALLOWED_HOSTS` to the
proxy's hostname), the hook‑secret loopback bypass (a proxy should still refuse
`/api/hook-event`, `/api/status-telemetry` and their `/api/v1/` aliases from outside;
local hooks call the loopback port directly), and Basic sign‑in for requests without
the secret header. Admin actions through the proxy are audited with IP `127.0.0.1`, as
with any reverse proxy.
- **Not supported:** Docker Compose installs where Codeman runs in a container and the
proxy on the host; the proxy then connects from the bridge address, not loopback.
---
## 10b. Web tabs (dashboard proxy)
@@ -639,6 +789,8 @@ Opt-in by a click, macOS only, admin-only in multi-user mode on every verb. The
| Env / flag | Effect |
|------------|--------|
| `CODEMAN_PASSWORD` (+ `CODEMAN_USERNAME`) | Enable HTTP Basic auth |
| `CODEMAN_TRUSTED_PROXY_SECRET_FILE` / `CODEMAN_TRUSTED_PROXY_SECRET` | Multi‑user only: trust a same‑host authenticating reverse proxy that presents this secret (≥ 32 printable ASCII chars; the file variant is preferred; both variables are removed from the environment once read; a setup that cannot be used stops the start) and a username header. Experimental — see §10a |
| `CODEMAN_TRUSTED_PROXY_USER_HEADER` | Header the trusted proxy puts the Codeman username in (default `X-Codeman-User`) |
| `--host` / `CODEMAN_HOST` | Bind host (default `127.0.0.1`) |
| `CODEMAN_ALLOWED_HOSTS` | Extra `Host`/`Origin` allowlist entries for reverse proxies (comma‑separated; exact host, or leading‑dot `.suffix` for subdomains) — see §3 |
| `--base-url` / `CODEMAN_BASE_URL` | Sub‑path prefix Codeman is mounted under behind a reverse proxy, e.g. `/codeman` (default `/`); the proxy must forward the prefix unchanged. Independent of `CODEMAN_ALLOWED_HOSTS` |
@@ -660,6 +812,7 @@ Opt-in by a click, macOS only, admin-only in multi-user mode on every verb. The
| Bind‑host classification, env‑flag parsing, Host/Origin allowlist (`buildHostPolicy` / `isAllowedRequestHost` / `isAllowedRequestOrigin`) | `src/web/network-auth-policy.ts` |
| Start‑and‑warn policy | `src/web/server.ts` (`WebServer.start()`) |
| Auth pipeline, rate limiting, security headers, CORS, Host/Origin guard (`registerHostGuard`) | `src/web/middleware/auth.ts` |
| Trusted reverse‑proxy sign‑in: secret loading, header names, header stripping | `src/config/trusted-proxy.ts` |
| File‑path containment (realpath‑before‑check) | `src/web/route-helpers.ts` (`validateSessionFilePath`) |
| File routes, caps, SVG handling, download blocklist | `src/web/routes/file-routes.ts` |
| Instance/socket/data‑dir scoping | `src/config/instance.ts` |
+19
View File
@@ -110,6 +110,25 @@ any other endpoint. On-disk state (`local-model.json`, the `local-model/` folder
internal, as for every other file in the data directory. Promotion to stable requires
an explicit documented decision.
### Experimental trusted-proxy sign-in
Sign-in through an authenticating reverse proxy in multi-user mode
([security-architecture.md](security-architecture.md) §10a) is labeled experimental, so
item 3 above applies to all of its surface: the environment variables
`CODEMAN_TRUSTED_PROXY_SECRET_FILE`, `CODEMAN_TRUSTED_PROXY_SECRET` and
`CODEMAN_TRUSTED_PROXY_USER_HEADER`, the request headers `X-Codeman-Proxy-Secret` and
`X-Codeman-User`, the `viaTrustedProxy` field of `GET /api/v1/me` (and its `/api` alias),
the status codes and messages of its refusals, and the conditions under which a
configured setup stops the start. They may change or be removed in a MINOR or PATCH
release.
It is off unless a secret is configured. With it off, sign-in works as before. Three
things still apply: the identity headers (the two above and a configured username
header) are dropped on arrival, downloads and attachments refuse the secret file, and a
trusted-proxy setting that cannot be used stops the start. The other fields
of `GET /api/v1/me` keep their existing guarantees. Promotion to stable requires an
explicit documented decision.
## Deprecation policy
When we need to change a covered surface:
+6 -1
View File
@@ -107,7 +107,12 @@ similar). The sandboxed frame is opaque-origin, so its stylesheet, script, and A
requests do not carry the proxy's authentication cookie; the proxy redirects them to
the login provider, where CORS/CSP kills them, and the embedded app renders
unstyled or broken while the Codeman page around it works fine. Trusted mode
(**Open sandboxed** off) keeps a real origin and the cookie, so it works. The
(**Open sandboxed** off) keeps a real origin and the cookie, so it works. ⚠️ In trusted
mode the relay forwards the browser's cookies to the dashboard, all but
`codeman_session`, and that includes the proxy's own session cookie unless the proxy
removes it from the requests it forwards to Codeman (the Caddy example in
[`docs/wiki/Multi-User-Mode.md`](wiki/Multi-User-Mode.md#single-sign-on-through-a-reverse-proxy)
does). The
**Test** button cannot catch this: it checks that the Codeman *server* can reach the
upstream, not that a sandboxed *browser* frame can load assets through the public
authentication layer.
+3 -1
View File
@@ -110,7 +110,9 @@ approve those steps. With nothing else said, that also installs the first agent
catalogue when none is found; `--ai-cli` (or `CODEMAN_AI_CLI`) says which one, or none.
`CODEMAN_TAILSCALE=1` preselects the Tailscale answer, and never
installs Tailscale itself non-interactively; a non-interactive run never renames the
machine and never starts a service. Everything the unattended steps print goes to
machine and never starts a service. With no terminal there is nowhere to type a password,
so a step that needs `sudo` works only where `sudo` asks for none (a `NOPASSWD` entry, as
cloud images and CI runners have). Everything the unattended steps print goes to
`~/.codeman/install.log`, and the last lines of it are shown when a step fails.
### Without administrator rights
+15 -3
View File
@@ -14,6 +14,7 @@ Press `Ctrl+?` in the app for the same list in a floating overlay.
| `Alt+1` to `Alt+9` | Switch to tab N. Physical keys, so macOS Option layouts work. |
| `Ctrl+Shift+{` / `Ctrl+Shift+}` | Move the active tab left / right. |
| `Alt+B` | Collapse / expand the session sidebar, when that layout is on. |
| `Alt+Shift+C` | Switch a Claude session between Chat and Terminal view, when [the chat view](Settings-Reference#header--panels) applies to it. |
`Ctrl+W` is not a Codeman shortcut: it goes to the terminal, where shells and agent CLIs
use it to delete the previous word. **Close Session** has no key by default; close a session
@@ -89,9 +90,20 @@ The terminal sees keystrokes before the app does. Any chord the app claims has t
swallowed at the terminal layer, or xterm writes the control byte into the session as well
as triggering the action. A chord **you** rebind an action to is kept out of the terminal
too, so rebinding Previous Session to `Alt+J` switches the session and sends nothing to the
CLI. The built-in defaults are deliberately not held back this way: `Ctrl+L` clears the
screen and also reaches the CLI, which redraws on it. Binding an action back onto its own
default behaves like the default.
CLI. Several built-in defaults are held back too, each by a check of its own:
- the tab switches (`Alt+1` to `Alt+9`, `Alt+[` and `Alt+]`) and the session finder
(`Ctrl+K`, `Alt+K`);
- `Alt+B`, while the sidebar layout is on;
- `Alt+Shift+C`, while the active session can show the chat view;
- Copy Selection, whose `Ctrl+Shift+C` never reaches the CLI and whose `Ctrl+C` does not
while text is selected;
- the tile grid chords.
None of those chords types anything into the CLI when it acts as its shortcut; `Ctrl+C`
with nothing selected is the interrupt and reaches the CLI. The other defaults still
reach it: `Ctrl+L` clears the screen and also reaches the CLI, which redraws on it.
Binding an action back onto its own default behaves like the default.
`Alt+1` through `Alt+9` are matched on **physical key position** rather than the character
produced, so macOS Option layouts that produce `¡™£` still switch tabs.
+364 -1
View File
@@ -112,7 +112,370 @@ casually; they do not make the account a sandbox.
Each user authenticates with their own name and password rather than the shared
`CODEMAN_PASSWORD`. Logins are individually revocable: disable, reset, or delete an account
at any time, and existing browser sessions can be revoked.
at any time, and existing browser sessions can be revoked. A person who signs in through a
reverse proxy (next section) uses no Codeman password and holds no browser session, so a
password reset or a logout does not end their access: disable or delete the account.
## Single sign-on through a reverse proxy
Instead of Codeman passwords, people can sign in through your identity provider (Entra ID,
Google Workspace, Keycloak, Okta, ...). An authenticating reverse proxy on the same host
does the sign-in and tells Codeman who the person is. Codeman still decides who has an
account: the username must name an existing, enabled user, or the request gets `403`.
**Experimental.** The settings, the two headers and the `viaTrustedProxy` field of
`GET /api/me` may still change (see
[`docs/versioning-policy.md`](https://github.com/Ark0N/Codeman/blob/master/docs/versioning-policy.md)).
"Trusted proxy" here means only this sign-in. It does not make Codeman read
`X-Forwarded-For` or any other forwarded address: the client address stays the address of
the socket, which behind the proxy is `127.0.0.1`.
```
browser --HTTPS--> Caddy --forward_auth--> oauth2-proxy (127.0.0.1:4180) --> identity provider
\--reverse_proxy--> Codeman (127.0.0.1:3000, multi-user mode)
```
On every request the proxy adds two headers:
| Header | Value |
|---|---|
| `X-Codeman-Proxy-Secret` | the shared secret |
| `X-Codeman-User` | the Codeman username (another name can be set with `CODEMAN_TRUSTED_PROXY_USER_HEADER`: an `X-…` header such as `X-Forwarded-User`, or `Remote-User`; standard and reserved headers are refused, because the header is removed from every request) |
Codeman believes them only from a loopback connection (`127.0.0.1`, `::1` or
`::ffff:127.0.0.1`) with the matching secret, so keep Codeman bound to `127.0.0.1` and the
proxy on the same host. It removes both headers from
every request before anything else sees them. The exact rules are in
[`docs/security-architecture.md` §10a](https://github.com/Ark0N/Codeman/blob/master/docs/security-architecture.md).
The secret keeps other local processes from claiming an identity. It does not protect
against anything that runs as Codeman's own OS account, which includes every agent session:
such a process can read the secret and sign in as anyone, an admin included, over loopback.
That is the same exposure as editing `users.json`, which the same account can also do (see
[Read this before enabling it](#read-this-before-enabling-it)).
### Codeman
```bash
install -m 600 /dev/null ~/.codeman/proxy-secret
openssl rand -hex 32 > ~/.codeman/proxy-secret # the shared secret, also given to the proxy
codeman users add alice --admin # accounts still come from Codeman
CODEMAN_MULTIUSER=1 \
CODEMAN_ALLOWED_HOSTS=codeman.example.com \
CODEMAN_TRUSTED_PROXY_SECRET_FILE=~/.codeman/proxy-secret \
codeman web # stays on 127.0.0.1:3000
```
The startup log says `Trusted-proxy sign-in enabled (experimental)`. A setup that cannot be
used stops the start, with a message that says why:
- the secret file cannot be read, is empty, or can be read by group or others (`chmod 600`
it; the mode is not checked on Windows);
- the secret is shorter than 32 characters or not printable ASCII;
- both `CODEMAN_TRUSTED_PROXY_SECRET_FILE` and `CODEMAN_TRUSTED_PROXY_SECRET` are set;
- a secret is set without multi-user mode;
- `CODEMAN_TRUSTED_PROXY_USER_HEADER` names a header that is not allowed.
In a systemd unit, give the file as an absolute path (systemd does not expand `~`; `%h`
works in a user unit; in a system unit write the full path). Codeman's downloads and
attachments refuse the configured secret file.
`CODEMAN_TRUSTED_PROXY_SECRET` (the value itself) works too. Codeman reads the settings
once and removes both variables from its environment, so sessions started later don't
inherit them. That is all it does: the value stays visible in `/proc/<pid>/environ` for as
long as the server runs, and a tmux server started earlier with it set keeps its own copy
until restarted. Prefer the file.
Password sign-in stays available for requests that reach Codeman without the proxy.
Codeman's own tools need it: `codeman agent`, `mcp`, `notify`, `attach` and `tui` and the
Codeman skill sign in on loopback with `CODEMAN_USERNAME` / `CODEMAN_PASSWORD`. Such a
request is not checked by the identity provider, so its MFA does not apply to it. For a
person who only ever signs in through the proxy, create the account without a password:
Codeman generates a random one-time password, which you can discard. The account then
keeps its `must-change-pw` label in the Admin Panel; the label has no effect on proxy
sign-ins.
### oauth2-proxy
Register an OIDC app with your identity provider (redirect URI
`https://codeman.example.com/oauth2/callback`) and restrict it to the people who should
get in. A minimal `oauth2-proxy.cfg`:
```toml
http_address = "127.0.0.1:4180"
reverse_proxy = true
provider = "oidc"
oidc_issuer_url = "https://login.microsoftonline.com/<tenant-id>/v2.0" # your provider
redirect_url = "https://codeman.example.com/oauth2/callback"
whitelist_domains = ["codeman.example.com"]
email_domains = ["example.com"]
set_xauthrequest = true # return the identity as X-Auth-Request-* headers
skip_provider_button = true
upstreams = ["static://202"] # forward_auth only, nothing to proxy
cookie_secure = true
cookie_samesite = "lax" # never sent from a sandboxed web-tab frame
cookie_expire = "12h" # sign in again after this (default 168h)
cookie_refresh = "1h" # re-check with the provider this often
cookie_csrf_per_request = true # one CSRF cookie per sign-in, so parallel ones don't collide
cookie_csrf_per_request_limit = 5
scope = "openid email profile offline_access" # offline_access: a refresh token (Entra ID)
```
Client ID, client secret and cookie secret go in the environment
(`OAUTH2_PROXY_CLIENT_ID`, `OAUTH2_PROXY_CLIENT_SECRET`, `OAUTH2_PROXY_COOKIE_SECRET`).
For Entra ID add `oidc_email_claim = "preferred_username"`. Without `cookie_refresh`, a
person disabled at the provider keeps access until the cookie expires. `cookie_refresh`
needs a refresh token: without one (for Entra ID, without `offline_access` in the scope),
oauth2-proxy can't refresh, and people are sent back through sign-in whenever the ID token
expires, about hourly.
Set `cookie_samesite`. oauth2-proxy puts no `SameSite` attribute on its cookie unless it is
configured, and browsers disagree about a cookie without one. With `lax`, a sandboxed
web-tab frame does not send the proxy's cookie in any browser.
The username Codeman gets is only as trustworthy as the claim it comes from:
- **Register the app as single-tenant.** The proxy trusts values that the administrators
of the signing-in person's tenant control, so only your own tenant may sign in.
- **`email` and `preferred_username` are mutable.** An administrator can change them, and
an address can be given to another person later. That person then gets the Codeman
account the address maps to, until you remove its row from the `map` below. Go through
the table when people leave or are renamed.
### Caddy
Give Caddy the same secret through its environment, not in the Caddyfile (which is often
world-readable): for the packaged service, a systemd drop-in with
`EnvironmentFile=/etc/caddy/codeman-proxy.env` (mode 0600) containing
`CODEMAN_TRUSTED_PROXY_SECRET=<secret>`. Keep the `{env.…}` placeholder below; a `{$…}`
placeholder would put the value into the adapted config, which local processes can read
from Caddy's admin port.
```caddyfile
codeman.example.com {
# Signed-in identity -> Codeman username (case-sensitive: use the spelling your
# provider returns). Unlisted people get an empty username and are refused below.
map {http.request.header.X-Auth-Request-Email} {codeman_user} {
alice@example.com alice
default ""
}
# Hooks call 127.0.0.1:3000 directly; never expose them (or their /api/v1 aliases).
@hooks path /api/hook-event /api/status-telemetry /api/v1/hook-event /api/v1/status-telemetry
# Web tabs and rendered HTML files authenticate by the capability in their URL: their
# sandboxed frames send no cookies, so they can't pass the sign-in below.
@capability path /webview/* /html-view/*
# `route` keeps the order as written. Without it Caddy sorts directives itself, and
# `handle` would run before `respond`, or forward_auth before request_header.
route {
respond @hooks 403
handle /oauth2/* {
reverse_proxy 127.0.0.1:4180 {
header_up X-Real-IP {remote_host}
header_up X-Forwarded-Uri {uri}
}
}
handle @capability {
# No sign-in and no secret: Codeman checks the capability itself. No password
# either: these paths must never reach Codeman's password check or prompt.
request_header -X-Codeman-Proxy-Secret
request_header -X-Codeman-User
request_header -Authorization
# oauth2-proxy's cookie is a sign-in for this whole site. Codeman never needs
# it, and its web-tab relay forwards browser cookies to a dashboard opened in
# trusted mode.
request_header Cookie "(^|;\s*)_oauth2_proxy[^=;]*=[^;]*" ""
reverse_proxy 127.0.0.1:3000 {
header_down -WWW-Authenticate
}
}
handle {
route {
# Only oauth2-proxy and this file may set identity headers.
request_header -X-Auth-Request-Email
request_header -X-Codeman-Proxy-Secret
request_header -X-Codeman-User
forward_auth 127.0.0.1:4180 {
uri /oauth2/auth
copy_headers X-Auth-Request-Email
@unauthenticated status 401
handle_response @unauthenticated {
# Only a page navigation can complete a sign-in. A background request
# (fetch, the live-update stream, a WebSocket) gets a 401. A client
# that sends no Sec-Fetch-Mode header is still redirected.
@background {
header Sec-Fetch-Mode *
not header Sec-Fetch-Mode navigate
}
route {
respond @background "Sign-in required" 401
redir * /oauth2/start?rd={scheme}://{hostport}{uri}
}
}
}
@nouser vars {codeman_user} ""
respond @nouser "No Codeman account for this sign-in" 403
# After forward_auth, which needs it: remove oauth2-proxy's cookie.
request_header Cookie "(^|;\s*)_oauth2_proxy[^=;]*=[^;]*" ""
reverse_proxy 127.0.0.1:3000 {
header_up X-Codeman-Proxy-Secret {env.CODEMAN_TRUSTED_PROXY_SECRET}
header_up X-Codeman-User {codeman_user}
# Codeman needs only the two headers above.
header_up -X-Auth-Request-Email
}
}
}
}
}
```
This example was run with Caddy 2.11.9 and oauth2-proxy 7.15.6. What it relies on, because
Codeman cannot see a mistake here:
- **The proxy removes what the client sent.** The `request_header -…` lines delete any
copy of the identity headers that arrived from outside, and `header_up` replaces a
header, it never appends. The username therefore only ever comes from the sign-in result.
- **The secret is added only behind the sign-in**, never on the `/webview/*` and
`/html-view/*` route.
- **The proxy's own cookie stops at the proxy.** The `request_header Cookie …` lines remove
it on both routes. With a different `cookie_name` in oauth2-proxy, change the name in
the pattern.
- **A background request is not sent to the sign-in.** A request with a `Sec-Fetch-Mode`
other than `navigate` gets a `401`. Page navigations are redirected as before, and so
are clients that send no such header (command-line tools, old browsers). Without that
rule an open Codeman page whose proxy session has ended starts a sign-in with every
background request that follows the redirect, which `fetch()` and the live-update stream
do. Each one replaces oauth2-proxy's CSRF cookie, and the person's real sign-in then
ends on oauth2-proxy's error page ("CSRF token mismatch"). `cookie_csrf_per_request`
covers the remaining case of several tabs signing in at once.
- **oauth2-proxy's identity headers stop at the proxy too.** `header_up -X-Auth-Request-Email`
removes the address on the way to Codeman, because the web-tab relay passes headers it
does not know on to dashboards.
Check the order Caddy will actually use with
`caddy adapt --config Caddyfile --adapter caddyfile` before going live. With
`CODEMAN_BASE_URL` (a sub-path mount), prefix the paths in `@hooks` and `@capability`.
To check that a forged header is ignored, run this in the browser console of the signed-in
page. It must show your own username:
```js
fetch('/api/me', { headers: { 'X-Codeman-User': 'someone-else' } }).then((r) => r.json()).then(console.log)
```
### Taking the username from the identity provider instead
The `map` is a list you maintain. If your provider can put the Codeman username into the
ID token (for example the AD logon name: Entra ID can add it with a claims mapping policy
that emits `user.onpremisessamaccountname` as a custom claim; the app then needs
`acceptMappedClaims` enabled, which belongs only on a single-tenant app registration), let
oauth2-proxy return that claim as a header. That needs
oauth2-proxy 7.15.5 or later with its alpha config (`--alpha-config`), and the claim must
be listed in the provider's `additionalClaims`, otherwise the header stays empty:
```yaml
providers:
- id: idp
provider: oidc
# ... clientID, clientSecretFile, oidcConfig ...
additionalClaims:
- samaccountname
injectResponseHeaders:
- name: X-Auth-Request-Codeman-User
values:
- claimSource:
claim: samaccountname
```
In the Caddyfile, drop the `map` and replace the inner `route` of the last `handle`:
```caddyfile
route {
request_header -X-Auth-Request-Email
request_header -X-Auth-Request-Codeman-User
request_header -X-Codeman-Proxy-Secret
request_header -X-Codeman-User
forward_auth 127.0.0.1:4180 {
uri /oauth2/auth
copy_headers X-Auth-Request-Email X-Auth-Request-Codeman-User
@unauthenticated status 401
handle_response @unauthenticated {
@background {
header Sec-Fetch-Mode *
not header Sec-Fetch-Mode navigate
}
route {
respond @background "Sign-in required" 401
redir * /oauth2/start?rd={scheme}://{hostport}{uri}
}
}
}
@nouser vars {http.request.header.X-Auth-Request-Codeman-User} ""
respond @nouser "No Codeman username for this sign-in" 403
request_header Cookie "(^|;\s*)_oauth2_proxy[^=;]*=[^;]*" ""
reverse_proxy 127.0.0.1:3000 {
header_up X-Codeman-Proxy-Secret {env.CODEMAN_TRUSTED_PROXY_SECRET}
header_up X-Codeman-User {http.request.header.X-Auth-Request-Codeman-User}
header_up -X-Auth-Request-Email
header_up -X-Auth-Request-Codeman-User
}
}
```
Adding a person is then: allow them at the identity provider, and
`codeman users add <name>`. Codeman usernames allow letters, digits, `_` and `-` only, so
the claim must fit that. A logon name with a dot (`jane.doe`) does not: for such accounts
keep the `map`. A browser that signed in before the claim existed needs to sign
out (`/oauth2/sign_out`) and in again.
### Things to know
- **No Codeman cookie is issued** for proxy sign-ins. The proxy authorizes every new
request and WebSocket upgrade, but a terminal or live-update connection that is already
open stays open until it disconnects.
- **Cutting someone off:** disable their Codeman account (new requests are refused), then
use **Logout** for them in the Admin Panel, which also revokes the web-tab and HTML-view
links they opened (disabling alone doesn't, and those links don't need the proxy's
sign-in). Deleting the account does both. Logout alone, or a password reset, does not
cut off a proxy sign-in: it holds no cookie and uses no password, so the next request
signs the person in again. Connections already open stay open until they disconnect.
- **Web tabs and HTML view behind the proxy:** with trusted-proxy sign-in configured, a
path under those prefixes without a live capability, malformed ones included, is refused
(`403` / `404`) without a password check,
prompt or failure count, so anonymous requests can't probe passwords or lock out the
password sign-in.
- **When the proxy session expires**, API calls and the live-update stream get the proxy's
`401`. An open Codeman page then shows "No connection to the Codeman server" and does
not recover by itself: reload it to sign in again. The `rd=` return address is not
URL-encoded, so a query string with `&` loses everything after the first one.
- **`mustChangePassword` is ignored** for proxy sign-ins, since no Codeman password was
used, and `GET /api/me` reports it as `false` for them. A person's own "Revoke all" and logout end Codeman cookies, not the proxy's
session; sign out of the proxy at `/oauth2/sign_out`.
- **A wrong or empty secret is refused outright** (and failures are rate-limited per IP);
it never falls back to the cookie or password sign-in.
- **Sandboxed web tabs:** a request the dashboard makes outside its
`/webview/<capability>/` prefix (a root-absolute asset the rewriting missed, or a page
that reloads itself) goes through the proxy's sign-in, carries no cookie and fails
there. Codeman's `Referer` relay and lost-frame recovery never see it. Dashboards that
use relative URLs work; for the others use trusted mode or a new browser tab.
- **Trusted web tabs** forward the browser's cookies to their dashboard. The proxy's
sign-in cookie would be among them, which is why the Caddy example removes it.
- **Docker Compose installs** can't use this: the proxy on the host reaches the container
from the bridge address, not loopback.
- **Audit log:** admin actions through the proxy are recorded with IP `127.0.0.1`.
## Gotchas
+28 -2
View File
@@ -63,11 +63,20 @@ non-updatable. See [Running As A Service](Running-As-A-Service).
Chips for every optional header control, with a live preview of the resulting header:
Run, Font Size, System Stats, Redraw Terminal, Response Viewer, Away Digest, Session
Run, Font Size, System Stats, Redraw Terminal, Response Viewer, Codex files, Away Digest, Session
Manager, Attachments, Edit history, File Viewer, Multi-monitor, Split, Tiles, Plan Usage, Lifecycle Log, Monitor,
Project Insights, File Browser, Subagents, Approvals Inbox, Read My Mind, Ultracode Agents,
Ultracode Windows, Cron.
**Codex files** (off by default, per device) switches on four extras for Codex sessions, together:
a click on a file name Codex underlined in the pane opening that file in the preview when it names a
single supported file from the conversation (off, the click goes to Codex), a **Response files** header button that lists the previewable files linked in the latest reply
(desktop only: phones keep File Viewer as their one header button, even with this on), a click on a
file name in Codex's own sidebar opening that file in the preview when it matches a single linked
file (off, the click goes to Codex), and a **Dock** button on file previews that, on a window 1180px
or wider with a single terminal, docks the preview beside the terminal. With it off none of the four
exists, and every click in a Codex pane goes to Codex as before.
**Host readings** (opt-in, both off by default and per device): **GPU Stats** adds three items after CPU and MEM: GPU load, graphics memory and the GPU clock,
and **CPU MHz** adds the live CPU clock. Both sets of items live inside **System Stats**, so they show only
while that chip is on, and nothing is fetched while it is off. An item appears only when the
@@ -114,7 +123,21 @@ images it produced. Claude sessions, local and remote (SSH). Nothing is read unt
stores those diffs (secrets included) under `~/.codeman/edit-history/`; see
[Working With Files](Working-With-Files#edit-history).
Most default to off. The stock desktop header is system stats, File Viewer, Tiles, and the gear.
Under **Panels**, **Open Claude sessions in Chat view** (per device, off by default, never on
phones) picks the view a Claude session opens in. The chat view draws the session's conversation
as text, over the terminal. To type, switch to the Terminal view. The terminal keeps running underneath, so switching
views never resizes it. The chat view applies to local and Docker Claude sessions in the main
view. Remote (SSH) and adopted sessions keep the terminal, and so do the tiles of the tile grid
and the second pane of a split. Each session remembers its own choice in this browser: press
`Alt+Shift+C`, or use the Chat / Terminal switch at the terminal's top right, to change it.
Another browser or device opens the same session in its own default until you choose there too.
This setting decides only where a session with no choice of its own starts.
**Show the Chat / Terminal switch** (per device, off by default, never on phones) shows that switch
at the top right of a Claude session. Turn it on to switch views with a click. Without it, each
session keeps the view it had, and `Alt+Shift+C` still switches views.
Most header chips default to off. The stock desktop header is system stats, File Viewer, Tiles, and the gear.
**Header Stats Style** picks how the system stats and plan usage are drawn: *Compact*
(default; two pills with a ring beside every value), *Tiles* (label over value with a bar underneath) or *As before* (the bars and the `5H · 7D` chip). Desktop only, per device.
New header controls never appear on phones. Split is desktop-only regardless of this
@@ -300,6 +323,9 @@ Some things are configured before the server starts, not in the UI:
| `CODEMAN_ALLOWED_HOSTS` | Extra Host and Origin allowlist entries for a reverse proxy. |
| `CODEMAN_INSTANCE` | Scopes the data directory and tmux socket together. Required for a second instance. |
| `CODEMAN_MULTIUSER` | Enables multi-user mode. |
| `CODEMAN_TRUSTED_PROXY_SECRET_FILE` | Experimental, multi-user only. A file (mode 600) holding the secret that lets an authenticating reverse proxy on the same host sign people in (single sign-on). A setup that cannot be used stops the start. See [Multi-User Mode](Multi-User-Mode#single-sign-on-through-a-reverse-proxy). |
| `CODEMAN_TRUSTED_PROXY_SECRET` | The same secret given directly. Both variables are read once at startup and then removed from the environment, so sessions don't inherit them; the file variant is preferred. |
| `CODEMAN_TRUSTED_PROXY_USER_HEADER` | Header that proxy puts the Codeman username in. `X-Codeman-User` by default; only an `X-…` header or `Remote-User` is accepted. |
| `CODEMAN_GESTURE` | Makes gesture control available to be enabled. |
| `CODEMAN_DOCKER_BRIDGE_HOOKS` | Lets in-container hooks reach the host on a loopback bind. |
| `CODEMAN_FILE_PICKER_ROOTS` | Extra roots for the path picker. |
+11
View File
@@ -131,6 +131,17 @@ That prompt comes from Claude Code, not Codeman. Codeman's default is to start w
permission prompts skipped, which is what the security model is built around. If you would
rather it prompted, change **App Settings → Agents & CLIs → Claude → Startup Mode**.
### Claude asks for permission although Startup Mode skips the prompts (Codeman runs as root)
When the Codeman server itself runs as root (common on a VPS and in an LXC container),
Claude sessions start without the permission bypass and ask before they act. Claude Code
refuses `--dangerously-skip-permissions` under root and exits, which on older versions left
every Claude tab with a dead pane (`--dangerously-skip-permissions cannot be used with
root/sudo privileges for security reasons`). Codeman now leaves the flag out there and writes
one line to the server log for each such launch; the other startup modes are passed through
unchanged. Run Codeman as a normal user to get the default back. A session in a Docker case
or on a remote host runs under the account on that side, so this does not apply to it.
### My settings were reset, or a CLI I enabled is gone
Something rewrote a file in `~/.codeman/` (a hand edit, a restart that loaded a bad file, a
+4 -1
View File
@@ -97,7 +97,10 @@ The reason: an opaque-origin frame's stylesheet, script, and API requests do not
proxy's authentication cookie. The proxy redirects them to the login provider, and CORS or
CSP kills them there.
Trusted mode keeps a real origin and the cookie, so it works. Test cannot catch this, because
Trusted mode keeps a real origin and the cookie, so it works. In trusted mode Codeman
forwards the browser's cookies to the dashboard, and that includes the proxy's own session
cookie unless the proxy removes it from what it forwards to Codeman (the Caddy example in
[Multi-User Mode](Multi-User-Mode#single-sign-on-through-a-reverse-proxy) does). Test cannot catch this, because
it checks the server's reach, not the browser's.
## Security notes
+14 -4
View File
@@ -142,6 +142,14 @@ File paths in a session are links. That works in two places:
render as underlined monospace links. A Markdown link whose target is a path
(`[report](/tmp/run/report.json)`, the way Codex cites files) opens the same way.
In a Codex session, with the **Codex files** setting on (App Settings > Header & Panels,
per device, off by default), clicking a file name Codex underlined opens it in Codeman's
preview when it names a single supported file from the conversation; anything else goes to
Codex as before. The same setting adds three more: a **Response files** header button that lists the files linked in
the latest reply (desktop only), a file name in Codex's own sidebar opening the preview when it
matches a single linked file, and a **Dock** button that, on a wide window with a single
terminal, switches between a preview beside the terminal and a floating one.
Clicking one opens it in the preview: images and PDFs render, video and audio play with a
working scrub bar, documents convert, text shows inline, Markdown renders and HTML opens as a
page. The exception is a plain text file (a log, `.txt`, `.json`, code) inside the workspace
@@ -254,14 +262,16 @@ Images (png, jpg, gif, webp, bmp, heic) are re-encoded on the device before they
goes as is, so it keeps its frames), and HEIC from an iPhone is converted to JPEG. Videos (mp4, webm, mov, m4v, ogv) are stored as recorded,
up to 1 GB each by default (`CODEMAN_MAX_PASTE_VIDEO_BYTES`); they stream to disk rather than
through server memory. Documents are the office formats (pdf, docx, pptx, xlsx, zip) and the
text family (txt, md, csv, tsv, json, log, yaml, yml, xml). Each is checked on the way in,
text family (txt, md, csv, tsv, json, log, yaml, yml, xml, html, htm). Each is checked on the way in,
against its file signature for the binary formats and against its encoding for text (UTF-8,
no NUL bytes), so a script renamed to `.pdf` is refused while a `.txt` can hold any text at
all. A text file in another encoding is refused with a message saying it is not UTF-8 (or that
it is UTF-16, which Excel's "Unicode Text" and Notepad's "Unicode" produce); save it as UTF-8
(in Excel, "CSV UTF-8") and attach it again. Files with script or page extensions (sh, py,
js, html) are not accepted, since a prompt upload is something for the agent to read, not
something for Codeman to store and serve. A document keeps a trimmed copy of its original
(in Excel, "CSV UTF-8") and attach it again. HTML is accepted because AI tools write
specifications and reports as HTML as often as Markdown; an attached page is stored for the
agent to read (the File Viewer shows its source; Codeman never renders it as a page). Files with script
extensions (sh, py, js) are not accepted, since a prompt upload is something for the agent to
read, not something to run. A document keeps a trimmed copy of its original
name, letters, digits, dot, dash and underscore with anything else turned into a dash, so
`Q3 report.pdf` is findable as `paste-<time>-<id>-Q3-report.pdf`; a name made entirely of
other characters saves without one. Uploads are refused for remote (SSH) sessions, whose
+35 -10
View File
@@ -1185,9 +1185,20 @@ ensure_sudo() {
if ! command -v sudo &>/dev/null; then
die "sudo is required but not installed. Please install packages manually or run as root."
fi
# A sudo that runs without a password (NOPASSWD, or the timestamp
# sudo_session_try keeps warm) needs no terminal and nothing validated.
# `sudo -v` is no substitute for this test: it asks for a password as soon as
# ONE sudoers entry of the account asks for one, so an account in the sudo
# group with a NOPASSWD entry of its own (the cloud-image layout) runs
# `sudo <command>` freely and is refused by `sudo -v` (measured on sudo 1.9.15).
if sudo -n true 2>/dev/null; then
return 0
fi
# Validate sudo access
# When piped (curl | bash), stdin is the pipe — redirect from /dev/tty so sudo can prompt
if [[ -e /dev/tty ]]; then
# When piped (curl | bash), stdin is the pipe: redirect from /dev/tty so sudo can prompt.
# Only when it can be opened (see tty_openable): with no terminal at all, sudo gets
# its chance as it is and fails by itself when it would have to ask.
if tty_openable; then
if ! sudo -v 2>/dev/null < /dev/tty; then
die "Failed to obtain sudo privileges."
fi
@@ -1217,8 +1228,9 @@ ensure_homebrew() {
fi
info "Installing Homebrew first..."
# When piped (curl | bash), stdin is the pipe — Homebrew needs TTY for sudo password prompt
if [[ -e /dev/tty ]]; then
# When piped (curl | bash), stdin is the pipe: Homebrew needs TTY for sudo password prompt.
# With no terminal to open (see tty_openable) it runs unattended instead.
if tty_openable; then
/bin/bash -c "$(download_to_stdout https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" < /dev/tty
else
NONINTERACTIVE=1 /bin/bash -c "$(download_to_stdout https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
@@ -2019,9 +2031,21 @@ fetch_source_archive() {
# the keyboard even though the user is sitting at a terminal. These helpers
# prompt via /dev/tty whenever a real terminal is available, and only fall back
# to defaults when there is genuinely none (CI, truly headless pipes).
# True when /dev/tty can really be OPENED. The node is there on every Linux and
# macOS, also for a process with no controlling terminal (su -c, cron, a CI
# runner, cloud-init, a container started without -t): `[[ -e /dev/tty ]]` says
# yes there, and a `< /dev/tty` behind it fails before the command ever runs.
# That ended a headless install with a working passwordless sudo on "Failed to
# obtain sudo privileges". Opening the node is the only test, so every redirect
# from /dev/tty asks this first, never `-e`.
tty_openable() {
{ : < /dev/tty; } 2>/dev/null
}
has_tty() {
[[ -t 0 ]] && return 0
{ : < /dev/tty; } 2>/dev/null
tty_openable
}
read_reply() {
@@ -2102,7 +2126,7 @@ sudo_session_try() {
if ! sudo -n true 2>/dev/null; then
echo "" >&2
info "Some steps need administrator rights. You will be asked for your password once."
if [[ -e /dev/tty ]]; then
if tty_openable; then
sudo -v < /dev/tty || return 1
else
sudo -v || return 1
@@ -2124,7 +2148,7 @@ sudo_session_start() {
if sudo_session_try; then
return 0
fi
if [[ -e /dev/tty ]]; then
if tty_openable; then
die "Failed to obtain sudo privileges."
fi
die "Failed to obtain sudo privileges. Try running the script directly instead of piping."
@@ -2920,8 +2944,9 @@ offer_install_tailscale() {
sudo_session_start
info "Running the official Tailscale installer..."
# When piped (curl | bash), stdin is our pipe: give the child installer
# the real terminal so its own sudo prompt works.
if [[ -e /dev/tty ]]; then
# the real terminal so its own sudo prompt works. A run with no terminal
# to open (see tty_openable) hands it stdin as it is.
if tty_openable; then
if ! sh -c "$(download_to_stdout https://tailscale.com/install.sh)" < /dev/tty; then
warn "Tailscale installation failed."
return 1
@@ -2966,7 +2991,7 @@ ensure_tailscale_login() {
if "$ts_bin" up --timeout=300s; then up_ok="1"; fi
else
sudo_session_start
if [[ -e /dev/tty ]]; then
if tty_openable; then
if run_as_root "$ts_bin" up --timeout=300s < /dev/tty; then up_ok="1"; fi
else
if run_as_root "$ts_bin" up --timeout=300s; then up_ok="1"; fi
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "aicodeman",
"version": "1.52.0",
"version": "1.52.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "aicodeman",
"version": "1.52.0",
"version": "1.52.1",
"hasInstallScript": true,
"license": "MIT",
"workspaces": [
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "aicodeman",
"version": "1.52.0",
"version": "1.52.1",
"description": "Self-hosted mission control for AI coding agents: run Claude Code, Codex, OpenCode, Gemini, DeepSeek, Grok and more 24/7 in tmux, from any device.",
"mcpName": "io.github.Ark0N/codeman",
"type": "module",
+6 -1
View File
@@ -449,9 +449,14 @@
dx = Math.max(minDx, Math.min(maxDx, dx));
drag.root.style.transform = 'translateX(' + dx + 'px)';
var centre = r0.left + r0.width / 2 + dx;
// A tab after the dragged one is passed once the centres meet, not only once they cross:
// the clamp stops a tab dragged all the way right with its centre ON the last tab's
// centre, and a strict comparison there left it one place short of the end.
var to = 0;
for (var i = 0; i < rects.length; i++) {
if (i !== drag.from && centre > rects[i].left + rects[i].width / 2) to++;
if (i === drag.from) continue;
var c = rects[i].left + rects[i].width / 2;
if (i > drag.from ? centre >= c : centre > c) to++;
}
drag.to = to;
drag.roots.forEach(function (r, i) {
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "codeman",
"description": "Drive Codeman, the self-hosted session manager for AI coding agents, from inside a Claude Code session: spawn worker sessions, prompt them, wait for them, read their answers, clean up. Acts inside a Codeman-managed session; outside one it only reads saved Codex conversations offline.",
"version": "1.52.0",
"version": "1.52.1",
"author": {
"name": "Ark0N",
"url": "https://github.com/Ark0N"
+28 -21
View File
@@ -1,20 +1,21 @@
#!/usr/bin/env node
/**
* @fileoverview `npm run release`: `changeset publish` with `README.zh-CN.md` moved aside.
* @fileoverview `npm run release`: `changeset publish` with the translated READMEs moved aside.
*
* npmjs.com renders the package's top-level `readme`, and npm picks it at publish time:
* @npmcli/package-json's normalize globs `{README,README.*}` in the package root UNSORTED and
* keeps the first `.md` it sees. With `README.zh-CN.md` next to `README.md` that was the
* Chinese one on this machine and on CI, so npmjs.com showed the Chinese README for months.
* Every translated root README (`README.zh-CN.md`, `README.ja.md`) is moved aside the same way.
* `files` cannot help: npm-packlist always includes every root `README.*`.
*
* Renaming the file would break every link to it, so for the length of the publish only it
* Renaming the files would break every link to them, so for the length of the publish only each
* moves to a name npm does not treat as a readme (a leading dot), and is put back afterwards,
* whatever the publish did. The move happens HERE, inside the publish command, never as a
* step before `changesets/action` in release.yml: that action also runs the version path and
* commits the working tree into its version PR, which would commit the deletion.
*
* A previous run killed between the move and the restore leaves the aside copy behind; the
* A previous run killed between the move and the restore leaves an aside copy behind; the
* next run puts it back first. `xterm-zerolag-input` (packages/) has only a README.md.
*
* node scripts/npm-release.mjs what the Release workflow runs (via `npm run release`)
@@ -24,34 +25,40 @@ import { spawnSync } from 'node:child_process';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
export const HIDDEN_README = 'README.zh-CN.md';
export const ASIDE_NAME = '.README.zh-CN.md.release-aside';
export const HIDDEN_READMES = ['README.zh-CN.md', 'README.ja.md'];
/** @param {string} name */
export const asideName = (name) => `.${name}.release-aside`;
export const HIDDEN_README = HIDDEN_READMES[0];
export const ASIDE_NAME = asideName(HIDDEN_README);
/**
* Runs `publish` with `HIDDEN_README` moved aside in `root`, restoring it afterwards, also
* when `publish` fails or throws. Returns the exit code `publish` returned.
* Runs `publish` with every `HIDDEN_READMES` file moved aside in `root`, restoring them
* afterwards, also when `publish` fails or throws. Returns the exit code `publish` returned.
*
* @param {{ root: string, publish: () => number, log?: (msg: string) => void }} opts
* @returns {number}
*/
export function publishWithReadmeAside({ root, publish, log = (msg) => console.log(msg) }) {
const original = join(root, HIDDEN_README);
const aside = join(root, ASIDE_NAME);
if (existsSync(aside) && !existsSync(original)) {
renameSync(aside, original);
log(`npm-release: restored ${HIDDEN_README} left aside by an earlier run`);
}
const moved = existsSync(original);
if (moved) {
renameSync(original, aside);
log(`npm-release: ${HIDDEN_README} moved aside so npm picks README.md as the readme`);
}
const moved = [];
try {
for (const name of HIDDEN_READMES) {
const original = join(root, name);
const aside = join(root, asideName(name));
if (existsSync(aside) && !existsSync(original)) {
renameSync(aside, original);
log(`npm-release: restored ${name} left aside by an earlier run`);
}
if (existsSync(original)) {
renameSync(original, aside);
moved.push(name);
log(`npm-release: ${name} moved aside so npm picks README.md as the readme`);
}
}
return publish();
} finally {
if (moved) {
renameSync(aside, original);
log(`npm-release: ${HIDDEN_README} restored`);
for (const name of moved) {
renameSync(join(root, asideName(name)), join(root, name));
log(`npm-release: ${name} restored`);
}
}
}
+16 -5
View File
@@ -71,6 +71,20 @@ function renderToken(value: string, style: QuoteStyle | undefined): string {
}
}
/**
* The value an enum param resolves to: the caller's when it is a declared one, else the
* default. Exported so `applyRootValues()` (root-launch.ts) judges the same value the
* renderer is about to emit, rather than restating this rule.
*/
export function resolveEnumValue(
spec: Extract<ParamSpec, { type: 'enum' }>,
raw: string | boolean | undefined
): string | undefined {
if (raw === undefined) return spec.default;
const s = String(raw);
return spec.values.includes(s) ? s : spec.default;
}
/** Resolve one parameter to a plain string, or undefined if it is unset / invalid. */
function resolveParam(
name: string,
@@ -82,13 +96,10 @@ function resolveParam(
if (spec.type === 'engine') return engineValues[spec.source];
const raw = params[name];
if (raw === undefined) return spec.type === 'enum' ? spec.default : undefined;
if (spec.type === 'enum') return resolveEnumValue(spec, raw);
if (raw === undefined) return undefined;
if (spec.type === 'bool') return typeof raw === 'boolean' ? String(raw) : undefined;
if (spec.type === 'enum') {
const s = String(raw);
return spec.values.includes(s) ? s : spec.default;
}
// token
const s = String(raw);
return matchesPattern(spec.pattern, s) ? s : undefined;
+79
View File
@@ -0,0 +1,79 @@
/**
* @fileoverview The launch params a CLI takes a different value for when it is started as
* root. Pure: the caller says whether the launch runs as root, this module never asks.
*
* Claude Code refuses `--dangerously-skip-permissions` under uid 0 and exits, so a Codeman
* server that runs as root (a VPS, an LXC container) showed a dead pane for every local
* Claude session, the default permission mode being exactly that flag. Docker cases already
* answer the same refusal for a root container with `overlays.docker.rootCommand`; this is
* the host-level form, for a CLI the server process starts as its own child.
*
* Which value gives way to which is registry DATA (`ParamSpec.rootValue` on an enum param),
* so no code here or at the call sites names a CLI. `applyRootValues()` runs BEFORE the argv
* engine and only rewrites the param values handed to it: the engine, and with it every
* command line of a launch that is not root, is untouched.
*
* ⚠️ Local launches only. A remote or Docker launch runs under another account, which the
* server's uid says nothing about; those keep their own handling (`buildRemoteLaunchCommand`,
* `rootCommand`). The callers decide that, by passing `runsAsRoot` false.
*
* @module config/cli-registry/root-launch
*/
import { resolveEnumValue, type ParamValues } from './argv.js';
import type { CliLaunch } from './types.js';
/** One param that was launched with its `rootValue` instead of the value it resolved to. */
export interface RootValueChange {
param: string;
from: string;
to: string;
}
/**
* Apply every declared `rootValue` to `params`.
*
* Returns the SAME `params` object when nothing changes (not root, or no param whose
* resolved value has a replacement), so a caller can rely on a launch that is not root
* rendering from exactly the values it passed in. Otherwise a copy, with `changes` naming
* what was swapped so the caller can log it.
*
* The value judged is the one the renderer would emit: an absent or undeclared value counts
* as the param's default, which is how the default permission mode is caught although no
* caller ever sends it.
*/
export function applyRootValues(
launch: CliLaunch,
params: ParamValues,
runsAsRoot: boolean
): { params: ParamValues; changes: RootValueChange[] } {
const changes: RootValueChange[] = [];
if (!runsAsRoot) return { params, changes };
let out = params;
for (const [name, spec] of Object.entries(launch.params)) {
if (spec.type !== 'enum' || !spec.rootValue) continue;
const from = resolveEnumValue(spec, params[name]);
if (from === undefined || !Object.hasOwn(spec.rootValue, from)) continue;
const to = spec.rootValue[from];
// Schema-validated at load; belt and braces, since a value outside `values` would
// resolve back to the default, which is the very value being replaced.
if (to === from || !spec.values.includes(to)) continue;
if (out === params) out = { ...params };
out[name] = to;
changes.push({ param: name, from, to });
}
return { params: out, changes };
}
/**
* The one log line for a launch that took a `rootValue`. `what` names the launch ("Claude
* Code session 0f9c2b14"); the wording stays free of any CLI's vocabulary because the
* params and values in it are the registry's own.
*/
export function describeRootValueChanges(what: string, changes: readonly RootValueChange[]): string {
const swapped = changes.map((c) => `${c.param} "${c.from}" as "${c.to}"`).join(', ');
return (
`${what} is launched with ${swapped}: the Codeman server runs as root (uid 0), and the CLI refuses ` +
`the configured value under root. Run Codeman as a normal user to get the configured value back.`
);
}
+30 -1
View File
@@ -67,7 +67,13 @@ const condSchema: z.ZodType<import('./types.js').Cond> = z.lazy(() =>
const paramSpecSchema = z.union([
z
.object({ type: z.literal('enum'), values: z.array(z.string()).min(1).max(16), default: z.string().optional() })
.object({
type: z.literal('enum'),
values: z.array(z.string()).min(1).max(16),
default: z.string().optional(),
// Cross-checked against `values` in launchSchema's superRefine below.
rootValue: z.record(z.string(), z.string()).optional(),
})
.strict(),
z.object({ type: z.literal('bool') }).strict(),
z.object({ type: z.literal('token'), pattern: z.enum(TOKEN_PATTERNS as [string, ...string[]]) }).strict(),
@@ -145,6 +151,29 @@ const launchSchema = z
});
}
}
// `rootValue` swaps one declared value for another when the server runs as root. A key or
// a replacement outside `values` could never apply (or would launch with a value no arg
// tests for), and a replacement that is itself replaced would make the outcome depend on
// how many passes the reader makes.
for (const [paramName, spec] of Object.entries(launch.params)) {
if (spec.type !== 'enum' || !spec.rootValue) continue;
for (const [from, to] of Object.entries(spec.rootValue)) {
const path = ['params', paramName, 'rootValue', from];
if (!spec.values.includes(from)) {
ctx.addIssue({ code: 'custom', message: `rootValue key "${from}" is not one of this param's values`, path });
}
if (!spec.values.includes(to)) {
ctx.addIssue({ code: 'custom', message: `rootValue "${to}" is not one of this param's values`, path });
}
if (to === from || Object.hasOwn(spec.rootValue, to)) {
ctx.addIssue({
code: 'custom',
message: `rootValue "${to}" must be a value that is launched as it is under root`,
path,
});
}
}
}
if (launch.legacyConfigAliases) {
for (const paramName of Object.keys(launch.legacyConfigAliases)) {
if (!paramNames.has(paramName)) {
+7
View File
@@ -142,6 +142,13 @@ const CLAUDE: CliEntry = {
type: 'enum',
values: ['dangerously-skip-permissions', 'auto', 'normal', 'allowedTools'],
default: 'dangerously-skip-permissions',
// ⚠️ Claude Code REFUSES the bypass flag under uid 0 ("cannot be used with root/sudo
// privileges for security reasons") and exits, so under a server that runs as root (a
// VPS, an LXC container) every local session was a dead pane, this being the default.
// There it starts as `normal` and asks. The same refusal `overlays.docker.rootCommand`
// below answers for a root container; the other three modes do not carry the flag
// and stay as they are. Never force the bypass back on with `IS_SANDBOX`.
rootValue: { 'dangerously-skip-permissions': 'normal' },
},
allowedTools: { type: 'token', pattern: 'tool-list' },
model: { type: 'token', pattern: 'model-claude' },
+19 -1
View File
@@ -45,7 +45,25 @@ export type EngineValue =
* the only ones that need a pattern; `engine` params are produced in code.
*/
export type ParamSpec =
| { type: 'enum'; values: string[]; default?: string }
| {
type: 'enum';
values: string[];
default?: string;
/**
* The value this param takes INSTEAD when the Codeman server process runs as uid 0 and
* the launch is LOCAL (the CLI is then a child of that process, so it runs as root too).
* Keyed by the value the param would otherwise resolve to, the default included; a
* value with no key is launched as it is.
*
* For a value the CLI REFUSES under root, where the alternative is a pane that dies at
* once. It is the host-level form of `overlays.docker.rootCommand`, which answers the
* same refusal for a container whose exec user is uid 0. Remote and Docker launches
* never read it: the server's uid says nothing about the account on the other side.
* Applied by `applyRootValues()` (root-launch.ts); the schema requires every key and
* every replacement to be one of `values`, and no replacement to be replaced again.
*/
rootValue?: Record<string, string>;
}
| { type: 'bool' }
| { type: 'token'; pattern: TokenPattern }
| { type: 'engine'; source: EngineValue };
+318
View File
@@ -0,0 +1,318 @@
/**
* @fileoverview Trusted reverse-proxy identity (multi-user mode, opt-in, off by default).
*
* Lets an authenticating reverse proxy on the same host (oauth2-proxy behind Caddy or
* nginx, Apache mod_auth_openidc, Authelia, ...) sign users in through an identity
* provider such as Entra ID, Google or Keycloak, instead of the Basic-auth password
* prompt. The proxy authenticates the person and forwards two headers:
*
* X-Codeman-Proxy-Secret: <the shared secret>
* X-Codeman-User: <codeman username>
*
* Codeman accepts the identity only when ALL of these hold:
* - multi-user mode is on (the username must name an existing, enabled account; there
* is no auto-provisioning, so an admin still decides who has an account);
* - a secret is configured: at least 32 printable ASCII characters, from
* `CODEMAN_TRUSTED_PROXY_SECRET_FILE` (preferred) or `CODEMAN_TRUSTED_PROXY_SECRET`;
* - the request arrives over a loopback socket (`req.ip`, which ignores
* X-Forwarded-For because Fastify runs with `trustProxy: false`);
* - the presented secret matches (timing-safe).
*
* What the secret does and does not separate: every process on the host reaches the
* loopback port, so loopback alone proves nothing, and the secret is what a local process
* lacks. It is not a boundary against code that can read the secret file or Codeman's
* memory, i.e. anything running as Codeman's OS account (see the multi-user threat
* model: sessions share that account). To keep it out of the obvious places, the value
* is read ONCE and both `CODEMAN_TRUSTED_PROXY_SECRET` and
* `CODEMAN_TRUSTED_PROXY_SECRET_FILE` are then deleted from `process.env`, because every
* session Codeman spawns inherits that environment. The file's resolved path stays in
* this module (`trustedProxySecretFilePath`, `trustedProxySecretFileRealPath`) for the
* sensitive-path blocklist.
*
* A configured setup that can't be used stops the server from starting
* (`trustedProxyConfigError`, thrown from `WebServer.start()`), so a typo never falls
* back silently to password sign-in.
*
* The two headers are taken off every request before anything else sees them
* (`takeTrustedProxyHeaders`, called from the first auth hook), so nothing downstream,
* e.g. the web-tab relay, can forward or log them.
*/
import { readFileSync, realpathSync, statSync } from 'node:fs';
import type { IncomingHttpHeaders } from 'node:http';
import { resolve } from 'node:path';
/** Header carrying the shared secret that proves the request came through the proxy. */
export const TRUSTED_PROXY_SECRET_HEADER = 'x-codeman-proxy-secret';
/** Default header carrying the authenticated Codeman username. */
export const DEFAULT_TRUSTED_PROXY_USER_HEADER = 'x-codeman-user';
/** Minimum secret length; a shorter secret stops the server from starting. */
export const TRUSTED_PROXY_SECRET_MIN_LENGTH = 32;
/**
* The username header is deleted from EVERY request (see takeTrustedProxyHeaders), so it
* must never be a header anything else needs. Allowed by shape, not by a deny list of
* standard headers: an `X-...` extension header (minus the reserved ones below) or the
* conventional `Remote-User`.
*/
const USER_HEADER_RE = /^x-[a-z0-9][a-z0-9-]*$/;
/** Identity headers authenticating proxies commonly send; allowed despite the reserved prefix. */
const ALLOWED_FORWARDED_IDENTITY_HEADERS = new Set([
'x-forwarded-user',
'x-forwarded-email',
'x-forwarded-preferred-username',
]);
const RESERVED_USER_HEADER_PREFIXES = ['x-forwarded-', 'x-codeman-'];
const RESERVED_USER_HEADERS = new Set([
'x-real-ip',
'x-requested-with',
'x-http-method-override',
'x-csrf-token',
'x-xsrf-token',
]);
/** Resolved trusted-proxy configuration, or null when the feature is off. */
export interface TrustedProxyConfig {
secret: string;
/** Lower-cased header name the username is read from. */
userHeader: string;
}
interface LoadedSecret {
secret?: string;
/** Why a configured secret can't be used (never contains the secret). */
problem?: string;
/** Absolute path of `CODEMAN_TRUSTED_PROXY_SECRET_FILE`, when it was set. */
filePath?: string;
/** That path with symlinks resolved, when it could be resolved. */
fileRealPath?: string;
}
let loaded: LoadedSecret | null = null;
/**
* Read the secret once, then delete `CODEMAN_TRUSTED_PROXY_SECRET` and
* `CODEMAN_TRUSTED_PROXY_SECRET_FILE` from `process.env` so sessions spawned later don't
* inherit either. Cached for the process lifetime.
*/
function loadSecret(): LoadedSecret {
if (loaded) return loaded;
const inline = process.env.CODEMAN_TRUSTED_PROXY_SECRET?.trim();
const file = process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE?.trim();
delete process.env.CODEMAN_TRUSTED_PROXY_SECRET;
delete process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE;
const filePath = file ? resolve(file) : undefined;
const fileRealPath = filePath ? realPathOrUndefined(filePath) : undefined;
let secret: string | undefined;
let problem: string | undefined;
if (inline && file) {
problem = 'both CODEMAN_TRUSTED_PROXY_SECRET and CODEMAN_TRUSTED_PROXY_SECRET_FILE are set; set only one';
} else if (file) {
try {
secret = readFileSync(file, 'utf-8').trim() || undefined;
if (!secret) problem = `CODEMAN_TRUSTED_PROXY_SECRET_FILE (${file}) is empty`;
// POSIX modes only; Windows reports synthetic ones.
else if (process.platform !== 'win32' && (statSync(file).mode & 0o077) !== 0) {
problem = `CODEMAN_TRUSTED_PROXY_SECRET_FILE (${file}) is readable by other users; chmod 600 it`;
}
} catch (err) {
problem = `cannot read CODEMAN_TRUSTED_PROXY_SECRET_FILE (${file}): ${(err as NodeJS.ErrnoException).code ?? 'error'}`;
}
} else if (inline) {
secret = inline;
}
if (secret && !problem) {
if (secret.length < TRUSTED_PROXY_SECRET_MIN_LENGTH) {
problem = `the trusted-proxy secret is shorter than ${TRUSTED_PROXY_SECRET_MIN_LENGTH} characters (generate one with: openssl rand -hex 32)`;
} else if (!/^[\x21-\x7e]+$/.test(secret)) {
// Header bytes arrive as latin1 and the env/file value as UTF-8, so anything outside
// printable ASCII could never match.
problem =
'the trusted-proxy secret must be printable ASCII without spaces (generate one with: openssl rand -hex 32)';
}
}
loaded = { secret, problem, filePath, fileRealPath };
return loaded;
}
function realPathOrUndefined(path: string): string | undefined {
try {
return realpathSync(path);
} catch {
return undefined;
}
}
/**
* Read the secret now and remove both variables from `process.env`. Called first in
* `WebServer.start()` and again (a no-op then) at auth setup, before any session is
* spawned or restored, in every mode.
*/
export function initTrustedProxySecret(): void {
loadSecret();
}
/**
* Absolute path of the configured secret file, or null. After the secret was read the
* variable is gone from `process.env`, so this answers from the cached value; before
* that, from the environment. Never reads the file.
*/
export function trustedProxySecretFilePath(): string | null {
if (loaded) return loaded.filePath ?? null;
const file = process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE?.trim();
return file ? resolve(file) : null;
}
/**
* The secret file's path with symlinks resolved, or null (not configured, or it can't be
* resolved). Resolved once when the secret is read; before that, from the environment.
*/
export function trustedProxySecretFileRealPath(): string | null {
if (loaded) return loaded.fileRealPath ?? null;
const file = trustedProxySecretFilePath();
return (file && realPathOrUndefined(file)) ?? null;
}
/** Test-only: forget the cached secret so the next call re-reads the environment. */
export function resetTrustedProxySecretForTests(): void {
loaded = null;
}
/** The configured username header (lower-cased), or the default. Not validated. */
function rawUserHeader(): string {
return process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER?.trim().toLowerCase() || DEFAULT_TRUSTED_PROXY_USER_HEADER;
}
/** Why the configured username header can't be used, or null when it is fine. */
function userHeaderProblem(name: string): string | null {
if (name === DEFAULT_TRUSTED_PROXY_USER_HEADER || name === 'remote-user') return null;
if (ALLOWED_FORWARDED_IDENTITY_HEADERS.has(name)) return null;
if (!USER_HEADER_RE.test(name)) {
return `CODEMAN_TRUSTED_PROXY_USER_HEADER (${name}) must be an X-... header or Remote-User`;
}
if (RESERVED_USER_HEADERS.has(name) || RESERVED_USER_HEADER_PREFIXES.some((p) => name.startsWith(p))) {
return `CODEMAN_TRUSTED_PROXY_USER_HEADER may not be ${name} (reserved)`;
}
return null;
}
/**
* The username header to strip and read: the configured one when it is usable, the default
* otherwise. Resolve it once (at auth setup) and pass it to `takeTrustedProxyHeaders`. A
* rejected name is never used, so a careless setting can't strip a header others need.
*/
export function resolveTrustedProxyUserHeader(): string {
const name = rawUserHeader();
return userHeaderProblem(name) ? DEFAULT_TRUSTED_PROXY_USER_HEADER : name;
}
/**
* The active configuration, or null when the feature is off: no usable secret, an
* unusable username header, or single-user mode (no named accounts to map onto). The
* unusable cases also stop the start (`trustedProxyConfigError`); this is the second layer.
*/
export function getTrustedProxyConfig(multiUser: boolean): TrustedProxyConfig | null {
const { secret, problem } = loadSecret();
if (!multiUser || !secret || problem) return null;
const userHeader = rawUserHeader();
if (userHeaderProblem(userHeader)) return null;
return { secret, userHeader };
}
/**
* Why a configured trusted-proxy setup can't be used, as the message for the start-up
* refusal, or null when it is fine (not configured, or valid). Never includes the secret.
* Refused: both secret variables set; a secret file that can't be read, is empty or is
* readable by group or others (not checked on Windows); a secret shorter than 32
* characters or not printable ASCII; a secret with multi-user mode off; and a
* `CODEMAN_TRUSTED_PROXY_USER_HEADER` the validation rejects (set at all, secret or not).
*/
export function trustedProxyConfigError(multiUser: boolean): string | null {
const { secret, problem } = loadSecret();
let reason: string | null = null;
if (problem) reason = problem;
else if (secret && !multiUser) reason = 'a trusted-proxy secret is set but multi-user mode is off';
else if (process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER?.trim()) reason = userHeaderProblem(rawUserHeader());
return reason
? `Trusted-proxy sign-in is misconfigured: ${reason}. Fix or remove the setting and start again.`
: null;
}
/** What a request presented, after `takeTrustedProxyHeaders` removed the headers. */
export interface PresentedProxyHeaders {
/** True when the secret header was present at all, even empty. */
secretPresent: boolean;
/** The presented secret (duplicates joined with ", ", so they never match). */
secret: string;
/**
* The presented username exactly as sent ('' when absent). The auth hook normalizes and
* validates it with the user store's own rule. A duplicated header arrives joined
* ("alice, bob"), which that rule rejects, so it is refused with 403.
*/
user: string;
}
/**
* The two other views Node keeps of a request's headers, beside `headers`: the flat
* `[name, value, ...]` list as received and the per-name arrays. Both are optional
* because a light-my-request message (`app.inject`) may lack `headersDistinct`.
*/
export interface RawHeaderViews {
headers?: IncomingHttpHeaders;
rawHeaders?: string[];
headersDistinct?: NodeJS.Dict<string[]>;
}
/**
* Remove `names` (lowercase) from `raw.rawHeaders` and `raw.headersDistinct`, in place.
*
* ⚠️ Order matters on a real `http.IncomingMessage`: its `headers` and `headersDistinct`
* getters are LAZY and walk `rawHeaders` up to a header count stored when the request was
* parsed, so a getter that first runs after a splice reads past the shortened array and
* throws. Both are therefore read (and so cached) BEFORE `rawHeaders` shrinks, and later
* reads return the cached, already stripped objects.
*/
function stripRawHeaderViews(raw: RawHeaderViews, names: readonly string[]): void {
void raw.headers;
const distinct = raw.headersDistinct;
if (distinct && typeof distinct === 'object') {
for (const name of names) delete distinct[name];
}
const list = raw.rawHeaders;
if (!Array.isArray(list)) return;
for (let i = list.length - 2; i >= 0; i -= 2) {
const name = list[i];
if (typeof name === 'string' && names.includes(name.toLowerCase())) list.splice(i, 2);
}
}
/**
* Read the trusted-proxy headers and DELETE them from `headers`, so nothing that later
* copies request headers (the web-tab relay, logging) ever sees the secret. Removes the
* secret header, the default username header and `userHeader` (from
* `resolveTrustedProxyUserHeader`, so always a usable name), whether or not the feature is
* on: a proxy may send them to an instance that has it off. Given the raw message (`raw`,
* the auth hook passes `req.raw`), it removes them from `rawHeaders` and `headersDistinct`
* too, so no view of the request still holds the secret.
*/
export function takeTrustedProxyHeaders(
headers: IncomingHttpHeaders,
userHeader: string = DEFAULT_TRUSTED_PROXY_USER_HEADER,
raw?: RawHeaderViews
): PresentedProxyHeaders {
const rawSecret = headers[TRUSTED_PROXY_SECRET_HEADER];
const rawUser = headers[userHeader];
if (raw) stripRawHeaderViews(raw, [TRUSTED_PROXY_SECRET_HEADER, DEFAULT_TRUSTED_PROXY_USER_HEADER, userHeader]);
delete headers[TRUSTED_PROXY_SECRET_HEADER];
delete headers[DEFAULT_TRUSTED_PROXY_USER_HEADER];
delete headers[userHeader];
return {
secretPresent: rawSecret !== undefined,
secret: Array.isArray(rawSecret) ? rawSecret.join(', ') : (rawSecret ?? ''),
user: Array.isArray(rawUser) ? rawUser.join(', ') : (rawUser ?? ''),
};
}
+39 -1
View File
@@ -14,12 +14,50 @@ import { getAugmentedPath } from './utils/index.js';
import { compareVersions } from './utils/dependency-checker.js';
import { dataPath } from './config/instance.js';
import { getCli } from './config/cli-registry/registry.js';
import { applyRootValues, describeRootValueChanges } from './config/cli-registry/root-launch.js';
import { serverRunsAsRoot } from './utils/server-uid.js';
/** Narrow a registry value back to the wire type; anything else keeps the caller's own mode. */
function isClaudeMode(value: unknown): value is ClaudeMode {
return value === 'dangerously-skip-permissions' || value === 'auto' || value === 'normal' || value === 'allowedTools';
}
/**
* The permission mode a claude process started DIRECTLY by this server gets (the direct-PTY
* fallback and the one-shot `-p` run, both children of the server process).
*
* Under a server that runs as root the bypass mode gives way to the registry's declared
* `rootValue` (`normal`): Claude Code exits on `--dangerously-skip-permissions` under uid 0.
* The tmux path applies the same registry data through `serverRootSpawnOptions()`; this is
* its counterpart for the two launches that never reach the argv engine. Pure: the caller
* says whether the server is root, and `onChange` gets the log line when the mode moved.
*/
export function directLaunchClaudeMode(
claudeMode: ClaudeMode,
runsAsRoot: boolean,
onChange?: (line: string) => void
): ClaudeMode {
const launch = getCli('claude')?.launch;
if (!launch) return claudeMode;
const { params, changes } = applyRootValues(launch, { claudeMode }, runsAsRoot);
const effective = params.claudeMode;
if (changes.length === 0 || !isClaudeMode(effective)) return claudeMode;
onChange?.(describeRootValueChanges('A directly started Claude Code process', changes));
return effective;
}
/**
* Build Claude CLI permission flags based on the configured mode.
* Returns an array of args to pass to the CLI.
*
* ⚠️ Both direct launches (`buildInteractiveArgs`, `buildPromptArgs`) get their flags here,
* so this is where the root downgrade is applied for them: see `directLaunchClaudeMode`.
* The uid is asked at call time (`serverRunsAsRoot()`), never cached.
*/
function buildPermissionArgs(claudeMode: ClaudeMode, allowedTools?: string): string[] {
function buildPermissionArgs(configuredMode: ClaudeMode, allowedTools?: string): string[] {
const claudeMode = directLaunchClaudeMode(configuredMode, serverRunsAsRoot(), (line) =>
console.warn(`[Session] ${line}`)
);
switch (claudeMode) {
case 'dangerously-skip-permissions':
return ['--dangerously-skip-permissions'];
+19 -1
View File
@@ -21,6 +21,7 @@ import { getDiscordStartupHint } from './discord-bridge.js';
import type { CliEntry } from './config/cli-registry/types.js';
import { renderLaunch, type EngineValues, type ParamValues } from './config/cli-registry/argv.js';
import { matchesPattern } from './config/cli-registry/patterns.js';
import { applyRootValues, type RootValueChange } from './config/cli-registry/root-launch.js';
import { buildAdvisorSettings, buildEffortCliArgs, sanitizeCliSessionName } from './session-cli-builder.js';
import { compareVersions } from './utils/dependency-checker.js';
import { resolveSessionCliVersion } from './utils/cli-resolver.js';
@@ -77,6 +78,16 @@ export interface SpawnBridgeOptions {
* passed) by TmuxManager._resolveIdleCompactionOptOut, which records it on the mux record.
*/
idleCompactionOff?: boolean;
/**
* True when this command will run as a child of a server process whose uid is 0: a LOCAL
* launch under a root server. Params that declare a `rootValue` then take it (see
* config/cli-registry/root-launch.ts). Decided by the caller, never here: this bridge also
* renders commands that run under another account (the remote omp relaunch), where the
* server's uid means nothing. Absent or false leaves the command byte-identical.
*/
runsAsServerRoot?: boolean;
/** Told which params took their `rootValue`, so the launch site can log it. Never called with none. */
onRootValue?: (changes: RootValueChange[]) => void;
}
/**
@@ -209,7 +220,14 @@ function gateVersion(entry: CliEntry, explicit: string | null | undefined): stri
export function buildSpawnCommandFromRegistry(entry: CliEntry, options: SpawnBridgeOptions): string | undefined {
if (entry.kind === 'shell' || entry.launch.variants.length === 0) return undefined;
const params = buildParamsFromLegacyConfig(entry, legacyConfigFor(entry, options));
// A value the CLI refuses under root gives way to its declared `rootValue` before the engine
// sees it. Not root: `applyRootValues` hands back the very object it was given.
const { params, changes: rootChanges } = applyRootValues(
entry.launch,
buildParamsFromLegacyConfig(entry, legacyConfigFor(entry, options)),
options.runsAsServerRoot === true
);
if (rootChanges.length > 0) options.onRootValue?.(rootChanges);
const engineValues: EngineValues = {
sessionId: options.sessionId,
+52
View File
@@ -81,6 +81,8 @@ import {
} from './session-cli-registry-bridge.js';
import { keepWarmOn } from './prompt-cache-keepwarm.js';
import type { CliEntry } from './config/cli-registry/types.js';
import { describeRootValueChanges, type RootValueChange } from './config/cli-registry/root-launch.js';
import { serverRunsAsRoot } from './utils/server-uid.js';
import {
resolveStatusLineCliCommand,
readPlanUsageTelemetryEnabled,
@@ -1258,6 +1260,44 @@ export function decideIdleCompactionOptOut(o: {
);
}
/** What `serverRootSpawnOptions()` adds to a `buildSpawnCommand` call; empty for every launch that is not root. */
export interface ServerRootSpawnOptions {
runsAsServerRoot?: true;
onRootValue?: (changes: RootValueChange[]) => void;
}
/**
* The `buildSpawnCommand` options for a launch under a Codeman server that itself runs as
* root (uid 0), which is common on a VPS and in an LXC container.
*
* A CLI started locally is the server's child and runs as root too, and Claude Code exits
* on `--dangerously-skip-permissions` there, so its default launch was a dead pane. With
* these options a param that declares a `rootValue` takes it (registry data, see
* config/cli-registry/root-launch.ts), and the swap is logged once per launch.
*
* ⚠️ The ONE place the tmux launch path asks for the uid. `createSession` and `respawnPane`
* both spread the result into `buildSpawnCommand`, and every local tmux launch (new
* session, resume, dead-pane respawn, `restartCli()`, cron, quick-start, reboot restore) is
* one of those two calls. The two launches with no tmux (direct-PTY fallback, one-shot) get
* the same registry data in `buildPermissionArgs()` (session-cli-builder.ts).
* ⚠️ `launchedElsewhere` (remote, Docker, adopted) returns nothing: that CLI runs under
* another account, and the local command built for it is never used. Docker answers the
* same refusal with `overlays.docker.rootCommand`, by the CONTAINER's uid.
* ⚠️ Not root returns `{}`, so the command line stays byte-identical.
*/
export function serverRootSpawnOptions(o: {
mode: SessionMode;
sessionId: string;
launchedElsewhere: boolean;
}): ServerRootSpawnOptions {
if (o.launchedElsewhere || !serverRunsAsRoot()) return {};
const what = `${getCli(o.mode)?.label ?? o.mode} session ${o.sessionId.slice(0, 8)}`;
return {
runsAsServerRoot: true,
onRootValue: (changes) => console.warn(`[TmuxManager] ${describeRootValueChanges(what, changes)}`),
};
}
export function buildSpawnCommand(options: {
mode: SessionMode;
sessionId: string;
@@ -1292,6 +1332,14 @@ export function buildSpawnCommand(options: {
* gate measuring the RIGHT binary, the local one.
*/
claudeCliVersion?: string | null;
/**
* The command will run as a child of a server process whose uid is 0, so a param declaring
* a `rootValue` takes it. Only ever supplied through `serverRootSpawnOptions()`, which the
* two local launch sites spread in; absent, the command is byte-identical.
*/
runsAsServerRoot?: boolean;
/** Told which params took their `rootValue` (see `serverRootSpawnOptions`). */
onRootValue?: (changes: RootValueChange[]) => void;
}): string {
// Every CLI's command shape is registry DATA, rendered by the argv engine — see
// config/cli-registry/argv.ts for why config can never contain shell text. A `shell`-kind
@@ -2731,6 +2779,8 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
statusLineCommand,
idleCompactionOff,
sessionName: cliName,
// A local launch under a server that runs as root: see serverRootSpawnOptions.
...serverRootSpawnOptions({ mode, sessionId, launchedElsewhere: !!(remote || docker || adopt) }),
});
const config = niceConfig || DEFAULT_NICE_CONFIG;
@@ -3055,6 +3105,8 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
statusLineCommand,
idleCompactionOff,
sessionName: cliName,
// Same as createSession: a respawn under a root server must not bring the refused value back.
...serverRootSpawnOptions({ mode, sessionId, launchedElsewhere: !!(remote || docker || adopt) }),
});
const config = niceConfig || DEFAULT_NICE_CONFIG;
const cmd = wrapWithNice(baseCmd, config);
+6
View File
@@ -50,6 +50,12 @@ export interface UsersFile {
export interface AuthUser {
username: string;
role: UserRole;
/**
* True when a trusted reverse proxy vouched for this request (see
* src/config/trusted-proxy.ts), so no Codeman password was involved. Absent for
* cookie, Basic and QR sign-ins.
*/
viaTrustedProxy?: boolean;
}
/** Admin-facing projection of a user: never carries the password hash. */
+1
View File
@@ -9,6 +9,7 @@
export { BufferAccumulator } from './buffer-accumulator.js';
export { CleanupManager } from './cleanup-manager.js';
export { Debouncer, KeyedDebouncer } from './debouncer.js';
export { KeyedThrottle } from './keyed-throttle.js';
export { startEventLoopMonitor } from './event-loop-monitor.js';
export type { EventLoopMonitorHandle } from './event-loop-monitor.js';
export { StaleExpirationMap } from './stale-expiration-map.js';
+65
View File
@@ -0,0 +1,65 @@
/**
* @fileoverview Per-key throttle: at most one send per key per interval, and the last call in a
* burst is never lost.
*
* The first call for a key in a quiet period sends at once. A call inside the interval after a
* send schedules one trailing send at the interval's end, and later calls collapse into it while
* it is pending. The trailing send runs the newest `send` it was given. Timers are unref'd, so a
* pending send never holds the process open. Its method names match KeyedDebouncer's
* (debouncer.ts): `cancelKey()` forgets one key, and `dispose()` forgets them all, which is how
* it integrates with CleanupManager.
*
* @module utils/keyed-throttle
*/
interface ThrottleState {
lastAt: number;
timer: NodeJS.Timeout | null;
send: () => void;
}
export class KeyedThrottle<K = string> {
private readonly state = new Map<K, ThrottleState>();
constructor(private readonly intervalMs: number) {}
/** Send for `key` now if its interval has passed, else once at the interval's end. */
fire(key: K, send: () => void): void {
let entry = this.state.get(key);
if (!entry) {
entry = { lastAt: 0, timer: null, send };
this.state.set(key, entry);
}
entry.send = send;
// A trailing send is already scheduled, and it covers this call.
if (entry.timer) return;
const wait = entry.lastAt + this.intervalMs - Date.now();
if (wait <= 0) {
entry.lastAt = Date.now();
send();
return;
}
const scheduled = entry;
scheduled.timer = setTimeout(() => {
scheduled.timer = null;
scheduled.lastAt = Date.now();
scheduled.send();
}, wait);
scheduled.timer.unref?.();
}
/** Forget `key`, dropping its pending trailing send. */
cancelKey(key: K): void {
const entry = this.state.get(key);
if (entry?.timer) clearTimeout(entry.timer);
this.state.delete(key);
}
/** Forget every key, dropping every pending send. The CleanupManager integration point. */
dispose(): void {
for (const entry of this.state.values()) {
if (entry.timer) clearTimeout(entry.timer);
}
this.state.clear();
}
}
+36
View File
@@ -0,0 +1,36 @@
/**
* @fileoverview Whether the Codeman server process itself runs as root (uid 0).
*
* A CLI the server starts LOCALLY is its child, so it runs under the same uid, and some
* CLIs refuse part of their own command line there: Claude Code exits on
* `--dangerously-skip-permissions` under root ("cannot be used with root/sudo privileges").
* A server installed and started as root is common on a VPS and in an LXC container, and
* there every such session showed a dead pane.
*
* The answer is read at CALL time, never cached in a module-level const: every local launch
* asks again, and a test stands in for the uid through `stubServerUidForTest()`.
*
* Test hermeticity: under vitest the real uid is never consulted (`false` unless a test
* stubbed one), so the suite gives the same command lines when it is run as root, in a
* container for instance.
*
* @module utils/server-uid
*/
/** A test's stand-in for the process uid: `null` = no stub, `undefined` = a platform with no uid. */
let stubbedUid: number | undefined | null = null;
/**
* True when this process runs as uid 0. False on a platform with no uid (`process.getuid`
* is absent on Windows).
*/
export function serverRunsAsRoot(): boolean {
if (stubbedUid !== null) return stubbedUid === 0;
if (process.env.VITEST) return false;
return typeof process.getuid === 'function' && process.getuid() === 0;
}
/** Test seam: answer as if the server ran under `uid`; `null` puts the hermetic default back. */
export function stubServerUidForTest(uid: number | undefined | null): void {
stubbedUid = uid;
}
+6 -2
View File
@@ -14,6 +14,8 @@
**Tile grid** (`showTileGridButton`, header Tiles button + `Ctrl+Shift+G`, default ON on desktop and OFF on handhelds and touch-primary tablets (primary pointer coarse, `getDefaultSettings()`; a touchscreen laptop keeps ON), desktop-only at 1180px, per-device; tile-grid.js, design `docs/tile-grid-plan.md`): 1 to 6 live sessions side by side (the cap is ONE constant, `TILE_GRID_MAX` in constants.js, owner decision; the layout table still covers 7 to 9, unreachable), each a `TerminalTile` with a header (state dot, harness logo, name, model, menu, zoom, ×; no +, owner decision), laid out by count (`CodemanTileGrid`, constants.js) with draggable column/row dividers, zoom (tmux-style), an Attach overlay, and per-browser persistence (`codeman:tile-grid`, localStorage only: cells with `null` holes, `count`, focus, user zoom, divider fractions, never content; written on every change, kept by EVERY close, restored INSIDE `handleInit` in place of the single-view select, so the main terminal never loads on that page load). While the grid is open the main terminal is PARKED: `activeSessionId` is the focused tile's session, and every main-terminal path that would write, fetch, resize or reconnect stands aside through `_tilesOwnTerminal()` (the WebGL long-task observer included). ⚠️ Every capture a tile fetches (initial, reconnect refresh, `{t:'r'}`, history pull) goes through ONE `TileLoadQueue` (concurrency 1, a deadline covering the body), because each is a synchronous tmux call on the server. ⚠️ Only a USER-initiated pick of a non-tiled session (or `leaveTiles`, a followed link) leaves the grid; an `auto` selection never collapses it, and every app-driven fallback (close, delete, restore) picks a tile. A caller of `closeTileGrid({ reselect: false })` must null `activeSessionId` before any `_cleanupPreviousSession`, or the parked terminal's stale content is saved as a snapshot. ⚠️ The grid and the split are never open together. ⚠️ Tile chords go through `tileShortcutFor` and are swallowed in every xterm key handler BEFORE the Shift+Enter gate; the toggle follows `showTileGridButton` (owner decision: OFF makes the chord inert, it passes through like any unbound key). ⚠️ The Tiles button's click and Ctrl+Shift+G are ONE function, `toggleTileGrid` (owner decision): they open the grid AT ONCE on `tileGridOpenSet` (constants.js): the stored grid EXACTLY as the user left it (owner decision 11: `restoreTileGridCells`, never filled to the count nor trimmed to the window; a cell whose session is gone since is filled from the ranking, a hole the user made stays), else an open split's two, else the open sessions as `rankTileSessions` orders them (working first, keyed off `lastSubmitAt` ONLY, then needing input, then most recent; `_mobileOverviewState`'s states), the active one focused, filled to the remembered count (`codeman:tile-count`, default 6, at most `_tileGridLimit()`) by `tileGridSetForCount`, never a menu. ⚠️ `removeTile(..., { gone: true })` (a session deleted, popped out or refused) keeps the stored `count` so the next open refills that cell; a removal by hand lowers it. Right-click is the 2 / 4 / 6 count menu (`openTileCountMenu`, owner decision 10), which owns its Escape. The button has no native title: its hover card (`_installTileGridHint`, `#tileGridHint`) says it, is its `aria-describedby` (always present, hidden, kept current) and hides in the capture phase on any press, click or right-click, so the menu never opens beside it. ⚠️ The open, the count menu and the toggle's close animate opacity and transform only (the close leaves an inert cloned still copy until the single view's selection settles, at most 700 ms); nothing moves under `prefers-reduced-motion`. ⚠️ Opening builds one tile terminal per frame (`_connectTilesPaced`), so `openTileGrid` returns before the terminals exist: focus is handed over in `_connectTile` (`focusOnConnect`). ⚠️ A divider drag reflows locally per frame and sends ONE resize per affected tile at pointer-up. ⚠️ The grid is CELLS (owner: an empty cell can be any cell): `grid.cells` (id or `null`) is the one source of truth, `grid.ids` a derived getter, never written; the shape still comes from the tile count, a shape change goes through `fitTileCells`, and the stored `ids` carry the cells with `null` holes. ⚠️ A tile moves (its header dragged or its tab dropped onto another tile or an empty cell, `Ctrl+Shift+Arrows`) ONLY through `_reorderTiles`: never a remount, reconnect or reload, and since sizes belong to the cells only a tile whose cell size changed fits; off while a tile is zoomed. The header drag carries its own type, never text, and is not `draggedTabId`; the header focuses on click, never on press, so a cancelled drag changes nothing. The arrow chords skip text fields. ⚠️ Sessions Run from this tab join the open grid (`_joinTileGridFromRun`, called from `_ensureCreatedSessionVisible`); sessions created elsewhere never do. SuchLine truncated
**Chat view** (`chat-view.js`, per-device `chatViewDefault`, default OFF, never on phones; design in [`docs/chat-view-plan.md`](../../docs/chat-view-plan.md)): a local or Docker Claude session in the main view can show its conversation, read from the transcript, as text; to type, the user switches to the Terminal view. `chatViewEligible()` takes the modes whose CLI declares `transcript: 'claude-jsonl'` (`window.__codemanChatViewModes`, never a mode id) and refuses a remote or an adopted session and a phone. The per-device `showChatViewSwitch` (default OFF, owner decision for 1.52.1: only an explicit `true` shows the switch, read as `=== true`, so nobody sees it without choosing it) shows or hides only the Chat / Terminal switch; the view and Alt+Shift+C work either way. ⚠️ The terminal stays mounted, attached and sized under the chat layer, so switching views never resizes the PTY. Focus that lands on the hidden terminal moves to the conversation, and `body.chat-view-showing` hides the keyboard accessory bar and, on touch devices, the CJK input field while Chat shows, because both write into the pane. While the tile grid owns the terminal, the chat view is hidden whatever the session's choice (`_tilesOwnTerminal()`, synced from tile-grid.js). A pending `permission_prompt` or `elicitation_dialog` hook shows a notice whose button switches to the terminal. Codeman's keep-alive turn shows no status line. i18n.js skips the `data-i18n-skip` conversation, so the strings drawn there go through `_chatViewT()`. Tests: `test/chat-view.test.ts`, `test/chat-view-i18n.test.ts`.
**Terminal touch gestures: link taps and text selection**: on touch devices xterm's linkifier and SelectionService never see the gesture, so both are driven explicitly (terminal-ui.js). ⚠️ A tap activates the link under it through the SAME provider as the hover linkifier (`_terminalLinkAtPoint`), synchronously inside `touchend` (keeps the user gesture `window.open` needs) and BEFORE any mouse report; the caret's logical line (`_tapIsOnCaretLine`) and TUI-owned rows (`_isActionableMobileTerminalTap`) keep their meaning. ⚠️ Gate on the caret line, never on tap intent (a shell calls every tap `'input'`). ⚠️ Long-press selects via xterm's public `select()`; keep the three guards: suppress the compat mouse pair after `touchend`, the bounded focus guard + `contextmenu` suppression for the platform long-press, and no closing `terminal.focus()` on phones. ⚠️ A sideways drag belongs to the session swipe (`SwipeHandler`, mobile-handlers.js): the touch handler locks the dominant axis on the first travel past the tap slop (`panAxis`: `y` scrolls, `x` pans a terminal wider than its box, `swipe` otherwise) and publishes it as `app._terminalGestureAxis`; a `swipe` drag neither scrolls nor ends as a tap on the session being left until it passes the swipe's own vertical drift limit (`SwipeHandler.maxVerticalDrift`), where it is handed back to the scroll as `y` (a scroll that opens on a thumb arc), and the swipe stands aside for `x`/`y`, a touch selection, a second finger and surfaces with controls of their own (`IGNORE_SELECTOR`; the phone overview and welcome screen are deliberately not listed). A swipe is 80 px within 500 ms with at most 50 px of vertical drift at any point; a touch starting outside the terminal (the home screen) resets the published axis, and a lift the terminal consumed (`defaultPrevented`, its selection gesture) is never a swipe (`test/session-swipe-gesture.test.ts`). Tests: `test/terminal-touch-tap.test.ts`. → [architecture-invariants#terminal-touch-gestures-link-taps-and-text-selection](../../docs/architecture-invariants.md#terminal-touch-gestures-link-taps-and-text-selection)
**Auto Copy (copy-on-select)** (`autoCopySelection`, per-device, default OFF): a finished terminal selection lands on the clipboard with no keystroke. ⚠️ Copy at the END of a gesture, never in `onSelectionChange` (per-cell); it only arms `_autoCopyPending` and a document-level `mouseup` flushes. ⚠️ The flush must be SYNCHRONOUS in the handler (both clipboard paths need user activation); never defer it to a timer. ⚠️ Touch needs its own calls from `_endTouchSelectionGesture()`/`_selectTouchSelectionLine()` (no mouseup arrives). ⚠️ Unlike `copyTerminalSelection()`, never clear the selection or focus the terminal; restore prior focus. Guards are pure in `decideAutoCopy()` (constants.js, 1M-char cap, refused not truncated). Tests: `test/terminal-auto-copy.test.ts`. → [architecture-invariants#auto-copy-copy-on-select](../../docs/architecture-invariants.md#auto-copy-copy-on-select)
@@ -60,7 +62,7 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
**Where a dialog hands the keyboard back to** (`FocusTrap.focusToReturn()`, keyboard-accessory.js): a dialog that saves focus on open asks this, never `document.activeElement`. By the time a dialog opens, the mouse press that opened it has already moved focus (onto the pressed control in Chromium and Firefox, onto `<body>` in WebKit on macOS, where a button takes no focus from the mouse), and restoring that left the keyboard out of the terminal until it was clicked. The answer is the typing field (textarea, text-like input, editable region) that had focus at `pointerdown`, whenever focus now sits on the pressed control or on `<body>`. ⚠️ `pointerdown`, never `mousedown` or `click`: moving focus is `mousedown`'s default action, so only the earlier event still sees what had the keyboard. ⚠️ One press, from a typing field, by mouse: the field of an earlier press is not carried over (it can be behind a dialog opened since), a press that began on a button (a dialog opened inside a dialog) still returns to the pressed control, any key but a held modifier forgets the press (a keyboard user gets the control back), and a finger or pen records nothing (a focused field there means the on-screen keyboard). The one press that inherits a field is a press on an item inside `[role="menu"]`, from the press that opened the menu (a tile's menu button, then "Session options"); a menu that hands focus back to its trigger before running the item is not covered. ⚠️ Asking spends the press, so nothing pressed inside the opening dialog can hand the keyboard to a field behind it; call it once, when the dialog opens. Callers: `FocusTrap.activate()` (App Settings, Session Options, Help, Kill All, the phone composer) and `_rememberOverlayFocus()` (command palette, Session Manager); the local model window places its own focus. A dialog that never handed focus back (most of the small confirm dialogs) is not changed by this. Tests: `test/dialog-focus-return.test.ts`, `test/dialog-focus-return.browser.test.ts` (real Chromium, not in the gate).
**Per-device vs synced settings**: the `displayKeys` set in settings-ui.js is a **client-side merge policy**, not a wire filter. A display key seeds from the server only when localStorage has no value for it, which is what prevents one device overwriting another; `showPlanUsageLimits` is additionally `delete`d from the incoming payload outright. Separately, `SettingsUpdateSchema` is `.strict()` and simply **does not declare** `skin`, `showFileViewerButton`, `showCronButton`, `webglRendererEnabled`, `localEchoEnabled`, `keyboardHoldsRows`, `cjkInputEnabled`, `cjkInputHoldUntilEnter`, `extendedKeyboardBar`, or `historyReloadAction`, so sending one of those is a validation error. The rest (`showResponseViewer`, `showPlanUsageLimits`, `language`, and most `show*` keys) ARE in the schema and do persist server-side; they are per-device by client policy only. ⚠️ Adding a new per-device setting means deciding **both** questions: membership in `displayKeys`, and presence in the schema.
**Per-device vs synced settings**: the `displayKeys` set in settings-ui.js is a **client-side merge policy**, not a wire filter. A display key seeds from the server only when localStorage has no value for it, which is what prevents one device overwriting another; `showPlanUsageLimits` is additionally `delete`d from the incoming payload outright. Separately, `SettingsUpdateSchema` is `.strict()` and simply **does not declare**, among others, `skin`, `showFileViewerButton`, `showCronButton`, `webglRendererEnabled`, `localEchoEnabled`, `keyboardHoldsRows`, `cjkInputEnabled`, `cjkInputHoldUntilEnter`, `extendedKeyboardBar`, `historyReloadAction`, `chatViewDefault`, or `showChatViewSwitch`, so sending one of those is a validation error. Others (`showResponseViewer`, `showPlanUsageLimits`, `language`, and many `show*` keys) ARE in the schema and do persist server-side; they are per-device by client policy only. ⚠️ Adding a new per-device setting means deciding **both** questions: membership in `displayKeys`, and presence in the schema.
**Settings surface** (`#appSettingsModal` + `#sessionOptionsModal` + `#createCaseModal`): one `set-*` language shared through a single `:is(...)` id scope in styles.css. App Settings' rail is a table of contents over ONE scrolling document (`switchSettingsTab` scrolls); Session Options and Add Case really switch (`switchOptionsTab` / `switchCaseModalTab`), and their larger per-modal size blocks are the design, not drift. ⚠️ **The load/save contract is `getElementById` by id**: renaming or dropping a control id silently stops it loading or saving. ⚠️ The Session Options "Session" entry still keys off `context` (label-only rename). ⚠️ Add Case keeps its legacy `.form-row` markup via an adapter; every `<details>` there needs `.set-adv-chev` plus both marker suppressions. ⚠️ Model cards and the effort segment are views over hidden `<select>`s, which stay the source of truth. ⚠️ `.modal-tabs*` classes are retired; `admin-ui.js` needs `.set-rail-items` + `.set-doc` to survive any restructure. Guard: `test/app-settings-structure.test.ts`. → [architecture-invariants#settings-surface-app-settings-session-options-add-case](../../docs/architecture-invariants.md#settings-surface-app-settings-session-options-add-case)
@@ -98,6 +100,8 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
**SSE staleness watchdog** (`computeSseStale()` in constants.js, `_checkSseStale()` + a 5s interval in app.js): an `EventSource` can stop delivering without erroring, so the client forces a reconnect when nothing arrives. ⚠️ The server keepalive must stay the named `sse:heartbeat` event (`cleanupDeadClients()`, sse-stream-manager.ts), never an SSE comment, which `EventSource` cannot observe; its no-op client listener must stay registered. ⚠️ Judge staleness only while `connected` and online (the loop breaker). ⚠️ The liveness stamp lives inside `addListener`. ⚠️ Clear the interval only at the top of `connectSSE()`, or intervals stack. ⚠️ The watchdog cannot see an attempt that never OPENS (no response headers: no `open`, no `error`, never `connected`), so each attempt is bounded by `SSE_CONNECT_TIMEOUT_MS` (15s, `CodemanSseStale.CONNECT_TIMEOUT_MS`) and then retried through `_handleSseConnectionFailure()`, the same backoff `onerror` uses. Its timer is cleared at the top of `connectSSE()` BEFORE the offline early return, on `open`, and in `_handleSseConnectionFailure()`; the timer and the handler both ignore an `EventSource` that has been replaced. The window `offline` handler leaves it running on purpose (`navigator.onLine` can report offline on a working network). Tests: `test/sse-connect-timeout.test.ts`. → [architecture-invariants#sse-staleness-watchdog](../../docs/architecture-invariants.md#sse-staleness-watchdog)
**Z-index layers** (keep new overlays consistent with this stack): local echo overlay (7; with local echo on it also draws the iOS IME composition preview, as an underlined tail after its pending text via `setComposition`), iOS IME composition preview span when local echo is off (6 inside `.xterm-helpers`, whose own z-index 5 is its EFFECTIVE layer, so it sits UNDER the overlay and must never be used while the overlay shows text), terminal touch-selection bar (900, below floating agent windows), subagent windows + split picker menu + Tiles count menu (1000), mobile/tablet fixed header (1200), modals on ≤768px (1300, must beat the fixed header), log viewers (2000), connection-loss overlay (2500), image popups (3000), response viewer (5000, backdrop 4999), folder grid (5090, above the response viewer it opens from, below the file preview its tiles open), file-preview overlay (5100, must outrank the response viewer that launches it), toasts/path picker (10000+), custom-model center-status banner (10001; its `[hidden]` must re-assert `display: none` or `dismiss()` leaves an invisible click-blocker), custom-model swap-confirm/context-warning modals (10010). → [architecture-invariants#z-index-layers](../../docs/architecture-invariants.md#z-index-layers)
**Codex file previews** (`codexFilePreviewsEnabled`, App Settings > Header buttons > Codex files, per-device display key, absent from `SettingsUpdateSchema`, default OFF; `_codexFilePreviewsEnabled()` in app.js is the ONE reader): a session whose CLI publishes `transcript: 'codex-rollout'` opens the files Codex links in the file preview. The served CLI catalog (`window.__codemanCliCatalog`, server.ts) carries `transcript` for that check (`_supportsCodexResponseFiles()`), never a CLI id, and `_syncCliLaunchCatalog()` keeps it across a Settings refresh. A click on an underlined label in the pane is resolved against the conversation (`last-response?context=full`, cached per session while idle until the next `lastSubmitAt`, `_codexResponseMessages()`) and opens only a single, unambiguous, previewable file, else it is forwarded to Codex as before. All of it is behind the setting (owner decision for 1.52.1: the in-pane click too, gated in `_handleDesktopTerminalClick()`), four things absent while it is off: that in-pane click (every click then goes on to Codex), the Response files header button (`toggleResponseViewer(true)`; marker `btn-response-files--hidden` for the setting, `hidden` for the capability, and `mobile.css` hides it on phones regardless, pinned by `test/mobile-header-buttons-policy.test.ts`), the Codex SIDEBAR file tabs (`codexSidebarFileRow()` in terminal-ui.js: with the setting on, `registerFilePathLinkProvider` drops its links on those rows, which are Codex chrome, and a click there is taken by `_codexTerminalLinkLabel()`; off, the row keeps its ordinary links and its click reaches Codex), and the Dock control. ⚠️ Docking MOVES `#filePreviewOverlay` out of its home and after `.terminal-wrap` (`_setFilePreviewDocked()`), only when the wrap is a direct child of `.main` without `.tiles-active`/`.webview-active` and the window is 1180px or wider; otherwise the preview floats. It moves back on close, on Escape inside it, when a split opens (`openSplitPane()` undocks first, or `closeSplitPane()` would remove the overlay with the split container) and when the setting is switched off. Tests: `test/codex-file-previews-setting.test.ts` (off-state of all three), `test/response-viewer-file-links.test.ts`, `test/terminal-link-provider-target.test.ts`, `test/terminal-touch-tap.test.ts`, `test/file-preview-window.test.ts`.
**Z-index layers** (keep new overlays consistent with this stack): local echo overlay (7; with local echo on it also draws the iOS IME composition preview, as an underlined tail after its pending text via `setComposition`), iOS IME composition preview span when local echo is off (6 inside `.xterm-helpers`, whose own z-index 5 is its EFFECTIVE layer, so it sits UNDER the overlay and must never be used while the overlay shows text), chat view (20, covering the terminal inside `.terminal-wrap`) and its Chat / Terminal switch (21, above it), terminal touch-selection bar (900, below floating agent windows), subagent windows + split picker menu + Tiles count menu (1000), mobile/tablet fixed header (1200), modals on ≤768px (1300, must beat the fixed header), log viewers (2000), connection-loss overlay (2500), image popups (3000), response viewer (5000, backdrop 4999), folder grid (5090, above the response viewer it opens from, below the file preview its tiles open), file-preview overlay (5100, must outrank the response viewer that launches it; DOCKED it is `z-index: auto`, page content beside the terminal, so it sits under every modal and the response viewer, pinned in `test/file-preview-window.test.ts`), toasts/path picker (10000+), custom-model center-status banner (10001; its `[hidden]` must re-assert `display: none` or `dismiss()` leaves an invisible click-blocker), custom-model swap-confirm/context-warning modals (10010). → [architecture-invariants#z-index-layers](../../docs/architecture-invariants.md#z-index-layers)
**Keyboard shortcuts**: Escape (close), Ctrl+? (shortcut overlay), Ctrl/Cmd/Alt+K (session palette), Ctrl+Tab (next), Alt+[/] (prev/next tab), Alt+1-9 (switch tab), Ctrl+Shift+{/} (move tab left/right), Shift+Enter or Ctrl+Enter (newline), Ctrl+C (copy selection, else interrupt) / Ctrl+Shift+C (copy, never interrupts), Ctrl+L (clear), Ctrl+Shift+R (restore size), Ctrl+Shift+V (voice input), Ctrl/Cmd +/- (font), Shift+Wheel (local scrollback when mouse passthrough is active), Shift+drag (start a selection in a stripped-DECSET pane, where xterm's own Shift branch is unreachable and a Shift+drag used to select nothing; `_installShiftDragSelection`), right-click (copy the selection, the mintty/PuTTY convention, since xterm paints into a canvas and the native menu has no Copy for it; with nothing selected the native menu is left alone). Rebindable via the registry. ⚠️ **Ctrl+W is deliberately NOT bound** (owner decision): it is delete-word in every shell and agent CLI, and as Close Session it killed sessions with no confirm; `close-session` keeps `bindings: []` and stays bindable (`test/ctrl-w-never-closes.test.ts`).
+139
View File
@@ -0,0 +1,139 @@
/**
* @fileoverview A Claude pane's report of its live conversation: the conversation id and the
* transcript path that Claude Code hands to every hook and to the statusline command.
*
* Two routes receive the report. `POST /api/hook-event` gets it from every hook Codeman
* installs. `POST /api/status-telemetry` gets it from the statusline exporter, and Claude Code
* runs the statusline command again about a second after a `/clear` (measured on 2.1.332), so
* the server learns of the new conversation before the next prompt without a hook of its own.
*
* Both reports are first-hand: they come from the CLI process in the pane, addressed by the
* pane's own `$CODEMAN_SESSION_ID`, so no cwd or timestamp guess is involved.
*
* @dependency web/schemas.ts (isValidWorkingDir), docker-hosts.ts (the Docker resume seed and the
* container's Claude folder)
*/
import { homedir } from 'node:os';
import { join } from 'node:path';
import { CONTAINER_CLAUDE_DIR, persistDockerCaseClaudeSessionId } from '../docker-hosts.js';
import { getDataDir } from '../config/instance.js';
import { isValidWorkingDir } from './schemas.js';
import type { Session } from '../session.js';
import type { ConfigPort, SessionPort } from './ports/index.js';
/**
* The host path of a transcript a pane reported. Claude in a Docker case runs with
* `HOME=/home/agent`, so it reports `/home/agent/.claude/projects/...`, a path that does not exist
* on the host. The case mounts the host's `~/.claude/projects` at that folder
* (resolveDockerClaudeArtifacts in docker-hosts.ts), so the same file is under the host's folder.
* Every other path is returned as reported.
*/
export function hostTranscriptPath(session: Pick<Session, 'docker'> | undefined, reported: string): string {
if (!session?.docker) return reported;
const containerProjects = `${CONTAINER_CLAUDE_DIR}/projects/`;
if (!reported.startsWith(containerProjects)) return reported;
const rest = reported.slice(containerProjects.length);
// A `..` segment would leave the projects folder; such a path is left as reported.
if (rest.split('/').some((part) => part === '..' || part === '')) return reported;
return join(homedir(), '.claude', 'projects', rest);
}
/** The two fields of a hook or statusline payload that name the conversation. */
export interface ClaudeConversationReport {
session_id?: unknown;
transcript_path?: unknown;
}
/**
* How long after a session's last accepted move a statusline report may not move it back to an
* earlier conversation. The exporter's POST is bounded by `curl --max-time 5` (hooks-config.ts),
* so a report sent before the newest move lands within this window.
*/
const STATUSLINE_REORDER_WINDOW_MS = 10_000;
/**
* Sessions whose conversation moved since their last `prompt_submitted` hook. The statusline can
* adopt a `/clear` successor before the next prompt's hook arrives, so that hook would see no
* change in its own report; it asks {@link takeConversationMove} instead.
*/
const conversationMoves = new WeakSet<Session>();
/** When each session last moved to another conversation, for {@link STATUSLINE_REORDER_WINDOW_MS}. */
const lastConversationMoveAt = new WeakMap<Session, number>();
/**
* Report whether the session's conversation moved since the last call for it, and forget the move.
* The hook route calls it for each `prompt_submitted`, to record a `/clear` successor's first prompt.
*/
export function takeConversationMove(session: Session | undefined): boolean {
return !!session && conversationMoves.delete(session);
}
/**
* Follow the conversation a Claude pane reports: point the session's transcript watcher at the
* reported file, adopt the reported conversation id, and persist the session when the id moved.
* Returns true when the conversation changed.
*
* `forwardOnly` refuses a report that names an earlier conversation of the session's chain while
* the session's last move is less than {@link STATUSLINE_REORDER_WINDOW_MS} old.
*/
export function noteClaudeConversationReport(
ctx: SessionPort & Pick<ConfigPort, 'startTranscriptWatcher'>,
sessionId: string,
report: ClaudeConversationReport | null | undefined,
options: { forwardOnly?: boolean } = {}
): boolean {
if (!report) return false;
// The statusline exporter can post out of order, because it backgrounds the POST when it wraps
// the user's own statusline. So a statusline report moves the session back to an earlier
// conversation, as a `/resume` makes, only when the last move is more than the window old.
// Inside the window the move waits for the next hook or the next statusline report after it.
if (options.forwardOnly && typeof report.session_id === 'string' && report.session_id) {
const reported = ctx.sessions.get(sessionId);
const chain = reported?.claudeSessionChain;
if (
reported &&
chain &&
chain.includes(report.session_id) &&
chain[chain.length - 1] !== report.session_id &&
Date.now() - (lastConversationMoveAt.get(reported) ?? 0) < STATUSLINE_REORDER_WINDOW_MS
) {
return false;
}
}
// Watch the reported transcript when its path is safe. The watcher ignores a path it already watches.
if (typeof report.transcript_path === 'string') {
const transcriptPath = hostTranscriptPath(ctx.sessions.get(sessionId), report.transcript_path);
if (isValidWorkingDir(transcriptPath)) ctx.startTranscriptWatcher(sessionId, transcriptPath);
}
// Sync Claude's current conversation id. Interactive PTY mode never emits `session_id` on
// stdout, so these reports are the only reliable way to learn that the user ran `/clear`,
// which starts a new conversation file.
if (typeof report.session_id !== 'string' || !report.session_id) return false;
const session = ctx.sessions.get(sessionId);
if (!session) return false;
const prevClaudeSessionId = session.claudeSessionId;
const prevChainLength = session.claudeSessionChain.length;
// FIRST-HAND, so the response viewer can stop guessing (see resolveActiveClaudeSessionIdFromHistory).
session.adoptClaudeSessionId(report.session_id, { firstHand: true });
if (session.claudeSessionId === prevClaudeSessionId && session.claudeSessionChain.length === prevChainLength) {
return false;
}
// Persist when the conversation actually moved: `/clear` emits no completion event, so without
// this the successor id is lost on restart and recovery falls back to the launch conversation.
ctx.persistSessionState(session);
conversationMoves.add(session);
lastConversationMoveAt.set(session, Date.now());
// Docker sessions: keep the case's resume seed following the LIVE conversation, so a container
// stop or reboot relaunch resumes the right transcript.
if (session.docker && session.claudeSessionId && session.claudeSessionId !== prevClaudeSessionId) {
void persistDockerCaseClaudeSessionId(getDataDir(), session.docker.containerName, session.claudeSessionId).catch(
() => {}
);
}
return true;
}
+371
View File
@@ -0,0 +1,371 @@
/**
* @fileoverview A Claude transcript read into the Response Viewer's messages, incrementally.
*
* `GET /api/sessions/:id/last-response` answers the Response Viewer, the Discord bridge and the
* chat view from a Claude session's transcript, an append-only JSONL file that grows past 200 MB
* on long sessions. The chat view asks again on every `transcript:update`, up to once per 750 ms
* per session while a turn runs. A read that parsed the whole file each time held the event loop
* for 375 ms on a 66 MB transcript and 1.5 s on a 219 MB one, which froze every terminal and SSE
* stream on the server.
*
* {@link ClaudeTranscriptReader} keeps the parser's state and the byte offset it reached for each
* transcript path, in a small LRU. A read parses only the bytes appended since the last one, in
* chunks with an await between them, so even the first read of a large file never holds the event
* loop for long. It starts again from byte 0 when the file shrank, was replaced by another file,
* or no longer holds the bytes it ended on. Reads of one path that overlap share one pass.
*
* The parser consumes whole lines only. A last line without its newline is parsed on a copy of
* the state for that one answer, and parsed for good once its newline arrives, so the answer
* always equals a parse of the whole file.
*
* @dependency prompt-cache-keepwarm.ts (KEEP_WARM_NUDGE), utils/lru-map.ts
*/
import fs from 'node:fs/promises';
import { KEEP_WARM_NUDGE } from '../prompt-cache-keepwarm.js';
import { LRUMap } from '../utils/lru-map.js';
export interface ClaudeResponseMessage {
kind: 'prompt' | 'response';
label: 'Prompt' | 'Response';
role: 'user' | 'assistant';
text: string;
timestamp?: string;
turn: number;
queued?: boolean;
/**
* Part of a keep-warm turn (prompt-cache-keepwarm.ts): Codeman sent the prompt, not the user,
* and the reply is its "ok". The chat view leaves such turns out, as Read My Mind does.
*/
keepAlive?: boolean;
}
/** The last assistant text of a transcript and every message, as the route answers them. */
export interface ClaudeResponseTranscript {
text: string;
timestamp: string;
messages: ClaudeResponseMessage[];
}
interface ClaudeTranscriptEntry {
type?: string;
timestamp?: string;
isMeta?: boolean;
isSidechain?: boolean;
isCompactSummary?: boolean;
message?: { content?: unknown };
// A prompt typed while Claude is working is absorbed mid-turn and recorded
// ONLY here — the CLI never re-emits it as a `user` row. Every field stays
// optional and unvalidated: `queued_command` is not a documented CLI
// contract, so a missing/renamed field must mean "skip", which is also what
// the CLI's own non-human queue entries (commandMode 'task-notification',
// no `origin` key) require. Shape observed on Claude Code 2.1.220-2.1.251.
attachment?: {
type?: string;
prompt?: string;
commandMode?: string;
timestamp?: string;
origin?: { kind?: string };
};
}
function extractClaudeText(content: unknown, separator: string): string {
if (typeof content === 'string') return content;
if (!Array.isArray(content)) return '';
return content
.filter(
(block): block is { type: string; text: string } =>
!!block &&
typeof block === 'object' &&
(block as { type?: string }).type === 'text' &&
typeof (block as { text?: string }).text === 'string'
)
.map((block) => block.text)
.join(separator);
}
function isClaudeSyntheticUserMessage(entry: ClaudeTranscriptEntry, text: string): boolean {
if (entry.isMeta || entry.isCompactSummary) return true;
return /^(?:<local-command|<command-name>|<task-notification>|<system-reminder>|<teammate-message\b|Another Claude session sent a message:|Base directory for this skill:)/i.test(
text
);
}
/**
* Claude writes an append-only event log: tool results arrive as user rows,
* thinking/tool_use rows carry no text, and a prompt typed while the agent is
* working is only ever recorded as an `attachment/queued_command` row. But one
* assistant row IS one whole model message: measured across ~/.claude/projects
* (CLI 2.1.220-2.1.251) no assistant row carries more than one content block
* and no message id carries more than one text block, so there is nothing to
* reassemble. Emit one card per row and group them with `turn` instead of
* concatenating a human turn's replies into a single card (#169), which fused
* up to 74 distinct model messages into one card. Splitting is safe for
* markdown: no adjacent pair of assistant text rows in the corpus continues a
* table, a list, or an open code fence.
*
* The state is the parse so far, fed one line at a time, so a reader can stop at the end of the
* file and go on from there when it grows.
*/
export class ClaudeResponseParser {
private lastText = '';
private lastTimestamp = '';
private messages: ClaudeResponseMessage[] = [];
// #169's replay guards, kept: they now SKIP a duplicated row instead of
// concatenating it into the previous card.
private currentUserFragments = new Set<string>();
private currentAssistantFragments = new Set<string>();
// Turn 0 is reserved for anything emitted before the first human prompt.
private turn = 0;
// Whether the current turn opened with Codeman's keep-warm nudge.
private keepAliveTurn = false;
/** A parser in the same state, for parsing a line that may not be finished yet. */
clone(): ClaudeResponseParser {
const copy = new ClaudeResponseParser();
copy.lastText = this.lastText;
copy.lastTimestamp = this.lastTimestamp;
copy.messages = this.messages.slice();
copy.currentUserFragments = new Set(this.currentUserFragments);
copy.currentAssistantFragments = new Set(this.currentAssistantFragments);
copy.turn = this.turn;
copy.keepAliveTurn = this.keepAliveTurn;
return copy;
}
/** The parse so far. The messages array is a copy, so a later line never changes an answer. */
result(): ClaudeResponseTranscript {
return { text: this.lastText, timestamp: this.lastTimestamp, messages: this.messages.slice() };
}
/** Feed text holding whole lines separated by `\n`. */
feedLines(text: string): void {
for (const line of text.split('\n')) this.feedLine(line);
}
private pushUserMessage(text: string, timestamp: string | undefined, queued: boolean): void {
// A run of consecutive human inputs (a mid-turn queued burst) is ONE turn,
// so the viewer renders it under one badge instead of one badge per line.
// The keep-warm nudge never joins an earlier user run: the turn before it
// may have ended without assistant text (an interrupt before Claude wrote
// anything, or a turn of tool calls only), and its reply belongs to the
// keep-alive turn, not to the user's prompt.
const isNudge = text === KEEP_WARM_NUDGE;
if (isNudge || this.messages.at(-1)?.role !== 'user') {
this.turn += 1;
this.keepAliveTurn = isNudge;
} else if (!isNudge) {
// A prompt the user queued during the keep-warm turn makes the turn theirs.
this.keepAliveTurn = false;
}
const message: ClaudeResponseMessage = {
kind: 'prompt',
label: 'Prompt',
role: 'user',
text,
timestamp,
turn: this.turn,
};
if (queued) message.queued = true;
if (isNudge) message.keepAlive = true;
this.messages.push(message);
this.currentUserFragments.add(text);
this.currentAssistantFragments.clear();
}
feedLine(line: string): void {
if (!line) return;
let entry: ClaudeTranscriptEntry;
try {
entry = JSON.parse(line) as ClaudeTranscriptEntry;
} catch {
return;
}
// Sidechains belong to agents/forks, not the main conversation. Meta user
// rows include repeated image dimensions and other UI-generated context.
if (entry.isSidechain) return;
// A prompt typed while Claude is working is absorbed mid-turn and lives
// ONLY in an attachment row, so it was lost outright. `origin.kind` and
// `commandMode` separate the human's queue entries from the CLI's own:
// measured over 57 real transcripts on 2026-09-01, 322 queued_command rows
// split 163 `prompt`/`human` and 159 `task-notification`, and not one of
// those 159 carries an `origin` key. The 163 human rows become 162 user
// cards here — one is a verbatim repeat inside a still-unanswered user run
// and is collapsed by the dedup guard below — out of 353 user cards total.
if (entry.type === 'attachment') {
const queued = entry.attachment;
if (!queued || queued.type !== 'queued_command') return;
if (queued.origin?.kind !== 'human' || queued.commandMode !== 'prompt') return;
const text = typeof queued.prompt === 'string' ? queued.prompt.trim() : '';
if (!text || isClaudeSyntheticUserMessage(entry, text)) return;
if (this.currentUserFragments.has(text)) return;
this.pushUserMessage(text, queued.timestamp || entry.timestamp, true);
return;
}
if (entry.type === 'user') {
const text = extractClaudeText(entry.message?.content, '\n').trim();
// A tool_result block has no text block and naturally drops out here.
if (!text || isClaudeSyntheticUserMessage(entry, text)) return;
// Claude replays the initial user row while restoring a transcript, and
// a CLI that also wrote an absorbed prompt as a user row would double it.
// Both collapse here. The same prompt sent again AFTER a reply is a
// legitimate second turn, because that reply cleared the set.
if (this.currentUserFragments.has(text)) return;
this.pushUserMessage(text, entry.timestamp, false);
return;
}
if (entry.type !== 'assistant') return;
const text = extractClaudeText(entry.message?.content, '\n\n').trim();
if (!text) return;
this.lastText = text;
this.lastTimestamp = entry.timestamp || '';
// Replayed snapshots repeat an identical text block inside one turn.
if (this.currentAssistantFragments.has(text)) return;
const response: ClaudeResponseMessage = {
kind: 'response',
label: 'Response',
role: 'assistant',
text,
timestamp: entry.timestamp,
turn: this.turn,
};
if (this.keepAliveTurn) response.keepAlive = true;
this.messages.push(response);
this.currentAssistantFragments.add(text);
this.currentUserFragments.clear();
}
}
/** Parse a whole transcript at once. */
export function parseClaudeResponseTranscript(content: string): ClaudeResponseTranscript {
const parser = new ClaudeResponseParser();
parser.feedLines(content);
return parser.result();
}
/** How many bytes before the offset a reader compares, to notice a file rewritten in place. */
const CHECK_BYTES = 64;
interface CachedTranscript {
parser: ClaudeResponseParser | null;
dev: number;
ino: number;
/** The byte just after the last newline the parser consumed. */
offset: number;
/** The bytes that ended at `offset` when the parser reached it. */
check: Buffer;
running: Promise<ClaudeResponseTranscript> | null;
queued: Promise<ClaudeResponseTranscript> | null;
}
export interface ClaudeTranscriptReaderOptions {
/** How many transcripts keep their parse. */
maxEntries?: number;
/** How many bytes one read call takes, and so how much one synchronous parse step covers. */
chunkBytes?: number;
}
/** Reads Claude transcripts, parsing each file's new bytes only. See the file overview. */
export class ClaudeTranscriptReader {
private readonly cache: LRUMap<string, CachedTranscript>;
private readonly chunkBytes: number;
constructor(options: ClaudeTranscriptReaderOptions = {}) {
this.cache = new LRUMap({ maxSize: options.maxEntries ?? 16 });
this.chunkBytes = options.chunkBytes ?? 1024 * 1024;
}
/**
* The transcript at `path`, parsed to its current end. Rejects when the file cannot be read.
*
* A read asked for while another runs waits for it and then parses what was appended meanwhile,
* so it never answers from before its own request. Every read asked for during that wait
* shares the one pass that follows.
*/
read(path: string): Promise<ClaudeResponseTranscript> {
let entry = this.cache.get(path);
if (!entry) {
entry = { parser: null, dev: 0, ino: 0, offset: 0, check: Buffer.alloc(0), running: null, queued: null };
this.cache.set(path, entry);
}
const cached = entry;
if (cached.queued) return cached.queued;
if (cached.running) {
cached.queued = cached.running
.catch(() => undefined)
.then(() => {
cached.queued = null;
return this.start(path, cached);
});
return cached.queued;
}
return this.start(path, cached);
}
private start(path: string, entry: CachedTranscript): Promise<ClaudeResponseTranscript> {
entry.running = this.update(path, entry).finally(() => {
entry.running = null;
});
return entry.running;
}
private async update(path: string, entry: CachedTranscript): Promise<ClaudeResponseTranscript> {
const handle = await fs.open(path, 'r');
try {
const stat = await handle.stat();
if (!stat.isFile()) throw new Error(`not a file: ${path}`);
let reset = !entry.parser || stat.dev !== entry.dev || stat.ino !== entry.ino || stat.size < entry.offset;
if (!reset && entry.check.length > 0) {
const now = Buffer.alloc(entry.check.length);
const { bytesRead } = await handle.read(now, 0, now.length, entry.offset - now.length);
reset = bytesRead !== now.length || !now.equals(entry.check);
}
if (reset || !entry.parser) {
entry.parser = new ClaudeResponseParser();
entry.dev = stat.dev;
entry.ino = stat.ino;
entry.offset = 0;
entry.check = Buffer.alloc(0);
}
const parser = entry.parser;
// Read to the size the stat saw; bytes written after it wait for the next read.
let position = entry.offset;
let carry = Buffer.alloc(0);
while (position < stat.size) {
const chunk = Buffer.allocUnsafe(Math.min(this.chunkBytes, stat.size - position));
const { bytesRead } = await handle.read(chunk, 0, chunk.length, position);
if (bytesRead === 0) break;
position += bytesRead;
const data =
carry.length > 0 ? Buffer.concat([carry, chunk.subarray(0, bytesRead)]) : chunk.subarray(0, bytesRead);
// A newline byte never occurs inside a multi-byte UTF-8 character, so cutting there is safe.
const newline = data.lastIndexOf(0x0a);
if (newline === -1) {
carry = data;
continue;
}
parser.feedLines(data.toString('utf8', 0, newline));
entry.offset = position - (data.length - newline - 1);
entry.check = Buffer.from(data.subarray(Math.max(0, newline + 1 - CHECK_BYTES), newline + 1));
carry = Buffer.from(data.subarray(newline + 1));
}
if (carry.length === 0) return parser.result();
const unfinished = parser.clone();
unfinished.feedLine(carry.toString('utf8'));
return unfinished.result();
} catch (err) {
// A parse left part-way is not trusted: the next read starts from byte 0.
entry.parser = null;
throw err;
} finally {
await handle.close().catch(() => {});
}
}
}
+245 -7
View File
@@ -10,6 +10,7 @@
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
import { posix } from 'node:path';
import { StaleExpirationMap } from '../../utils/index.js';
import type { AuthSessionRecord } from '../ports/auth-port.js';
import { isAllowedRequestHost, isAllowedRequestOrigin, type HostPolicy } from '../network-auth-policy.js';
@@ -22,9 +23,25 @@ import {
} from '../../config/auth-config.js';
import { getHookSecret, HOOK_SECRET_HEADER } from '../../config/hook-secret.js';
import { isMultiUserMode } from '../../config/multiuser.js';
import { findUser, setPassword, touchLastLogin, verifyPassword } from '../../user-store.js';
import {
getTrustedProxyConfig,
initTrustedProxySecret,
resolveTrustedProxyUserHeader,
takeTrustedProxyHeaders,
type PresentedProxyHeaders,
type TrustedProxyConfig,
} from '../../config/trusted-proxy.js';
import {
findUser,
isValidUsername,
normalizeUsername,
setPassword,
touchLastLogin,
verifyPassword,
} from '../../user-store.js';
import { webviewCapabilities } from '../../webview-capabilities.js';
import { capabilityFromHtmlViewPath, htmlViewCapabilities } from '../../html-view-capabilities.js';
import { capabilityFromHtmlViewPath, HTML_VIEW_PREFIX, htmlViewCapabilities } from '../../html-view-capabilities.js';
import { WEBVIEW_PROXY_PREFIX } from '../../config/webview-limits.js';
import {
capabilityFromProxyPath,
capabilityFromReferer,
@@ -56,6 +73,8 @@ interface AuthState {
userFailures: StaleExpirationMap<string, number> | null;
/** Per-(username, client IP) Basic-auth failure bucket (multi-user only). */
userIpFailures: StaleExpirationMap<string, number> | null;
/** Wrong trusted-proxy secret presentations, per client IP (multi-user + proxy secret only). */
proxySecretFailures: StaleExpirationMap<string, number> | null;
}
/** Rate-limit response for a client that exceeded the failure cap. */
@@ -118,9 +137,7 @@ function checkHookSecretBypass(
hookSecretFailures: StaleExpirationMap<string, number>
): 'bypass' | 'rejected' | 'continue' {
if ((req.url === '/api/hook-event' || req.url === '/api/status-telemetry') && req.method === 'POST') {
const ip = req.ip;
const isLoopback = ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1';
if (isLoopback) {
if (isLoopbackIp(req.ip)) {
const presented = Buffer.from(req.headers[HOOK_SECRET_HEADER.toLowerCase()]?.toString() ?? '');
const expected = Buffer.from(getHookSecret());
if (presented.length === expected.length && timingSafeEqual(presented, expected)) {
@@ -141,6 +158,111 @@ function checkHookSecretBypass(
return 'continue';
}
/** Whether a socket address is loopback. The one test both secret-gated paths (hook, proxy) use. */
function isLoopbackIp(ip: string): boolean {
return ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1';
}
/**
* The trusted-proxy headers each request presented, keyed by request. Filled by the first
* auth hook (`registerTrustedProxyHeaderStrip`), which also deletes the headers from the
* request; read by `checkTrustedProxyIdentity`. A WeakMap, so nothing outlives the request.
*/
const presentedProxyHeaders = new WeakMap<FastifyRequest, PresentedProxyHeaders>();
/** Minimum interval between `touchLastLogin` writes for proxy sign-ins, per user. */
const PROXY_LAST_LOGIN_INTERVAL_MS = 15 * 60 * 1000;
/**
* Take the trusted-proxy headers off EVERY request before any other auth logic, route or
* exemption (web-tab relay, HTML view, QR) can see them, in every auth mode. Registered
* first in `registerAuthMiddleware`, i.e. right after the Host guard.
*/
function registerTrustedProxyHeaderStrip(app: FastifyInstance): void {
const userHeader = resolveTrustedProxyUserHeader();
app.addHook('onRequest', (req, _reply, done) => {
presentedProxyHeaders.set(req, takeTrustedProxyHeaders(req.headers, userHeader, req.raw));
done();
});
}
/**
* Trusted reverse-proxy identity (see src/config/trusted-proxy.ts). Returns:
* - 'continue' : no proxy secret header; fall through to cookie / Basic auth
* - 'authenticated' : req.authUser is set from the proxy's username header
* - 'rejected' : a reply was already sent
*
* Fails CLOSED once the secret header is present at all, even empty: a wrong secret or a
* non-loopback source (401), or a missing username, one the user store's rule rejects,
* or one with no enabled account (403, no challenge) is refused outright and never falls
* through to the cookie or Basic paths, so a misconfigured proxy cannot silently degrade
* into some other identity. A username header WITHOUT the secret header is ignored
* (normal auth applies).
*
* The username is matched exactly, by the store's own rule (`normalizeUsername`, then
* `isValidUsername`): no cutting at `@`, no character replacement. A duplicated header
* arrives joined ("alice, bob") and fails that rule.
*
* The secret is compared BEFORE the failure bucket is consulted, like the hook secret:
* a correct secret always passes, so local junk requests (which share 127.0.0.1 with
* the proxy) cannot lock sign-in out. Only failures are counted and throttled, in their
* own per-IP bucket, so a broken proxy cannot lock out the Basic or hook paths either.
*/
async function checkTrustedProxyIdentity(
req: FastifyRequest,
reply: FastifyReply,
config: TrustedProxyConfig,
proxySecretFailures: StaleExpirationMap<string, number>,
lastLoginTouched: Map<string, number>
): Promise<'continue' | 'authenticated' | 'rejected'> {
const presented = presentedProxyHeaders.get(req);
if (!presented?.secretPresent) return 'continue';
const clientIp = req.ip;
const given = Buffer.from(presented.secret);
const expected = Buffer.from(config.secret);
const secretOk = isLoopbackIp(clientIp) && given.length === expected.length && timingSafeEqual(given, expected);
if (!secretOk) {
const failures = proxySecretFailures.get(clientIp) ?? 0;
if (failures >= AUTH_FAILURE_MAX) {
sendAuthRateLimit(reply, proxySecretFailures, clientIp);
return 'rejected';
}
proxySecretFailures.set(clientIp, failures + 1);
reply.code(401).send('Unauthorized: trusted proxy secret rejected');
return 'rejected';
}
// The proxy vouched for the request, so none of the refusals below is a failed guess:
// 403, no challenge, no bucket.
const username = normalizeUsername(presented.user);
if (!username) {
reply.code(403).send('Forbidden: trusted proxy sent no username');
return 'rejected';
}
let user: Awaited<ReturnType<typeof findUser>>;
try {
user = isValidUsername(username) ? await findUser(username) : undefined;
} catch {
reply.code(503).send('Service Unavailable: user store unreadable');
return 'rejected';
}
if (!user || user.disabled) {
reply.code(403).send('Forbidden: no enabled Codeman account for this user');
return 'rejected';
}
// No mustChangePassword lockbox: the person did not sign in with a Codeman password,
// so a pending one-time password has nothing to do with this request.
req.authUser = { username: user.username, role: user.role, viaTrustedProxy: true };
// Keep "last login" meaningful for proxy sign-ins, without a store write per request.
const now = Date.now();
if (now - (lastLoginTouched.get(user.username) ?? 0) >= PROXY_LAST_LOGIN_INTERVAL_MS) {
lastLoginTouched.set(user.username, now);
void touchLastLogin(user.username).catch(() => {});
}
return 'authenticated';
}
/**
* Requests that a `mustChangePassword` user may still reach: the identity probe,
* the password-change endpoint, and any non-API path (static assets / index.html,
@@ -275,6 +397,80 @@ export function isLostWebviewRootFrame(req: FastifyRequest): boolean {
return !carriesAuthCredentials(req.headers, AUTH_COOKIE_NAME);
}
/**
* Which capability prefix a request falls under, judged the way a reverse proxy's path
* matcher does: query dropped, percent-decoded once, dot segments and doubled slashes
* resolved, case-insensitive. A proxy forwards everything it matches this way WITHOUT its
* sign-in, so the refusal below must recognise every such spelling, not only the literal
* one Codeman's own routes use. Any token shape counts: a malformed token is still a
* request the proxy let through.
*
* `rawUrl` has been through `stripBasePath()`, which removes the mount prefix only in its
* literal spelling, so under `basePath` a re-spelled prefix (`/CODEMAN/webview/x`,
* `/%63odeman/...`, `//codeman/...`, `/x/../codeman/...`) is still in front. So the
* normalised path is judged as it is first, and only when that is no capability path and
* it starts with the lower-cased base path, once more with the base path removed once.
* Either match counts. As it is comes first because the literal prefix may already be
* gone: under a mount named `/webview`, `/webview/webview/x` arrives as `/webview/x`, and
* removing the base again would lose the capability prefix itself.
*/
export function capabilityPrefixOf(rawUrl: string, basePath = ''): 'webview' | 'html-view' | null {
let path = rawUrl.split('?')[0];
try {
path = decodeURIComponent(path);
} catch {
// Malformed escape: judge the raw path.
}
// Fold U+0130 (capital I with dot above) to a plain "i" first: Go's lowercasing, which
// Caddy's matcher uses, does that, while toLowerCase() yields "i" + U+0307 and would miss
// the prefix. Written as an escape so Unicode normalisation can't split it.
path = posix
.normalize(path)
.replace(/\u0130/g, 'i')
.toLowerCase();
const asIs = capabilityPrefixOfNormalised(path);
if (asIs) return asIs;
const base = basePath.toLowerCase();
return base && path.startsWith(`${base}/`) ? capabilityPrefixOfNormalised(path.slice(base.length)) : null;
}
function capabilityPrefixOfNormalised(path: string): 'webview' | 'html-view' | null {
if (path.startsWith(`${WEBVIEW_PROXY_PREFIX}/`)) return 'webview';
if (path.startsWith(`${HTML_VIEW_PREFIX}/`)) return 'html-view';
return null;
}
/**
* A request under a capability prefix (`/webview/...`, `/html-view/...`, judged by
* `capabilityPrefixOf`) that the capability exemptions above did NOT let through: no live
* capability, whatever the token looks like (or a method the exemption never covers).
* Refused here with what the route answers an authenticated caller for an unknown
* capability (403 for a web tab, 404 for an HTML view), WITHOUT a Basic challenge and
* WITHOUT counting a failure.
*
* Only used when trusted-proxy sign-in is configured. There, these paths reach Codeman
* WITHOUT the proxy's own sign-in (their sandboxed frames carry no credentials, so the
* proxy has to let them through; see the trusted-proxy docs). Falling through to the
* credential checks would expose the password check and a `WWW-Authenticate` prompt to
* anyone who can reach the proxy, and let anonymous requests fill the per-IP failure
* bucket, which behind the proxy is always 127.0.0.1, locking out Basic sign-in from
* loopback. Without a proxy, these paths keep the normal 401 challenge.
*
* @returns true when the reply was sent.
*/
function serveRefusedCapabilityPath(req: FastifyRequest, reply: FastifyReply, basePath = ''): boolean {
const kind = capabilityPrefixOf(req.url ?? '', basePath);
if (kind === 'webview') {
reply.code(403).type('text/plain').send('Forbidden: unknown or expired webview capability');
return true;
}
if (kind === 'html-view') {
reply.code(404).header('Content-Type', 'text/plain; charset=utf-8').send('Not found');
return true;
}
return false;
}
/** Send the static recovery page (lostWebviewFramePage) with its own CSP, uncached. */
export function sendLostWebviewFramePage(reply: FastifyReply): FastifyReply {
reply.header('content-security-policy', LOST_FRAME_PAGE_CSP);
@@ -329,12 +525,18 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean, bas
hookSecretFailures: null,
userFailures: null,
userIpFailures: null,
proxySecretFailures: null,
};
// Always declare req.authUser so downstream reads are safe (single-user leaves it
// undefined; the ownership helpers then default to a synthetic admin).
if (!app.hasRequestDecorator('authUser')) app.decorateRequest('authUser', undefined);
// First, in every auth mode: take the trusted-proxy headers off the request, so no
// later hook, exemption or route (e.g. the web-tab relay) can forward the secret.
registerTrustedProxyHeaderStrip(app);
initTrustedProxySecret();
const multiUser = isMultiUserMode();
const authPassword = process.env.CODEMAN_PASSWORD;
@@ -395,6 +597,15 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean, bas
ttlMs: AUTH_FAILURE_WINDOW_MS,
refreshOnGet: false,
});
// Trusted reverse-proxy identity (opt-in). Its own failure bucket, like the hook
// secret's, so wrong proxy secrets never count against the Basic login path.
const trustedProxy = getTrustedProxyConfig(true);
if (trustedProxy) {
state.proxySecretFailures = new StaleExpirationMap<string, number>({
ttlMs: AUTH_FAILURE_WINDOW_MS,
refreshOnGet: false,
});
}
registerMultiUserAuthHook(
app,
https,
@@ -403,7 +614,10 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean, bas
hookSecretFailures,
state.userFailures,
state.userIpFailures,
basePath
basePath,
trustedProxy && state.proxySecretFailures
? { config: trustedProxy, failures: state.proxySecretFailures, lastLoginTouched: new Map<string, number>() }
: null
);
return state;
}
@@ -534,7 +748,12 @@ function registerMultiUserAuthHook(
hookSecretFailures: StaleExpirationMap<string, number>,
userFailures: StaleExpirationMap<string, number>,
userIpFailures: StaleExpirationMap<string, number>,
basePath = ''
basePath = '',
trustedProxy: {
config: TrustedProxyConfig;
failures: StaleExpirationMap<string, number>;
lastLoginTouched: Map<string, number>;
} | null = null
): void {
const setSessionCookie = (reply: FastifyReply, token: string) =>
reply.setCookie(AUTH_COOKIE_NAME, token, {
@@ -658,6 +877,25 @@ function registerMultiUserAuthHook(
if (hasValidHtmlViewCapability(req)) return;
// A web-tab frame that lost its prefix: hand it back to its tab, no credentials involved.
if (serveLostWebviewFrame(req, reply)) return;
// Behind an authenticating proxy, capability paths reach Codeman without the proxy's
// sign-in: refuse a non-exempt one with the route's own answer, no challenge, no count.
if (trustedProxy && serveRefusedCapabilityPath(req, reply, basePath)) return;
// 0. Trusted reverse-proxy identity, checked BEFORE the cookie: when the proxy
// vouches for a person on this request, that is authoritative, and a stale cookie
// from an earlier Basic login in the same browser must not override it. No cookie
// is minted: the proxy presents the identity on every new request and WebSocket
// upgrade. A stream that is already open is not re-checked.
if (trustedProxy) {
const proxied = await checkTrustedProxyIdentity(
req,
reply,
trustedProxy.config,
trustedProxy.failures,
trustedProxy.lastLoginTouched
);
if (proxied !== 'continue') return;
}
const clientIp = req.ip;
+214 -13
View File
@@ -289,6 +289,10 @@ const _SSE_HANDLER_MAP = [
// (and its turn ends, from _onSessionIdle: one handler per event in this map)
[SSE_EVENTS.TRANSCRIPT_TOOL_END, '_onEditHistoryTranscriptEvent'],
// Chat view (chat-view.js): re-read the conversation as the transcript grows. Turn starts and
// ends reach it from _onSessionWorking / _onSessionIdle.
[SSE_EVENTS.TRANSCRIPT_UPDATE, '_onChatViewTranscriptUpdate'],
// Tunnel
[SSE_EVENTS.TUNNEL_STARTED, '_onTunnelStarted'],
[SSE_EVENTS.TUNNEL_STOPPED, '_onTunnelStopped'],
@@ -535,6 +539,16 @@ const DEFAULT_SHORTCUTS = [
bindings: [{ modifiers: ['alt'], key: 'b', code: 'KeyB' }],
action: 'toggleSessionSidebar',
},
{
id: 'toggle-chat-view',
group: 'Session',
label: 'Toggle Chat / Terminal View',
// Alt+Shift+C: no browser binds it, and the xterm key handler swallows it only while the
// active session can show the chat view (shouldToggleChatViewFromShortcut), so elsewhere
// the chord still reaches the terminal.
bindings: [{ modifiers: ['alt', 'shift'], key: 'C', code: 'KeyC' }],
action: 'toggleChatView',
},
// Tile grid (tile-grid.js). Dispatched by tileShortcutFor()/runTileShortcut()
// and deliberately absent from SHORTCUT_ACTIONS: each applies only in some
// states (the focus chords only while the grid is open), and outside them the
@@ -1163,6 +1177,8 @@ class CodemanApp {
this.tabAlerts.set(sessionId, 'idle');
}
this.renderSessionTabs();
// An open chat view shows a dialog the pane is waiting on (chat-view.js).
this.onChatViewHooksChanged?.(sessionId);
}
// ═══════════════════════════════════════════════════════════════
@@ -1427,6 +1443,7 @@ class CodemanApp {
// Escape - close panels and modals (different logic: no preventDefault, no return)
if (e.key === 'Escape') {
if (this._maybeCloseDockedFilePreviewOnEscape?.(e)) return;
// An open group menu (or a grouped-rail drag) owns this Escape: close
// just that, not every panel behind it.
if (this._tabGroupMenu && this._tabGroupMenuKeydown) {
@@ -2439,6 +2456,8 @@ class CodemanApp {
if (session.id === this.activeSessionId) this._reconcileKeyboardHold?.();
// The agent moved into or out of a git worktree while the Files panel is open (#765).
if (session.id === this.activeSessionId) this._followFileBrowserWorktree?.(session);
// A started or switched agent can change whether the chat view applies (chat-view.js).
if (session.id === this.activeSessionId) this._chatViewSync?.();
// Update parentSessionName for any subagents belonging to this session
// (fixes stale name display after session rename)
this.updateSubagentParentNames(session.id);
@@ -2466,6 +2485,7 @@ class CodemanApp {
// Dashboard: a detached session ended → clear its detached state/timers.
if (this.detachedSessions.has(data.id)) this._redock(data.id);
this._cleanupSessionData(data.id);
this._chatViewForget?.(data.id);
// ⚠️ Skip the whole active-session handoff while THIS tab is closing that
// session: closeSession() owns the follow-up selection and moves you to the
// next tab, so acting here would race it and flash the welcome screen (or
@@ -2776,12 +2796,19 @@ class CodemanApp {
* newline is the agent's line break, wrong for a file (the File Viewer passes
* false), where a README hard-wrapped at 80 columns would break at every wrap.
*/
_renderMarkdown(text, { breaks = true } = {}) {
_renderMarkdown(text, { breaks = true, localFileLinks = false } = {}) {
const src = text || '';
if (typeof marked !== 'undefined' && marked.parse) {
try {
const prepared = this._preprocessAsciiArt(src);
let html = this._sanitizeHtml(marked.parse(prepared, { breaks, gfm: true }));
const options = { breaks, gfm: true };
if (localFileLinks) {
options.walkTokens = (token) => {
// Convert local URI destinations to inert path references before sanitizing.
if (token.type === 'link' && /^file:\/\/\/(?!\/)/i.test(token.href)) token.href = token.href.slice(7);
};
}
let html = this._sanitizeHtml(marked.parse(prepared, options));
// Wrap tables in a horizontal-scroll container so they overflow gracefully
// on mobile without collapsing into block-level cells.
html = html.replace(/<table>/g, '<div class="rv-table-wrap"><table>')
@@ -3228,19 +3255,166 @@ class CodemanApp {
: 'Claude';
}
async toggleResponseViewer() {
closeResponseViewer() {
this._responseViewerRequest = null;
const viewer = document.getElementById('responseViewer');
if (!viewer || !viewer.classList.contains('visible')) return false;
const backdrop = document.getElementById('responseViewerBackdrop');
viewer.classList.remove('visible');
if (backdrop) backdrop.classList.remove('visible');
const terminal = this._responseViewerReturnTerminal;
this._responseViewerReturnTerminal = null;
if (terminal && terminal.element?.isConnected !== false && this._shouldFocusTerminalForTabSwitch()) {
try {
terminal.focus();
} catch {
/* terminal may be detached mid-teardown */
}
}
return true;
}
_supportsCodexResponseFiles(sessionId) {
const mode = this.sessions?.get(sessionId)?.mode;
return window.__codemanCliCatalog?.find((entry) => entry.id === mode)?.transcript === 'codex-rollout';
}
/**
* Per-device opt-in (`codexFilePreviewsEnabled`, App Settings > Header buttons > Codex files),
* default OFF. It gates the three Codex file-preview extras together: the Response files header
* button, taking a click on a file tab in Codex's own sidebar (and the link suppression on those
* rows), and the Dock control on file previews. With it off none of them exists and sidebar clicks
* reach Codex as before.
*/
_codexFilePreviewsEnabled() {
const settings = this.loadAppSettingsFromStorage?.() || {};
const defaults = this.getDefaultSettings?.() || {};
return (settings.codexFilePreviewsEnabled ?? defaults.codexFilePreviewsEnabled ?? false) === true;
}
/**
* The Response files button shows only with the setting on (its --hidden marker; phones keep it
* hidden via mobile.css regardless) AND in a session whose CLI publishes a Codex rollout
* transcript (the `hidden` attribute).
*/
_syncResponseFilesButton() {
const button = document.getElementById('responseFilesBtn');
if (!button) return;
button.classList.toggle('btn-response-files--hidden', !this._codexFilePreviewsEnabled());
button.hidden = !this._supportsCodexResponseFiles(this.activeSessionId);
}
_findCodexResponseFile(messages, label, sessionId, sidebar = false) {
const [prefix, suffix, ...extra] = sidebar ? label.split('…') : [];
const abbreviated = Boolean(prefix && suffix && extra.length === 0);
const containsFilename = (text) => abbreviated ? text.includes(prefix) && text.includes(suffix) : text.includes(label);
let match = null;
for (const message of messages) {
const { text } = message;
if (message.role !== 'assistant' || typeof text !== 'string') continue;
if (sidebar && !containsFilename(text)) {
// Markdown destinations can URI-encode the filename. Leave Markdown
// escapes and HTML entities to the renderer when present.
const decoded = text.replace(/(?:%[\da-f]{2})+/gi, (escapes) => {
try {
return decodeURIComponent(escapes);
} catch {
return escapes;
}
});
if (!containsFilename(decoded) && !/\\[!-~]|&(?:#\w+|[a-z]+);/i.test(decoded)) continue;
} else if (!sidebar && !text.includes(label)) {
continue;
}
const rendered = document.createElement('template');
rendered.innerHTML = this._renderMarkdown(text, { localFileLinks: true });
const links = Array.from(rendered.content.querySelectorAll('a')).filter(
(link) => sidebar || link.textContent.trim() === label
);
if (!links.length) continue;
this._linkifyFilePaths(rendered.content);
for (const link of links) {
const path = this._resolveLinkedFilePath(link.dataset.path, sessionId);
if (sidebar) {
const basename = path.split('/').pop();
// Codex preserves both ends of a filename when it shortens the tab.
const matchesEnds =
abbreviated && basename.length > prefix.length + suffix.length &&
basename.startsWith(prefix) && basename.endsWith(suffix);
if (basename !== label && !matchesEnds) continue;
}
// Ambiguity includes web URLs and unsupported files with the same label.
if (!link.dataset.linkified || link.dataset.folder || !/^\/(?!\/)/.test(path) || !previewsInFileViewer(path)) {
return null;
}
if (match && match !== path) return null;
match = path;
}
}
return match;
}
_openResponseFile(path, sessionId) {
const discard = 'Discard unsaved changes?';
if (this.filePreviewEdit?.dirty && !confirm(window.codemanT?.(discard) || discard)) return;
return this.openFilePreview(path, sessionId, null, { dock: true });
}
_renderResponseFiles(body, responses, sessionId) {
const list = document.createElement('ul');
list.className = 'response-files-list';
const seen = new Set();
for (const response of responses) {
const rendered = document.createElement('template');
rendered.innerHTML = this._renderMarkdown(response, { localFileLinks: true });
this._linkifyFilePaths(rendered.content);
for (const link of rendered.content.querySelectorAll('a.rv-path')) {
if (link.dataset.folder) continue;
const path = this._resolveLinkedFilePath(link.dataset.path, sessionId);
if (!/^\/(?!\/)/.test(path) || !previewsInFileViewer(path) || seen.has(path)) continue;
seen.add(path);
const item = document.createElement('li');
// A button, not <a href="#">: under <base href> a middle-click on "#" opens the app root.
const action = document.createElement('button');
action.type = 'button';
action.className = 'response-files-item';
action.textContent = link.textContent.trim() || path.split('/').pop();
action.title = path;
action.addEventListener('click', (event) => {
event.preventDefault();
this.closeResponseViewer();
this._openResponseFile(path, sessionId);
});
item.appendChild(action);
list.appendChild(item);
}
}
if (seen.size) body.replaceChildren(list);
else {
const empty = 'No previewable files in the latest response.';
body.textContent = window.codemanT?.(empty) || empty;
}
}
async toggleResponseViewer(filesOnly = false) {
const viewer = document.getElementById('responseViewer');
const backdrop = document.getElementById('responseViewerBackdrop');
if (!viewer) return;
const isOpen = viewer.classList.contains('visible');
if (isOpen) {
viewer.classList.remove('visible');
backdrop.classList.remove('visible');
if (isOpen && (viewer.dataset.filesOnly === 'true') === filesOnly) {
this.closeResponseViewer();
return;
}
if (!this.activeSessionId) return;
const responseSessionId = this.activeSessionId;
const session = this.sessions?.get?.(responseSessionId);
if (filesOnly && !(this._codexFilePreviewsEnabled() && this._supportsCodexResponseFiles(responseSessionId))) return;
const returnTerminal = isOpen ? this._responseViewerReturnTerminal : this._focusedPane?.().terminal;
const request = Symbol('response-viewer');
this._responseViewerRequest = request;
try {
// Source 1: Transcript JSONL (best quality — clean structured text from Claude).
// `context=turn` asks for the last ANSWERED turn as messages: a Claude
@@ -3249,8 +3423,10 @@ class CodemanApp {
// rows before it. Readers that know no `turn` context (Codex, the pane
// parser, an older server) answer with `text` only, and that path is
// unchanged below.
const res = await fetch(`/api/sessions/${this.activeSessionId}/last-response?context=turn`);
const res = await fetch(`/api/sessions/${responseSessionId}/last-response?context=turn`);
if (filesOnly && !res.ok) throw new Error('Unable to load response files');
const data = (await res.json())?.data ?? {};
if (this._responseViewerRequest !== request || this.activeSessionId !== responseSessionId) return;
let lastResponse = data.text || '';
const turnMessages = (Array.isArray(data.messages) ? data.messages : []).filter(
(msg) => msg && msg.role === 'assistant' && typeof msg.text === 'string' && msg.text.trim()
@@ -3261,13 +3437,13 @@ class CodemanApp {
// shell sessions have no transcript source at all; for TUI modes
// (codex/opencode/gemini/antigravity) it yields repaint garbage, so a clear
// placeholder beats a messy screen dump there.
const sessionMode = this.sessions.get(this.activeSessionId)?.mode || 'claude';
const sessionMode = session?.mode || 'claude';
if (!lastResponse && (sessionMode === 'claude' || sessionMode === 'shell')) {
// The no-param form is capped only by `terminalBufferMaxBytes` (32MB by
// default), so it is the largest body the frontend asks for anywhere —
// it gets the full-history budget, not the tail one.
const termCapture = await this._fetchTerminalCapture(
`/api/sessions/${this.activeSessionId}/terminal`,
`/api/sessions/${responseSessionId}/terminal`,
{ full: true }
);
const termData = termCapture.json?.data ?? {};
@@ -3276,10 +3452,14 @@ class CodemanApp {
}
}
if (this._responseViewerRequest !== request || this.activeSessionId !== responseSessionId) return;
this._responseViewerMarkdown = this._responseViewerMarkdownFrom(turnMessages) || lastResponse;
const body = document.getElementById('responseViewerBody');
if (turnMessages.length > 0) {
if (filesOnly) {
const responses = turnMessages.length ? turnMessages.map((message) => message.text) : [lastResponse];
this._renderResponseFiles(body, responses, responseSessionId);
} else if (turnMessages.length > 0) {
// The whole last turn, rendered exactly as the full view renders that
// turn: one badge, then badge-less continuation segments. The same
// numeric-`turn` gate as loadFullContext, never same-role adjacency.
@@ -3308,9 +3488,15 @@ class CodemanApp {
// Reset state for fresh open
const title = document.getElementById('responseViewerTitle');
const moreBtn = document.getElementById('responseViewerMore');
if (title) title.textContent = 'Last Response';
if (moreBtn) { moreBtn.style.display = ''; moreBtn.textContent = 'More'; }
viewer.dataset.filesOnly = String(filesOnly);
const titleText = filesOnly ? 'Response files' : 'Last Response';
if (title) title.textContent = window.codemanT?.(titleText) || titleText;
if (moreBtn) {
moreBtn.style.display = '';
moreBtn.textContent = window.codemanT?.('More') || 'More';
}
this._responseViewerReturnTerminal = returnTerminal;
viewer.classList.add('visible');
backdrop.classList.add('visible');
// A multi-row turn opens at its NEWEST text, matching loadFullContext's
@@ -3318,9 +3504,13 @@ class CodemanApp {
// brief view was a single card holding the last row; with the whole turn
// rendered, the top is the turn's first narration line and the answer the
// eye button exists to show can be several screens down.
body.scrollTop = turnMessages.length > 1 ? body.scrollHeight : 0;
body.scrollTop = !filesOnly && turnMessages.length > 1 ? body.scrollHeight : 0;
} catch (err) {
console.error('Failed to load response:', err);
if (filesOnly && this._responseViewerRequest === request && this.activeSessionId === responseSessionId) {
const message = 'Unable to load response files';
this.showToast(window.codemanT?.(message) || message, 'error');
}
}
}
@@ -3718,6 +3908,7 @@ class CodemanApp {
// An open Edit history panel re-reads at the end of its session's turn (edit-history-ui.js),
// not after Codeman's own keep-alive turn, which edits nothing.
if (!data.keepAlive) this.onEditHistorySessionIdle?.(data.id);
this.onChatViewTurnEvent?.(data.id, true, data.keepAlive);
// Start stuck detection timer (only if no respawn running). Not at the end of Codeman's
// own keep-alive turn (`keepAlive`): the session has been waiting since the last real
// turn, whose timer is still running or has already fired.
@@ -3743,6 +3934,7 @@ class CodemanApp {
this.sendPendingCtrlL(data.id);
if (data.id === this.activeSessionId) this._updateLocalEchoState();
}
this.onChatViewTurnEvent?.(data.id, false, data.keepAlive);
// Clear stuck detection timer, unless this is Codeman's own keep-alive turn, which is
// no sign of life from the agent's side.
const timer = data.keepAlive ? null : this.idleTimers.get(data.id);
@@ -5251,6 +5443,8 @@ class CodemanApp {
});
}
});
// The chat view's per-device choices of sessions that are gone (chat-view.js).
this._chatViewPruneModes?.(new Set(data.sessions.map((s) => s.id)));
// Server is source of truth for open sessions — don't resurrect stale tabs
// from localStorage (would show phantom "ended" tabs when a session was closed
@@ -5410,6 +5604,9 @@ class CodemanApp {
// The fresh session record may no longer qualify for a keyboard row hold.
this._reconcileKeyboardHold?.();
void this._onSessionNeedsRefresh({ id: restoreId });
// The transcript events sent during the outage are lost, so the chat view re-reads the
// conversation now (a no-op while Chat is not showing).
this._chatViewReload?.({ immediate: true });
// The split pane's second terminal reconnects on its own backoff (up to
// 10 s between tries); the server is back now, so skip the wait. A no-op
// while its socket is open, stopped for good, or destroyed.
@@ -6592,6 +6789,7 @@ class CodemanApp {
// ═══════════════════════════════════════════════════════════════
renderSessionTabs({ immediate = false } = {}) {
this._syncResponseFilesButton();
// Don't re-render while user is typing in the inline rename input
if (this._inlineRenameActive) return;
if (immediate) {
@@ -10376,6 +10574,8 @@ class CodemanApp {
this.refreshHostWakeBanner?.(sessionId);
// An open Edit history panel follows the active session (edit-history-ui.js; no poll).
this.onEditHistoryActiveSession?.(sessionId);
// The chat view follows the active session too, showing it or the terminal (chat-view.js).
this.onChatViewActiveSession?.(sessionId);
// Restore flushed offset AND text IMMEDIATELY so backspace/typing work during
// the async buffer load. Without this, the offset is 0 during the
@@ -11614,6 +11814,7 @@ class CodemanApp {
moveActiveTabLeft: () => this.moveActiveTabLeft(),
moveActiveTabRight: () => this.moveActiveTabRight(),
toggleSessionSidebar: () => this.toggleSessionSidebar(),
toggleChatView: () => this.toggleChatView?.(),
};
}
+571
View File
@@ -0,0 +1,571 @@
/**
* @fileoverview Chat view: a session's conversation, rendered like the Response Viewer, as the
* session's main view (docs/chat-view-plan.md, phase 1).
*
* The agent keeps running in its tmux pane. The chat view is a second way to look at that pane:
* it covers the terminal (which stays mounted, attached and sized, so the PTY is never resized
* by a view switch) and draws the conversation from the session's transcript.
*
* - Which sessions can have it: those whose run mode Codeman reads from a Claude-format
* transcript (`window.__codemanChatViewModes`, published from the `transcript` capability,
* never an id list here), local or Docker, not remote and not adopted, and not on a phone.
* - Which view a session shows: the per-device choice remembered for that session
* (`codeman:chatViewModes` in localStorage), else the per-device setting `chatViewDefault`
* (default off, so a session opens in Terminal until the user picks Chat).
* - The Chat / Terminal switch: shown on an eligible session only when the per-device setting
* `showChatViewSwitch` is true (default off: an absent key means hidden, so nobody sees the
* switch without choosing it). Hidden, it changes nothing else: the session keeps its view,
* and Alt+Shift+C still switches.
* - Live updates: the conversation is re-read (debounced) on the session's `transcript:update`,
* `session:working` and `session:idle`. Nothing is read while the chat view is hidden.
* - Typing: the chat view has no message box yet, so the user types in the terminal. A focus
* that lands on the hidden terminal moves to the conversation, so keys never reach the pane
* unseen.
* - A dialog in the pane (permission, question, plan approval) shows as a notice with a button
* that switches to the terminal, where it is answered.
*
* Messages are model and user text: they go through the Response Viewer's sanitising markdown
* pipeline (`_buildResponseViewerMessage`), and everything else is set with `textContent`.
*
* @mixin Extends CodemanApp.prototype via Object.assign
* @dependency app.js (this.activeSessionId, this.sessions, this.pendingHooks, _buildResponseViewerMessage,
* _bindResponseViewerInteractions, _getResponseViewerAgentLabel)
* @dependency constants.js (CodemanChatView)
* @dependency api-client.js at runtime (this._apiJson)
* @loadorder 12.595 of 16, after local-model-ui.js, before entrance-animations.js
*/
const CHAT_VIEW_MODES_KEY = 'codeman:chatViewModes';
/** Wait after an update before re-reading, so a burst of events costs one read. */
const CHAT_VIEW_RELOAD_DEBOUNCE_MS = 250;
Object.assign(CodemanApp.prototype, {
// ─── Eligibility and choice ──────────────────────────────────
/** Whether `sessionId` can show the chat view on this device. */
chatViewEligible(sessionId) {
const session = sessionId ? this.sessions?.get(sessionId) : null;
if (!session) return false;
const modes = Array.isArray(window.__codemanChatViewModes) ? window.__codemanChatViewModes : [];
if (!session.mode || !modes.includes(session.mode)) return false;
// A remote session's transcript lives on its host, and an adopted one has none Codeman can name.
if (session.remote || session.adopt) return false;
// Phones keep the terminal and its keyboard bars (phase 3 lays the chat view out for them),
// whatever their orientation or fold: a phone turned to landscape is still a phone.
if (typeof MobileDetection !== 'undefined') {
const phone = MobileDetection.isHandheldDevice?.() ?? MobileDetection.getDeviceType?.() === 'mobile';
if (phone) return false;
}
return true;
},
/** The per-device choice for each session, `{ [sessionId]: 'chat' | 'terminal' }`. */
_chatViewStoredModes() {
try {
const parsed = JSON.parse(localStorage.getItem(CHAT_VIEW_MODES_KEY) || '{}');
return parsed && typeof parsed === 'object' ? parsed : {};
} catch {
return {};
}
},
_chatViewStoreModes(modes) {
try {
localStorage.setItem(CHAT_VIEW_MODES_KEY, JSON.stringify(modes));
} catch {
// Storage blocked: the choice lasts for this page load only.
}
},
/** 'chat' or 'terminal' for `sessionId`. */
chatViewModeFor(sessionId) {
const stored = this._chatViewStoredModes()[sessionId];
if (stored === 'chat' || stored === 'terminal') return stored;
if (this._chatViewMemoryModes?.has(sessionId)) return this._chatViewMemoryModes.get(sessionId);
return this.loadAppSettingsFromStorage?.().chatViewDefault === true ? 'chat' : 'terminal';
},
setChatViewMode(sessionId, mode) {
if (!sessionId || (mode !== 'chat' && mode !== 'terminal')) return;
if (!this._chatViewMemoryModes) this._chatViewMemoryModes = new Map();
this._chatViewMemoryModes.set(sessionId, mode);
const modes = this._chatViewStoredModes();
modes[sessionId] = mode;
this._chatViewStoreModes(modes);
if (sessionId === this.activeSessionId) this._chatViewSync({ focus: true });
},
/**
* Called after each init (app.js) with the server's session list: drop the view choice of every
* session not in it. A session deleted while no page was open sends this page no event.
*/
_chatViewPruneModes(liveIds) {
for (const id of [...(this._chatViewMemoryModes?.keys() ?? [])]) {
if (!liveIds.has(id)) this._chatViewMemoryModes.delete(id);
}
const modes = this._chatViewStoredModes();
const kept = Object.fromEntries(Object.entries(modes).filter(([id]) => liveIds.has(id)));
if (Object.keys(kept).length !== Object.keys(modes).length) this._chatViewStoreModes(kept);
},
/** Whether this device shows the Chat / Terminal switch. Off by default: an absent setting means it does not. */
_chatViewSwitchShown() {
return this.loadAppSettingsFromStorage?.().showChatViewSwitch === true;
},
/** The Alt+Shift+C action: flip the active session between Chat and Terminal. */
toggleChatView() {
const id = this.activeSessionId;
if (!this.chatViewEligible(id) || this._tilesOwnTerminal?.()) return;
this.setChatViewMode(id, this.chatViewModeFor(id) === 'chat' ? 'terminal' : 'chat');
},
/**
* True when `e` is the chat view toggle chord and it applies here, so the xterm key handler
* swallows it. Outside a session that can show the chat view, the chord reaches the terminal.
*/
shouldToggleChatViewFromShortcut(e) {
if (!e || (!e.ctrlKey && !e.metaKey && !e.altKey)) return false;
if (!this.chatViewEligible(this.activeSessionId) || this._tilesOwnTerminal?.()) return false;
if (typeof this.getShortcutRegistry !== 'function' || typeof this.matchesShortcutEvent !== 'function') return false;
const shortcut = this.getShortcutRegistry().find((s) => s.id === 'toggle-chat-view');
if (!shortcut || shortcut.disabled) return false;
return this.matchesShortcutEvent(e, shortcut);
},
// ─── DOM ─────────────────────────────────────────────────────
/**
* `text` in the page's language. i18n.js translates the DOM as it changes, but it skips every
* <textarea> and the `data-i18n-skip` conversation, so the strings drawn there are looked up here.
*/
_chatViewT(text, vars) {
return window.CodemanI18n?.t?.(text, vars) ?? text;
},
_chatViewEnsureDom() {
if (this._chatView) return this._chatView;
const wrap = document.querySelector('.terminal-wrap');
if (!wrap) return null;
const toggle = document.createElement('div');
toggle.className = 'chat-view-toggle';
toggle.setAttribute('role', 'group');
toggle.setAttribute('aria-label', 'Session view');
toggle.hidden = true;
const chatBtn = document.createElement('button');
chatBtn.type = 'button';
chatBtn.className = 'chat-view-toggle-btn';
chatBtn.dataset.mode = 'chat';
chatBtn.textContent = 'Chat';
chatBtn.title = 'Show the conversation (Alt+Shift+C)';
const termBtn = document.createElement('button');
termBtn.type = 'button';
termBtn.className = 'chat-view-toggle-btn';
termBtn.dataset.mode = 'terminal';
termBtn.textContent = 'Terminal';
termBtn.title = 'Show the terminal (Alt+Shift+C)';
toggle.append(chatBtn, termBtn);
toggle.addEventListener('click', (ev) => {
const btn = ev.target.closest('.chat-view-toggle-btn');
if (btn && this.activeSessionId) this.setChatViewMode(this.activeSessionId, btn.dataset.mode);
});
const root = document.createElement('section');
root.className = 'chat-view';
root.setAttribute('aria-label', 'Conversation');
root.hidden = true;
// The Response Viewer's body class: the chat view renders exactly as the viewer does.
const scroller = document.createElement('div');
scroller.className = 'chat-view-scroll response-viewer-body';
scroller.setAttribute('data-i18n-skip', '');
// Focusable, so a focus taken from the hidden terminal has somewhere to go.
scroller.tabIndex = -1;
const thread = document.createElement('div');
thread.className = 'chat-view-thread';
const empty = document.createElement('p');
empty.className = 'chat-view-empty';
empty.hidden = true;
scroller.append(thread, empty);
const dialog = document.createElement('div');
dialog.className = 'chat-view-dialog';
dialog.setAttribute('role', 'status');
dialog.hidden = true;
const dialogText = document.createElement('span');
dialogText.className = 'chat-view-dialog-text';
dialogText.textContent = 'Claude is waiting for your answer in the terminal.';
const dialogBtn = document.createElement('button');
dialogBtn.type = 'button';
dialogBtn.className = 'chat-view-btn chat-view-btn-primary';
dialogBtn.textContent = 'Open terminal';
dialogBtn.addEventListener('click', () => {
const id = this.activeSessionId;
if (!id) return;
this.setChatViewMode(id, 'terminal');
this.terminal?.focus?.();
});
dialog.append(dialogText, dialogBtn);
const status = document.createElement('div');
status.className = 'chat-view-status';
status.setAttribute('role', 'status');
status.setAttribute('aria-live', 'polite');
status.hidden = true;
const statusDot = document.createElement('span');
statusDot.className = 'chat-view-status-dot';
statusDot.setAttribute('aria-hidden', 'true');
const statusBody = document.createElement('div');
statusBody.className = 'chat-view-status-body';
const statusText = document.createElement('div');
statusText.className = 'chat-view-status-text';
statusBody.append(statusText);
status.append(statusDot, statusBody);
// The status line follows the last message, inside the scrolling area, so an eye watching
// the newest output finds it there and not at the bottom of the window.
scroller.insertBefore(status, empty);
root.append(scroller, dialog);
wrap.append(root, toggle);
// Keys must never reach the hidden terminal: a focus that lands there (a click-through, a
// code path that refocuses the terminal after a load) moves to the conversation. That covers
// #terminalContainer and #cjkInput, which takes terminal.focus() while CJK input is on and
// sits outside the container, under the chat layer.
const redirectFocus = () => {
if (this._chatViewShowing()) this._chatView?.scroller.focus({ preventScroll: true });
};
document.getElementById('terminalContainer')?.addEventListener('focusin', redirectFocus);
document.getElementById('cjkInput')?.addEventListener('focusin', redirectFocus);
// A file dropped on the conversation or on the Chat / Terminal switch must not make the
// browser open it and leave Codeman. Nothing is uploaded here: an upload would type the file's
// path into the hidden pane, and attaching belongs to the message box (docs/chat-view-plan.md,
// phase 1 step 2). The no-drop cursor tells a user who drags a file here that Chat takes none.
const refuseDragOver = (ev) => {
ev.preventDefault();
if (ev.dataTransfer) ev.dataTransfer.dropEffect = 'none';
};
const refuseDrop = (ev) => ev.preventDefault();
for (const target of [root, toggle]) {
target.addEventListener('dragover', refuseDragOver);
target.addEventListener('drop', refuseDrop);
}
this._chatView = {
root,
toggle,
chatBtn,
termBtn,
scroller,
thread,
empty,
dialog,
status,
statusText,
sessionId: null,
keys: [],
reloadTimer: null,
statusTimer: null,
loading: false,
reloadAgain: false,
};
return this._chatView;
},
/** Whether the chat view is what the main area shows right now. */
_chatViewShowing() {
return !!this._chatView && !this._chatView.root.hidden;
},
/** Whether keyboard focus sits in the terminal: inside #terminalContainer, or on #cjkInput. */
_chatViewFocusInTerminal() {
const active = document.activeElement;
if (!active) return false;
if (active.id === 'cjkInput') return true;
return !!document.getElementById('terminalContainer')?.contains(active);
},
// ─── Sync with the active session ────────────────────────────
/** app.js selectSession(): the active session changed. */
onChatViewActiveSession() {
this._chatViewSync({ focus: true });
},
/**
* Show or hide the toggle and the chat view for the active session, and (re)load the
* conversation when the chat view starts showing a session.
*/
_chatViewSync(opts = {}) {
const id = this.activeSessionId;
const eligible = this.chatViewEligible(id);
if (!eligible && !this._chatView) return;
const view = this._chatViewEnsureDom();
if (!view) return;
// Focus follows the app's tab-switch rule, as the terminal's does.
const focus = !!opts.focus && (this._shouldFocusTerminalForTabSwitch?.() ?? true);
const mode = eligible ? this.chatViewModeFor(id) : 'terminal';
// The tile grid owns the terminal area while it is open, and its tiles are terminals: the
// chat view stays hidden, whatever the active session's choice (tile-grid.js syncs it).
const showChat = eligible && mode === 'chat' && !this._tilesOwnTerminal?.();
// The setting hides only the switch: the session keeps its view, and Alt+Shift+C still works.
view.toggle.hidden = !eligible || !this._chatViewSwitchShown();
view.chatBtn.setAttribute('aria-pressed', String(showChat));
view.termBtn.setAttribute('aria-pressed', String(!showChat));
view.toggle.classList.toggle('chat-view-toggle--over-chat', showChat);
const wasShowing = !view.root.hidden;
const previousId = view.sessionId;
view.root.hidden = !showChat;
document.querySelector('.terminal-wrap')?.classList.toggle('chat-view-active', showChat);
// styles.css hides the keyboard accessory bar while this is set: its keys write into the pane.
document.body.classList.toggle('chat-view-showing', showChat);
if (!showChat) {
if (view.statusTimer) {
clearInterval(view.statusTimer);
view.statusTimer = null;
}
if (wasShowing && focus && eligible) this.terminal?.focus?.();
return;
}
if (previousId !== id) {
view.sessionId = id;
view.keys = [];
view.thread.replaceChildren();
view.empty.hidden = true;
}
const agent = this._getResponseViewerAgentLabel?.() || 'Claude';
view.root.querySelector('.chat-view-dialog-text').textContent =
`${agent} is waiting for your answer in the terminal.`;
this._chatViewSyncDialog(id);
this._chatViewRenderStatus();
if (previousId !== id || !wasShowing) this._chatViewReload({ immediate: true });
// A terminal that already has focus fires no new focusin, so hardware-keyboard input would
// keep reaching the pane behind the chat view. Move that focus now, whatever the tab-switch
// rule says: focusing the conversation opens no soft keyboard.
if (this._chatViewFocusInTerminal()) view.scroller.focus({ preventScroll: true });
if (focus) requestAnimationFrame(() => view.scroller.focus({ preventScroll: true }));
},
/** Hide everything (home screen, session gone). */
_chatViewHide() {
if (!this._chatView) return;
if (this._chatView.statusTimer) {
clearInterval(this._chatView.statusTimer);
this._chatView.statusTimer = null;
}
this._chatView.root.hidden = true;
this._chatView.toggle.hidden = true;
document.querySelector('.terminal-wrap')?.classList.remove('chat-view-active');
document.body.classList.remove('chat-view-showing');
},
/**
* Called when a session is deleted (app.js): forget its turn state. The view choice stays, because
* a detach sends the same event and the session can be attached again; `_chatViewPruneModes`
* drops the choices of sessions that are gone.
*/
_chatViewForget(sessionId) {
this._chatViewTurnStarts?.delete(sessionId);
this._chatViewIdleSeen?.delete(sessionId);
this._chatViewKeepAliveTurns?.delete(sessionId);
if (this._chatView?.sessionId === sessionId) {
this._chatView.sessionId = null;
this._chatView.keys = [];
this._chatView.thread.replaceChildren();
}
},
// ─── Events ──────────────────────────────────────────────────
/** SSE `transcript:update`: new transcript lines for `data.sessionId`. */
_onChatViewTranscriptUpdate(data) {
if (data?.sessionId && data.sessionId === this._chatView?.sessionId && this._chatViewShowing()) {
this._chatViewReload();
}
},
/**
* app.js `_onSessionIdle` / `_onSessionWorking`: a turn started or ended. `keepAlive` marks
* Codeman's own keep-warm turn, which the conversation hides: the status line stays hidden
* for it.
*/
onChatViewTurnEvent(sessionId, idle, keepAlive) {
if (!this._chatViewTurnStarts) this._chatViewTurnStarts = new Map();
if (!this._chatViewIdleSeen) this._chatViewIdleSeen = new Set();
if (!this._chatViewKeepAliveTurns) this._chatViewKeepAliveTurns = new Set();
if (!idle && keepAlive) this._chatViewKeepAliveTurns.add(sessionId);
else this._chatViewKeepAliveTurns.delete(sessionId);
// A turn's start is "now" only when this page saw the session idle first. A working event
// for a session already busy when the page loaded (or the server restarted) says nothing
// about when its turn began, so the status line falls back to the last Enter.
if (!idle && this._chatViewIdleSeen.has(sessionId)) {
this._chatViewIdleSeen.delete(sessionId);
this._chatViewTurnStarts.set(sessionId, Date.now());
}
if (idle) {
this._chatViewIdleSeen.add(sessionId);
this._chatViewTurnStarts.delete(sessionId);
}
if (sessionId !== this._chatView?.sessionId || !this._chatViewShowing()) return;
this._chatViewRenderStatus();
this._chatViewReload();
},
/** app.js updateTabAlertFromHooks(): a dialog appeared or was answered. */
onChatViewHooksChanged(sessionId) {
if (sessionId !== this._chatView?.sessionId || !this._chatViewShowing()) return;
this._chatViewSyncDialog(sessionId);
},
/** Whether the pane shows a dialog (permission, question, plan approval), answered in the terminal. */
_chatViewDialogPending(sessionId) {
const hooks = this.pendingHooks?.get(sessionId);
return !!hooks && (hooks.has('permission_prompt') || hooks.has('elicitation_dialog'));
},
_chatViewSyncDialog(sessionId) {
const view = this._chatView;
if (!view) return;
view.dialog.hidden = !this._chatViewDialogPending(sessionId);
},
/** Whether `sessionId` runs a turn the chat view shows: busy, and not Codeman's keep-alive turn. */
_chatViewBusy(sessionId) {
if (this._chatViewKeepAliveTurns?.has(sessionId)) return false;
return this.sessions?.get(sessionId)?.status === 'busy';
},
_chatViewRenderStatus() {
const view = this._chatView;
if (!view) return;
const session = this.sessions?.get(view.sessionId);
const busy = this._chatViewBusy(view.sessionId);
// Keep the view pinned to the bottom when the status line appears under the last message,
// if the reader was already there.
const scroller = view.scroller;
const atBottom = scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 48;
view.status.hidden = !busy;
if (!busy && view.sessionId) {
if (!this._chatViewIdleSeen) this._chatViewIdleSeen = new Set();
this._chatViewIdleSeen.add(view.sessionId);
}
if (busy) {
const activity = this._chatViewT('Working');
// The turn's start: seen live (session:working after idle), else the last Enter (a page
// loaded mid-turn), else unknown and left out.
const startedAt = this._chatViewTurnStarts?.get(view.sessionId) || session?.lastSubmitAt || 0;
view.statusText.textContent = startedAt
? `${activity} · ${window.CodemanChatView.elapsed(Date.now() - startedAt)}`
: activity;
}
// The running time ticks once a second, only while the status line is on screen.
const ticking = busy && this._chatViewShowing();
if (ticking && !view.statusTimer) view.statusTimer = setInterval(() => this._chatViewRenderStatus(), 1000);
if (!ticking && view.statusTimer) {
clearInterval(view.statusTimer);
view.statusTimer = null;
}
if (atBottom) scroller.scrollTop = scroller.scrollHeight;
},
// ─── Reading and drawing the conversation ────────────────────
/** Re-read the conversation, debounced unless `immediate`. One read at a time. */
_chatViewReload(opts = {}) {
const view = this._chatView;
if (!view || !view.sessionId) return;
clearTimeout(view.reloadTimer);
if (opts.immediate) {
this._chatViewFetch();
return;
}
view.reloadTimer = setTimeout(() => this._chatViewFetch(), CHAT_VIEW_RELOAD_DEBOUNCE_MS);
},
async _chatViewFetch() {
const view = this._chatView;
if (!view || !view.sessionId || !this._chatViewShowing()) return;
if (view.loading) {
view.reloadAgain = true;
return;
}
const sessionId = view.sessionId;
view.loading = true;
try {
const data = await this._apiJson(`/api/sessions/${encodeURIComponent(sessionId)}/last-response?context=full`);
// A read that finished after the user moved on is dropped.
if (view.sessionId !== sessionId || !this._chatViewShowing()) return;
if (data && Array.isArray(data.messages)) this._chatViewRender(data.messages);
} finally {
view.loading = false;
if (view.reloadAgain) {
view.reloadAgain = false;
this._chatViewReload();
}
}
},
_chatViewRender(rawMessages) {
const view = this._chatView;
const helpers = window.CodemanChatView;
if (!view || !helpers) return;
const messages = helpers.visibleMessages(rawMessages);
const keys = messages.map(helpers.messageKey);
const plan = helpers.renderPlan(view.keys, keys);
view.empty.hidden = messages.length > 0;
if (messages.length === 0) view.empty.textContent = this._chatViewT('No messages yet.');
if (plan.mode === 'none') return;
const scroller = view.scroller;
const atBottom = scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 48;
const firstDraw = view.keys.length === 0;
const from = plan.mode === 'append' ? plan.from : 0;
if (plan.mode === 'replace') view.thread.replaceChildren();
const agentLabel = this._getResponseViewerAgentLabel?.() || 'Claude';
const fragment = document.createDocumentFragment();
for (let i = from; i < messages.length; i++) {
const msg = messages[i];
const previous = i > 0 ? messages[i - 1] : null;
// Same rule as the Response Viewer's full view: one badge per speaker per turn.
const continuation =
!!previous && previous.role === msg.role && typeof msg.turn === 'number' && previous.turn === msg.turn;
fragment.appendChild(this._chatViewBuildMessage(msg, agentLabel, continuation));
}
view.thread.appendChild(fragment);
view.keys = keys;
this._bindResponseViewerInteractions?.(view.thread);
if (firstDraw || atBottom) scroller.scrollTop = scroller.scrollHeight;
},
/** One drawn message. A long prompt folds to its first lines. */
_chatViewBuildMessage(msg, agentLabel, continuation) {
const meta = { ...msg, continuation };
if (msg.role !== 'user') return this._buildResponseViewerMessage(msg.text, 'assistant', agentLabel, meta);
const text = window.CodemanChatView.promptText(msg.text);
const fold = window.CodemanChatView.promptFold(text);
const el = this._buildResponseViewerMessage(fold.head, 'user', agentLabel, meta);
if (!fold.folded) return el;
el.classList.add('chat-view-msg-folded');
const more = document.createElement('button');
more.type = 'button';
more.className = 'chat-view-show-all';
more.textContent = this._chatViewT(`Show all (${fold.totalLines} ${fold.totalLines === 1 ? 'line' : 'lines'})`);
// Unfold in place, keeping the badge the element shows now.
more.addEventListener('click', () => {
const full = this._buildResponseViewerMessage(text, 'user', agentLabel, {
...meta,
continuation: el.classList.contains('rv-msg-cont'),
});
el.replaceChildren(...full.childNodes);
el.classList.remove('chat-view-msg-folded');
});
el.appendChild(more);
return el;
},
});
+98
View File
@@ -1514,6 +1514,95 @@ function findMarkdownAnchorTarget(root, href) {
return null;
}
// ─── Chat view (chat-view.js) ─────────────────────────────────────────────────
// Pure halves of the chat view, the rendered conversation that replaces the terminal
// as a session's main view (docs/chat-view-plan.md). The module owns the DOM; these
// decide what it shows, so a test can pin them without a browser.
/** A prompt longer than this many lines, or characters, is folded. */
const CHAT_PROMPT_FOLD_LINES = 12;
const CHAT_PROMPT_FOLD_CHARS = 2400;
/** What a folded prompt still shows. */
const CHAT_PROMPT_HEAD_LINES = 6;
const CHAT_PROMPT_HEAD_CHARS = 800;
/**
* The messages the chat view draws, in order: prompts and answers with text, without
* the keep-warm turns Codeman sends on its own (`keepAlive`, set by the transcript reader).
*/
function chatViewVisibleMessages(messages) {
if (!Array.isArray(messages)) return [];
return messages.filter(
(m) =>
!!m &&
(m.role === 'user' || m.role === 'assistant') &&
typeof m.text === 'string' &&
m.text.trim() !== '' &&
m.keepAlive !== true
);
}
/** Identity of a drawn message: a transcript row never changes once written. */
function chatViewMessageKey(m) {
return `${m.role}\u0000${typeof m.turn === 'number' ? m.turn : ''}\u0000${m.queued ? 'q' : ''}\u0000${m.text}`;
}
/**
* How to bring the drawn thread up to date. `none` when nothing changed, `append`
* when the new list only adds messages after the drawn ones (the usual case while a
* turn runs), else `replace` (a `/clear`, a rewritten transcript, another session).
*/
function chatViewRenderPlan(drawnKeys, nextKeys) {
const drawn = Array.isArray(drawnKeys) ? drawnKeys : [];
const next = Array.isArray(nextKeys) ? nextKeys : [];
if (drawn.length > next.length) return { mode: 'replace' };
for (let i = 0; i < drawn.length; i++) {
if (drawn[i] !== next[i]) return { mode: 'replace' };
}
if (drawn.length === next.length) return { mode: 'none' };
return { mode: 'append', from: drawn.length };
}
/**
* A prompt as the user wrote it. Claude Code stores a pasted block (which every multi-line
* prompt sent through tmux is) inside `<pasted_content id="…">…</pasted_content id="…">` (the
* closing tag repeats the id, measured on Claude Code 2.1.331); the markdown
* renderer reads that as a raw HTML block and runs its lines together. Only matched pairs are
* unwrapped, so a prompt that merely mentions the tag is left alone.
*/
function chatViewPromptText(text) {
return String(text ?? '').replace(
/<pasted_content(?:\s[^>]*)?>\n?([\s\S]*?)\n?<\/pasted_content(?:\s[^>]*)?>/g,
(_match, body) => body
);
}
/** A running turn's length as the CLI shows it: `14s`, `2m 05s`, `1h 03m`. */
function chatViewElapsed(ms) {
const total = Math.max(0, Math.floor((Number(ms) || 0) / 1000));
const h = Math.floor(total / 3600);
const m = Math.floor((total % 3600) / 60);
const sec = total % 60;
if (h > 0) return `${h}h ${String(m).padStart(2, '0')}m`;
if (m > 0) return `${m}m ${String(sec).padStart(2, '0')}s`;
return `${sec}s`;
}
/**
* Whether a prompt is folded, and what its folded form shows: the first lines, capped
* in characters so one enormous pasted line folds too.
*/
function chatViewPromptFold(text) {
const value = String(text ?? '');
const lines = value.split('\n');
if (lines.length <= CHAT_PROMPT_FOLD_LINES && value.length <= CHAT_PROMPT_FOLD_CHARS) {
return { folded: false, head: value, totalLines: lines.length };
}
let head = lines.slice(0, CHAT_PROMPT_HEAD_LINES).join('\n');
if (head.length > CHAT_PROMPT_HEAD_CHARS) head = `${head.slice(0, CHAT_PROMPT_HEAD_CHARS)}…`;
return { folded: true, head, totalLines: lines.length };
}
if (typeof window !== 'undefined') {
window.WEBGL_FALLBACK = WEBGL_FALLBACK;
window.evaluateWebGLLongTaskTrip = evaluateWebGLLongTaskTrip;
@@ -1581,6 +1670,14 @@ if (typeof window !== 'undefined') {
needle: tabSearchNeedle,
filter: filterTabSearchRows,
};
window.CodemanChatView = {
visibleMessages: chatViewVisibleMessages,
messageKey: chatViewMessageKey,
renderPlan: chatViewRenderPlan,
promptFold: chatViewPromptFold,
promptText: chatViewPromptText,
elapsed: chatViewElapsed,
};
window.CodemanInputLimit = {
FRAME_MAX_CHARS: INPUT_FRAME_MAX_CHARS,
PASTE_MAX_CHARS: INPUT_PASTE_MAX_CHARS,
@@ -1914,6 +2011,7 @@ const SSE_EVENTS = {
TRANSCRIPT_PLAN_MODE: 'transcript:plan_mode',
TRANSCRIPT_TOOL_START: 'transcript:tool_start',
TRANSCRIPT_TOOL_END: 'transcript:tool_end',
TRANSCRIPT_UPDATE: 'transcript:update',
// Clipboard
CLIPBOARD_WRITE: 'clipboard:write',
+32 -2
View File
@@ -225,6 +225,21 @@
// input like Click (单击).
Tabs: '标签页',
'Toggle Session Sidebar': '切换会话侧边栏',
// Chat view (chat-view.js) and its App Settings row.
'Toggle Chat / Terminal View': '切换聊天 / 终端视图',
Chat: '聊天',
'Open terminal': '打开终端',
Conversation: '对话',
'Session view': '会话视图',
'Show the conversation (Alt+Shift+C)': '显示对话 (Alt+Shift+C)',
'Show the terminal (Alt+Shift+C)': '显示终端 (Alt+Shift+C)',
'No messages yet.': '还没有消息。',
'Open Claude sessions in Chat view': '以聊天视图打开 Claude 会话',
"Show a session's conversation rendered as text instead of the terminal. Each session remembers its own choice, and Alt+Shift+C or the Chat / Terminal switch changes it. Not on phones.":
'以渲染后的文本显示会话的对话,代替终端。每个会话记住自己的选择,可用 Alt+Shift+C 或聊天 / 终端开关切换。手机上不可用。',
'Show the Chat / Terminal switch': '显示聊天 / 终端开关',
'Show the Chat / Terminal switch at the top right of a Claude session. Alt+Shift+C switches views without it. Not on phones.':
'在 Claude 会话右上角显示聊天 / 终端开关。没有它时,Alt+Shift+C 也能切换视图。手机上不可用。',
'Copy Selection': '复制选中内容',
'Copy Selection (interrupts when nothing is selected)': '复制选中内容(无选中内容时中断)',
'Focus Tabs': '聚焦标签页',
@@ -244,6 +259,12 @@
'No response yet — send a message in this session first.': '暂无回复,请先在此会话中发送一条消息。',
'No full conversation history available for this session': '此会话没有可显示的完整对话历史',
'Last Response': '最近一次回复',
'Response files': '回复中的文件',
'Open Codex response files': '打开 Codex 回复中的文件',
'Dock preview': '停靠预览',
'No previewable files in the latest response.': '最新回复中没有可预览的文件。',
'Unable to load response files': '无法加载回复中的文件',
'Discard unsaved changes?': '放弃未保存的更改?',
More: '更多',
'Copy Markdown': '复制 Markdown',
'Copy response as Markdown': '将回复复制为 Markdown',
@@ -481,6 +502,9 @@
'CPU MHz': 'CPU 频率',
'Lifecycle Log': '生命周期日志',
'Response Viewer': '回复查看器',
'Codex files': 'Codex 文件',
'Codex sessions: underlined file names and Codex sidebar file tabs open in the preview, a Response files header button, and a Dock control on file previews':
'Codex 会话:在预览中打开带下划线的文件名和 Codex 侧边栏文件标签、标题栏的回复中的文件按钮,以及文件预览上的停靠控件',
'Attachments Button': '附件按钮',
'Multi-monitor Button': '多显示器按钮',
'Session Manager Button': '会话管理器按钮',
@@ -1733,6 +1757,8 @@
[/^(\d+) running$/, (_m, count) => `${count} 个运行中`],
[/^(\d+) active$/, (_m, count) => `${count} 个活动`],
[/^Show (\d+) more$/, (_m, count) => `再显示 ${count} 项`],
// Chat view (chat-view.js).
[/^Show all \((\d+) lines?\)$/, (_m, count) => `显示全部(${count} 行)`],
[/^Show (\d+) more \((\d+) remaining\)$/, (_m, count, remaining) => `再显示 ${count} 项(剩余 ${remaining} 项)`],
[/^Lifetime: (\d+) sessions created$/, (_m, count) => `累计已创建 ${count} 个会话`],
[/^Tunnel active: (.+)$/, (_m, url) => `隧道已启用:${url}`],
@@ -1832,8 +1858,12 @@
(_m, name, why) => `案例“${name}”的选项已保存到本设备(同步前有效),但未保存到服务器:${ZH_CN[why] || why}`,
],
// A dialog read off a hook-less CLI's screen (src/web/screen-blocked.ts), as the
// notification drawer shows it. The CLI's label passes through.
[/^(.+) is waiting for your answer in the terminal$/, (_m, cli) => `${cli} 正在终端中等待你的回答`],
// notification drawer shows it, and the chat view's notice, which ends in a period.
// The agent's label passes through.
[
/^(.+) is waiting for your answer in the terminal(\.?)$/,
(_m, who, dot) => `${who} 正在终端中等待你的回答${dot ? '。' : ''}`,
],
[/^The agent exited \(signal (\d+)\)$/, (_m, signal) => `智能体已退出(信号 ${signal})`],
// A session header's harness logo (tile grid, split pane): "<harness> · <model>",
// and where the model came from when the CLI did not report it. The harness
+1 -1
View File
@@ -306,7 +306,7 @@ Object.assign(CodemanApp.prototype, {
const ext = (file.name || '').toLowerCase().match(/\.([a-z0-9]+)$/)?.[1] || '';
if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'heic', 'heif'].includes(ext)) return 'image';
if (['mp4', 'webm', 'mov', 'm4v', 'ogv'].includes(ext)) return 'video';
if (['pdf', 'docx', 'pptx', 'xlsx', 'zip', 'txt', 'md', 'csv', 'tsv', 'json', 'log', 'yaml', 'yml', 'xml'].includes(ext)) {
if (['pdf', 'docx', 'pptx', 'xlsx', 'zip', 'txt', 'md', 'csv', 'tsv', 'json', 'log', 'yaml', 'yml', 'xml', 'html', 'htm'].includes(ext)) {
return 'document';
}
return null;
+22 -4
View File
@@ -206,6 +206,7 @@
</div>
<button class="btn-icon-header btn-redraw-terminal btn-redraw-terminal--hidden" onclick="app.restoreTerminalSize()" title="Redraw terminal to fit current screen (Ctrl+Shift+R)" aria-label="Redraw terminal"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="1 4 1 10 7 10"/><polyline points="23 20 23 14 17 14"/><path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"/></svg></button>
<button class="btn-icon-header btn-response-viewer-header btn-response-viewer-header--hidden" onclick="app.toggleResponseViewer()" title="View last response" aria-label="View last response"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></button>
<button id="responseFilesBtn" type="button" class="btn-icon-header btn-response-files btn-response-files--hidden" onclick="app.toggleResponseViewer(true)" title="Response files" aria-label="Open Codex response files" hidden><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6M8 13h8m-8 4h6"/></svg></button>
<button class="btn-icon-header btn-away-digest btn-away-digest--hidden" onclick="app.openAwayDigest()" title="Away Digest" aria-label="Open away digest"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 6h13"/><path d="M8 12h13"/><path d="M8 18h13"/><path d="M3 6h.01"/><path d="M3 12h.01"/><path d="M3 18h.01"/></svg></button>
<button class="btn-icon-header btn-session-manager btn-session-manager--hidden" onclick="app.openSessionManager()" title="Session Manager" aria-label="Open session manager"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></svg></button>
<button class="btn-icon-header btn-approvals btn-approvals--hidden" id="approvalsBtn" onclick="app.toggleApprovalsInbox()" title="Approvals waiting on you" aria-label="Open approvals inbox" aria-expanded="false">
@@ -696,6 +697,7 @@
<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 type="button" class="btn-icon-sm" id="filePreviewDockBtn" hidden onclick="app.toggleFilePreviewDock()" title="Dock preview" aria-label="Dock preview" aria-pressed="false"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M15 4v16"/></svg></button>
<button class="btn-icon-sm" id="filePreviewExpandBtn" onclick="app.toggleFilePreviewExpanded()" title="Expand" aria-label="Expand" aria-pressed="false"><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"><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg></button>
<button class="btn-icon-sm" onclick="app.closeFilePreview()" title="Close">&times;</button>
</div>
@@ -735,12 +737,12 @@
<div class="response-viewer-actions">
<button class="response-viewer-more" id="responseViewerMore" onclick="app.loadFullContext()">More</button>
<button class="response-viewer-more response-viewer-copy-markdown" id="responseViewerCopyMarkdown" type="button" onclick="app.copyResponseViewerMarkdown()" title="Copy response as Markdown">Copy Markdown</button>
<button class="response-viewer-close" onclick="app.toggleResponseViewer()">&times;</button>
<button class="response-viewer-close" onclick="app.closeResponseViewer()">&times;</button>
</div>
</div>
<div class="response-viewer-body" id="responseViewerBody"></div>
</div>
<div class="response-viewer-backdrop" id="responseViewerBackdrop" onclick="app.toggleResponseViewer()"></div>
<div class="response-viewer-backdrop" id="responseViewerBackdrop" onclick="app.closeResponseViewer()"></div>
<!-- Bottom Toolbar -->
<footer class="toolbar">
@@ -870,7 +872,7 @@
<path d="m21 15-5-5L5 21"/>
</svg>
</button>
<input type="file" class="btn-attach-mobile-input" id="attachFileInput" accept="image/*,video/*,.pdf,.docx,.pptx,.xlsx,.zip,.txt,.md,.csv,.tsv,.json,.log,.yaml,.yml,.xml" multiple tabindex="-1" aria-hidden="true">
<input type="file" class="btn-attach-mobile-input" id="attachFileInput" accept="image/*,video/*,.pdf,.docx,.pptx,.xlsx,.zip,.txt,.md,.csv,.tsv,.json,.log,.yaml,.yml,.xml,.html,.htm" multiple tabindex="-1" aria-hidden="true">
</span>
<button class="btn-voice-mobile" id="voiceInputBtnMobile" onclick="VoiceInput.toggle()"
title="Voice input" aria-label="Start voice input" aria-pressed="false">
@@ -2246,13 +2248,14 @@
<div class="set-group-head"><h4>Header buttons</h4><span class="set-scope">device</span></div>
<p class="set-group-hint">Tap to show a control in the header. Multi-monitor is the one entry here that syncs across devices.</p>
<div class="set-group-body">
<div class="set-chips" data-search="header buttons plan usage font stats lifecycle response file viewer attachments monitor session away cron redraw split tiles">
<div class="set-chips" data-search="header buttons plan usage font stats lifecycle response codex files file viewer attachments monitor session away cron redraw split tiles">
<label class="set-chip" data-preview="header" data-preview-order="1" data-preview-text="A+"><input type="checkbox" id="appSettingsShowFontControls"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 20 10 5l6 15"/><path d="M6.5 15h7"/><path d="M18 12h4M20 10v4"/></svg><span>Font Size</span></label>
<label class="set-chip" data-preview="header" data-preview-order="2" data-preview-text="CPU 12%"><input type="checkbox" id="appSettingsShowSystemStats" checked><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 12h4l2.5-7 4 14L16 12h5"/></svg><span>System Stats</span></label>
<label class="set-chip" data-preview="header" data-preview-order="2" data-preview-text="GPU 8%"><input type="checkbox" id="appSettingsShowGpuStats"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="7" width="18" height="10" rx="2"/><path d="M7 21v-4M12 21v-4M17 21v-4M7 7V3M17 7V3"/></svg><span>GPU Stats</span></label>
<label class="set-chip" data-preview="header" data-preview-order="2" data-preview-text="3400 MHz"><input type="checkbox" id="appSettingsShowCpuMhz"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg><span>CPU MHz</span></label>
<label class="set-chip" data-preview="header" data-preview-order="3"><input type="checkbox" id="appSettingsShowRedrawButton"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="1 4 1 10 7 10"/><polyline points="23 20 23 14 17 14"/><path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"/></svg><span>Redraw Terminal</span></label>
<label class="set-chip" data-preview="header" data-preview-order="4"><input type="checkbox" id="appSettingsShowResponseViewer"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg><span>Response Viewer</span></label>
<label class="set-chip" data-search="codex files response files sidebar file tabs dock preview" data-preview="header" data-preview-order="4.5" title="Codex sessions: underlined file names and Codex sidebar file tabs open in the preview, a Response files header button, and a Dock control on file previews"><input type="checkbox" id="appSettingsCodexFilePreviews"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6M8 13h8m-8 4h6"/></svg><span>Codex files</span></label>
<label class="set-chip" data-preview="header" data-preview-order="5"><input type="checkbox" id="appSettingsShowAwayDigestButton"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 6h13"/><path d="M8 12h13"/><path d="M8 18h13"/><path d="M3 6h.01"/><path d="M3 12h.01"/><path d="M3 18h.01"/></svg><span>Away Digest</span></label>
<label class="set-chip" data-preview="header" data-preview-order="6"><input type="checkbox" id="appSettingsShowSessionButton"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></svg><span>Session Manager</span></label>
<label class="set-chip" data-preview="header" data-preview-order="9"><input type="checkbox" id="appSettingsShowAttachmentsButton"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg><span>Attachments</span></label>
@@ -2287,6 +2290,20 @@
<label class="set-chip" data-preview="panel" data-preview-order="3"><input type="checkbox" id="appSettingsShowFileBrowser"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg><span>File Browser</span></label>
<label class="set-chip" data-preview="panel" data-preview-order="4"><input type="checkbox" id="appSettingsShowSubagents"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/><circle cx="18" cy="12" r="2.5"/><path d="M8.2 7.2 15.6 11M8.2 16.8 15.6 13"/></svg><span>Subagents</span></label>
</div>
<div class="set-row" data-search="chat view conversation rendered markdown terminal default claude sessions readable">
<div class="set-row-text">
<span class="set-row-label">Open Claude sessions in Chat view</span>
<span class="set-row-desc">Show a session's conversation rendered as text instead of the terminal. Each session remembers its own choice, and Alt+Shift+C or the Chat / Terminal switch changes it. Not on phones.</span>
</div>
<label class="switch switch-sm"><input type="checkbox" id="appSettingsChatViewDefault"><span class="slider"></span></label>
</div>
<div class="set-row" data-search="chat view terminal switch toggle button show hide claude sessions">
<div class="set-row-text">
<span class="set-row-label">Show the Chat / Terminal switch</span>
<span class="set-row-desc">Show the Chat / Terminal switch at the top right of a Claude session. Alt+Shift+C switches views without it. Not on phones.</span>
</div>
<label class="switch switch-sm"><input type="checkbox" id="appSettingsShowChatViewSwitch"><span class="slider"></span></label>
</div>
</div>
</div>
@@ -4586,6 +4603,7 @@
<script defer src="git-status-ui.js"></script>
<script defer src="edit-history-ui.js"></script>
<script defer src="local-model-ui.js"></script>
<script defer src="chat-view.js"></script>
<script defer src="entrance-animations.js"></script>
<script defer src="api-client.js"></script>
<script defer src="subagent-windows.js"></script>
+2 -2
View File
@@ -1564,7 +1564,7 @@ const KeyboardAccessoryBar = {
<button type="button" class="paste-cancel">Cancel</button>
<button type="button" class="paste-send">Send</button>
</div>
<input type="file" class="paste-file-input" accept="image/*,video/*,.pdf,.docx,.pptx,.xlsx,.zip,.txt,.md,.csv,.tsv,.json,.log,.yaml,.yml,.xml" multiple hidden>
<input type="file" class="paste-file-input" accept="image/*,video/*,.pdf,.docx,.pptx,.xlsx,.zip,.txt,.md,.csv,.tsv,.json,.log,.yaml,.yml,.xml,.html,.htm" multiple hidden>
</div>
`;
@@ -1786,7 +1786,7 @@ const KeyboardAccessoryBar = {
<button class="paste-cancel">Cancel</button>
<button class="paste-send">Send</button>
</div>
<input type="file" class="paste-file-input" accept="image/*,video/*,.pdf,.docx,.pptx,.xlsx,.zip,.txt,.md,.csv,.tsv,.json,.log,.yaml,.yml,.xml" multiple hidden>
<input type="file" class="paste-file-input" accept="image/*,video/*,.pdf,.docx,.pptx,.xlsx,.zip,.txt,.md,.csv,.tsv,.json,.log,.yaml,.yml,.xml,.html,.htm" multiple hidden>
</div>
`;
+3
View File
@@ -593,6 +593,9 @@ html.mobile-init .file-browser-panel {
.btn-icon-header.btn-session-manager,
/* Edit history: a desktop panel; phones never show the button (opt-in, default OFF anyway). */
.btn-icon-header.btn-edit-history,
/* Response files: the phone header keeps one opt-in button (File Viewer), so
this stays off phones even with the Codex files setting on. */
.btn-icon-header.btn-response-files,
/* Approvals bell: phones answer from the overview's NEEDS YOU rows instead
(inline approve/deny in mobile-overview.js); the bell would only crowd the
header it was designed to stay out of. */
+55
View File
@@ -4021,6 +4021,56 @@ Object.assign(CodemanApp.prototype, {
if (headerBtn) headerBtn.setAttribute('aria-expanded', 'false');
},
_setFilePreviewDocked(dock) {
const overlay = this.$('filePreviewOverlay');
if (!overlay) return;
const terminalWrap = this.$('terminalContainer')?.closest('.terminal-wrap');
// Docking is one of the Codex files extras (_codexFilePreviewsEnabled, app.js): with the
// setting off a preview only ever floats. Undocking is always allowed.
dock = Boolean(
dock &&
this._codexFilePreviewsEnabled?.() &&
terminalWrap?.parentElement?.matches('.main:not(.tiles-active, .webview-active)') &&
window.matchMedia?.('(min-width: 1180px)').matches
);
if (dock === overlay.classList.contains('is-docked')) return;
if (dock) {
if (!overlay.parentElement) return;
this._filePreviewOverlayHome = overlay.parentElement;
terminalWrap.after(overlay);
} else {
this._filePreviewOverlayHome?.append(overlay);
this._filePreviewOverlayHome = null;
}
overlay.classList.toggle('is-docked', dock);
this.$('filePreviewDockBtn')?.setAttribute('aria-pressed', String(dock));
},
_isFilePreviewDocked() {
const overlay = this.$('filePreviewOverlay');
return (
overlay?.classList.contains('is-docked') &&
overlay.parentElement?.matches('.main:not(.tiles-active, .webview-active)') &&
window.matchMedia?.('(min-width: 1180px)').matches
);
},
toggleFilePreviewDock() {
const overlay = this.$('filePreviewOverlay');
if (!overlay?.classList.contains('visible')) return;
this._setFilePreviewDocked(!overlay.classList.contains('is-docked'));
},
_maybeCloseDockedFilePreviewOnEscape(event) {
const overlay = this.$('filePreviewOverlay');
if (!this._isFilePreviewDocked() || !overlay?.classList.contains('visible') || !overlay.contains(event.target)) return false;
event.preventDefault();
event.stopPropagation();
this.closeFilePreview();
if (!overlay.classList.contains('visible')) this.terminal?.focus();
return true;
},
/**
* Whether a path is absolute and provably OUTSIDE this session's workspace.
*
@@ -4127,6 +4177,9 @@ Object.assign(CodemanApp.prototype, {
if (!overlay || !bodyEl) return;
const dockBtn = this.$('filePreviewDockBtn');
if (dockBtn) dockBtn.hidden = !this._codexFilePreviewsEnabled?.();
if (options.dock) this._setFilePreviewDocked?.(true);
this._recordFilePreviewHistory(filePath, sessionId, attachmentId, options);
this._bindFilePreviewChrome();
@@ -4657,6 +4710,7 @@ Object.assign(CodemanApp.prototype, {
if (ev.key !== 'ArrowLeft' && ev.key !== 'ArrowRight') return;
if (!this.$('filePreviewOverlay')?.classList.contains('visible')) return;
const t = ev.target;
if (this._isFilePreviewDocked?.() && !this.$('filePreviewOverlay')?.contains(t)) return;
if (t && (t.isContentEditable || (/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName) && !t.classList?.contains('xterm-helper-textarea')))) return;
// Swallowed even at the ends of the list: otherwise the terminal behind the overlay
// types it as word-left/right, and on a header button the browser's own Alt+← goes Back.
@@ -4787,6 +4841,7 @@ Object.assign(CodemanApp.prototype, {
const overlay = this.$('filePreviewOverlay');
if (overlay) {
overlay.classList.remove('visible');
this._setFilePreviewDocked?.(false);
}
// The overlay is hidden with display:none, which stops it being PAINTED and
// nothing else: a <video>/<audio> inside it keeps playing, keeps its audio
+27 -3
View File
@@ -605,6 +605,8 @@ Object.assign(CodemanApp.prototype, {
// in the template, so an unchecked box and a hidden button stay consistent).
document.getElementById('appSettingsShowSessionButton').checked = settings.showSessionButton ?? defaults.showSessionButton ?? false;
document.getElementById('appSettingsShowAwayDigestButton').checked = settings.showAwayDigestButton ?? defaults.showAwayDigestButton ?? false;
// Codex files (Response files button, sidebar file tabs, Dock): per-device, default OFF.
document.getElementById('appSettingsCodexFilePreviews').checked = settings.codexFilePreviewsEnabled ?? defaults.codexFilePreviewsEnabled ?? false;
document.getElementById('appSettingsShowCronButton').checked = settings.showCronButton ?? defaults.showCronButton ?? false;
document.getElementById('appSettingsShowGitStatus').checked = settings.showGitStatus ?? defaults.showGitStatus ?? false;
document.getElementById('appSettingsGitStatusTree').checked = settings.gitStatusTree ?? defaults.gitStatusTree ?? true;
@@ -616,6 +618,9 @@ Object.assign(CodemanApp.prototype, {
document.getElementById('appSettingsGitFetchEnabled').checked = settings.gitFetchEnabled === true;
document.getElementById('appSettingsGitFetchIntervalSeconds').value = settings.gitFetchIntervalSeconds ?? 300;
document.getElementById('appSettingsShowEditHistory').checked = settings.showEditHistory ?? defaults.showEditHistory ?? false;
document.getElementById('appSettingsChatViewDefault').checked = settings.chatViewDefault === true;
// Absent means ON: the switch shows until this device turns it off.
document.getElementById('appSettingsShowChatViewSwitch').checked = settings.showChatViewSwitch === true;
// Gesture control lives in the Input section (alongside Local Echo / CJK Input)
// but is only available when the instance runs with CODEMAN_GESTURE=1 (server sets
// window.__codemanGestureAvailable). Hide just this item otherwise so the toggle
@@ -3165,6 +3170,7 @@ Object.assign(CodemanApp.prototype, {
spawnedTabsFollowParent: document.getElementById('appSettingsSpawnedTabsFollowParent').checked,
showSessionButton: document.getElementById('appSettingsShowSessionButton').checked,
showAwayDigestButton: document.getElementById('appSettingsShowAwayDigestButton').checked,
codexFilePreviewsEnabled: document.getElementById('appSettingsCodexFilePreviews').checked,
showCronButton: document.getElementById('appSettingsShowCronButton').checked,
showGitStatus: document.getElementById('appSettingsShowGitStatus').checked,
gitStatusTree: document.getElementById('appSettingsGitStatusTree').checked,
@@ -3179,6 +3185,8 @@ Object.assign(CodemanApp.prototype, {
Math.max(30, parseInt(document.getElementById('appSettingsGitFetchIntervalSeconds').value, 10) || 300)
),
showEditHistory: document.getElementById('appSettingsShowEditHistory').checked,
chatViewDefault: document.getElementById('appSettingsChatViewDefault').checked,
showChatViewSwitch: document.getElementById('appSettingsShowChatViewSwitch').checked,
gestureControlEnabled: document.getElementById('appSettingsGestureControl').checked,
subagentTrackingEnabled: document.getElementById('appSettingsSubagentTracking').checked,
subagentActiveTabOnly: document.getElementById('appSettingsSubagentActiveTabOnly').checked,
@@ -3409,6 +3417,7 @@ Object.assign(CodemanApp.prototype, {
this._updateTokensImmediate(); // Re-render token display (picks up showCost change)
this.applyMonitorVisibility();
this.renderApprovals?.(); // Approvals Inbox toggle (hide/show bell + drawer)
this._chatViewSync?.(); // Chat view default and the Chat / Terminal switch's visibility
this.renderProjectInsightsPanel(); // Re-render to apply visibility setting
this.updateSubagentWindowVisibility(); // Apply subagent window visibility setting
@@ -3485,6 +3494,8 @@ Object.assign(CodemanApp.prototype, {
// SettingsUpdateSchema (.strict()), so sending them would 400 the PUT.
showSessionButton: _ssb,
showAwayDigestButton: _adb,
// Codex files extras (app.js _codexFilePreviewsEnabled): per-device, absent from the .strict() schema.
codexFilePreviewsEnabled: _cfp,
showCronButton: _crb,
// Per-device bottom-bar indicator, absent from SettingsUpdateSchema (.strict()): it must not reach the PUT.
showGitStatus: _sgs,
@@ -3496,6 +3507,10 @@ Object.assign(CodemanApp.prototype, {
gitStatusTimeoutSeconds: _gst2,
// Per-device header button (edit-history-ui.js), likewise absent from the .strict() schema.
showEditHistory: _seh,
// Which view a session opens in (chat-view.js): per-device, absent from the .strict() schema.
chatViewDefault: _cvd,
// Whether the Chat / Terminal switch shows (chat-view.js): per-device, absent from the .strict() schema.
showChatViewSwitch: _scvs,
showTabDetachButton: _tdb,
showTabNewButton: _tnb,
// Detach Tiles: what a tile drag does is a property of this device's
@@ -4184,8 +4199,7 @@ Object.assign(CodemanApp.prototype, {
/** Keep the launch surfaces in sync with Settings mutations without a reload. */
_syncCliLaunchCatalog() {
if (!Array.isArray(this._cliList) || this._cliList.length === 0) return;
// /api/clis rows carry no capabilities, so keep the served catalog's `external`
// (isExternalCliSession() reads it). A new custom CLI has none and falls back to `kind`.
// /api/clis rows carry no capabilities, so retain them from the served catalog.
const previous = new Map(
(Array.isArray(window.__codemanCliCatalog) ? window.__codemanCliCatalog : []).map((cli) => [cli.id, cli])
);
@@ -4196,6 +4210,7 @@ Object.assign(CodemanApp.prototype, {
order: cli.order,
kind: cli.kind,
external: previous.get(cli.id)?.external,
transcript: previous.get(cli.id)?.transcript,
enabled: cli.enabled,
available: cli.kind === 'shell' || (cli.enabled && cli.installed),
}));
@@ -4848,6 +4863,15 @@ Object.assign(CodemanApp.prototype, {
awayDigestBtn.classList.toggle('btn-away-digest--hidden', !showAwayDigestButton);
}
// Codex files (Response files button, sidebar file tabs, Dock) — opt-in, hidden by default.
// Switching it off takes a docked preview back to floating. The Dock button follows the
// setting here too, not only when a preview opens: with a preview open, switching the setting
// off would otherwise leave a Dock button that does nothing, and on would show none.
this._syncResponseFilesButton?.();
const filePreviewDockBtn = document.getElementById('filePreviewDockBtn');
if (filePreviewDockBtn) filePreviewDockBtn.hidden = !this._codexFilePreviewsEnabled?.();
if (!this._codexFilePreviewsEnabled?.()) this._setFilePreviewDocked?.(false);
// Cron button (footer toolbar) — opt-in, hidden by default. Same marker pattern.
const showCronButton = settings.showCronButton ?? defaults.showCronButton ?? false;
const cronBtn = document.querySelector('.btn-cron');
@@ -5224,7 +5248,7 @@ Object.assign(CodemanApp.prototype, {
'terminalWheelLocalScrollback',
'historyReloadAction',
'autoCopySelection', 'copyStripMargin',
'showSessionButton', 'showAwayDigestButton', 'showCronButton', 'showGitStatus', 'gitStatusTree', 'gitStatusMaxRepos', 'gitStatusTimeoutSeconds', 'showEditHistory',
'showSessionButton', 'showAwayDigestButton', 'codexFilePreviewsEnabled', 'showCronButton', 'showGitStatus', 'gitStatusTree', 'gitStatusMaxRepos', 'gitStatusTimeoutSeconds', 'showEditHistory', 'chatViewDefault', 'showChatViewSwitch',
'showTabDetachButton',
'showTabNewButton',
'mobileOverviewEnabled',
+327
View File
@@ -4399,6 +4399,9 @@ html[data-tab-logos='off'] .home-sessions-harness {
overflow: hidden;
/* Anchor for the partial-history banner, which overlays rather than stacks. */
position: relative;
/* Keeps the chat view's layers (20 and 21) inside the terminal area, so the
narrow-width session sidebar drawer (z-index 12, mobile.css) stays above them. */
isolation: isolate;
}
/* Partial-history banner (#258).
@@ -11953,6 +11956,63 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
display: flex;
}
#filePreviewDockBtn {
display: none;
}
/* Hidden while the Codex files setting is off (panels-ui.js openFilePreview). */
#filePreviewDockBtn[hidden] {
display: none !important;
}
@media (min-width: 1180px) {
html {
--file-preview-dock-width: clamp(400px, 35vw, 620px);
}
body:has(.main:not(.tiles-active, .webview-active) > .terminal-wrap) #filePreviewDockBtn {
display: inline-flex;
}
.main:not(.tiles-active, .webview-active) > .file-preview-overlay.is-docked {
position: relative;
/* The floating overlay's 5100 would, with nothing above it making a stacking
context, put a docked pane over every modal (1000+) and the response viewer
(5000). Docked, it is page content beside the terminal. */
z-index: auto;
inset: auto;
flex: 0 0 var(--file-preview-dock-width);
min-width: 0;
min-height: 0;
align-items: stretch;
background: transparent;
backdrop-filter: none;
-webkit-backdrop-filter: none;
}
.main:not(.tiles-active, .webview-active) > .file-preview-overlay.is-docked .file-preview-window {
width: 100% !important;
height: 100% !important;
min-width: 0;
min-height: 0;
max-height: none;
border-radius: 0;
resize: none;
}
.main:not(.tiles-active, .webview-active) > .file-preview-overlay.is-docked :is(#filePreviewExpandBtn, #filePreviewResize) {
display: none;
}
#filePreviewDockBtn[aria-pressed='true'] {
color: var(--accent);
}
body:has(.main:not(.tiles-active, .webview-active) > .file-preview-overlay.is-docked.visible) .attachment-card-stack {
right: calc(var(--file-preview-dock-width) + 18px);
}
}
/* Folder grid (panels-ui.js openFolderGrid): one step BELOW the file preview, so a
tile opens its preview on top and closing that preview lands back on the grid. */
.folder-grid-overlay {
@@ -13628,6 +13688,24 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
transform: translateY(0);
}
#responseFilesBtn[hidden],
.btn-icon-header.btn-response-files--hidden,
.response-viewer[data-files-only='true'] :is(#responseViewerMore, #responseViewerCopyMarkdown) {
display: none !important;
}
/* Response files rows: buttons (no href for a middle-click to open), drawn as links. */
.response-files-list .response-files-item {
padding: 0;
border: 0;
background: none;
color: var(--accent);
font: inherit;
text-align: left;
text-decoration: underline;
cursor: pointer;
}
.response-viewer-header {
display: flex;
align-items: center;
@@ -14119,6 +14197,28 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
text-align: start;
vertical-align: top;
white-space: normal;
/* A cell wraps between words, so its column is never narrower than its longest word.
With the `anywhere` that cells inherit from .rv-text, the table counted every letter
as a break point when it sized its columns, and a column beside wide headers shrank
to one letter per line. */
overflow-wrap: break-word;
}
/* Inline code and links hold long tokens such as URLs, identifiers and hashes. Chromium
finds no break point inside one, since it never breaks after `/`. Under `break-word`
the longest token set its column's width and the whole table scrolled sideways, so
these tokens break anywhere. A linked path already does, through the `break-all` of
the a.rv-path rule above. CSS cannot tell an autolink from a link with a prose label,
so a label breaks anywhere too. The one exception is a path link's label
(.rv-path-link), which keeps breaking between words. */
.rv-table-wrap td :is(code, a:not(.rv-path-link)) {
overflow-wrap: anywhere;
}
/* Breaking anywhere lets a column shrink to one letter per line, so a cell holding such
a token gets a floor of about ten characters. */
.rv-table-wrap td:has(code, a:not(.rv-path-link)) {
min-width: 6em;
}
.rv-text th:last-child, .rv-text td:last-child,
@@ -19648,6 +19748,15 @@ html[data-session-list="sidebar"][data-sidebar="collapsed"] .btn-sidebar-toggle
top: 28px;
}
/* Pane A's split header is the first child of .terminal-wrap, so the chat layer and its switch start below it. */
.terminal-pane-a-header ~ .chat-view {
top: 28px;
}
.terminal-pane-a-header ~ .chat-view-toggle {
top: 36px;
}
.split-harness.run-mode-dot {
font-size: 13px;
}
@@ -24061,3 +24170,221 @@ html[data-header-stats='tiles'] .header-plan-usage:not(:has(.pu-row)) {
body.keyboard-visible .terminal-container .xterm-screen {
transform: translateY(calc(-1 * var(--kb-clip, 0px)));
}
/* ═══ Chat view (chat-view.js) ═══════════════════════════════════════════════
A session's conversation as its main view. It covers the terminal inside
.terminal-wrap; the terminal stays mounted and sized underneath, so switching
views never resizes the PTY. The message list carries .response-viewer-body,
so it renders exactly as the Response Viewer does. Theme tokens only. */
.chat-view {
position: absolute;
inset: 0;
z-index: 20;
display: flex;
flex-direction: column;
background: var(--bg-dark);
color: var(--text);
}
.chat-view[hidden],
.chat-view-toggle[hidden],
.chat-view-dialog[hidden],
.chat-view-status[hidden],
.chat-view-empty[hidden] {
display: none;
}
.chat-view-scroll {
flex: 1;
min-height: 0;
padding-top: 48px;
}
.chat-view-thread,
.chat-view-empty {
max-width: 820px;
margin: 0 auto;
}
.chat-view-empty {
color: var(--text-muted);
text-align: center;
padding-top: 15vh;
}
/* The notice is a paragraph directly inside the scroller, which carries the Response Viewer's
`.response-viewer-body > p` margin rule; this one outranks it so the notice stays centred. */
.chat-view-scroll > .chat-view-empty {
margin-left: auto;
margin-right: auto;
}
.chat-view-show-all {
margin-top: 8px;
padding: 0;
border: 0;
background: none;
color: var(--accent);
font: inherit;
font-size: 13px;
cursor: pointer;
}
.chat-view-show-all:hover {
text-decoration: underline;
}
.chat-view-dialog {
width: calc(100% - 32px);
max-width: 820px;
margin-inline: auto;
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 8px;
padding: 10px 12px;
border: 1px solid var(--border);
border-inline-start: 3px solid var(--yellow);
border-radius: 10px;
background: var(--bg-card);
font-size: 14px;
}
.chat-view-dialog-text {
flex: 1;
}
/* Sits in the message list, right under the last message. */
.chat-view-status {
display: flex;
align-items: flex-start;
gap: 8px;
max-width: 820px;
margin: 4px auto 0;
padding-inline-start: 4px;
color: var(--text-muted);
font-size: 13px;
line-height: 1.5;
}
.chat-view-status-body {
min-width: 0;
}
.chat-view-status-dot {
flex: none;
margin-top: 6px;
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--accent);
animation: chat-view-pulse 1.4s ease-in-out infinite;
}
@keyframes chat-view-pulse {
0%, 100% { opacity: 0.35; }
50% { opacity: 1; }
}
.chat-view-btn {
height: 32px;
padding: 0 12px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--bg-input);
color: var(--text);
font: inherit;
font-size: 13px;
line-height: 1;
cursor: pointer;
white-space: nowrap;
}
.chat-view-btn:hover {
background: var(--bg-hover);
}
.chat-view-btn-primary {
border-color: var(--accent);
background: var(--accent);
color: var(--bg-card);
font-weight: 600;
}
.chat-view-btn-primary:hover {
background: var(--accent);
filter: brightness(1.08);
}
.chat-view-btn:focus-visible,
.chat-view-toggle-btn:focus-visible,
.chat-view-show-all:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
/* Chat / Terminal switch: top right of the session area, above both views. */
.chat-view-toggle {
position: absolute;
top: 8px;
inset-inline-end: 18px;
z-index: 21;
display: flex;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--floating-bg);
overflow: hidden;
opacity: 0.8;
transition: opacity 0.15s ease;
}
.chat-view-toggle:hover,
.chat-view-toggle:focus-within,
.chat-view-toggle--over-chat {
opacity: 1;
}
.chat-view-toggle-btn {
padding: 4px 10px;
border: 0;
background: transparent;
color: var(--text-muted);
font: inherit;
font-size: 12px;
cursor: pointer;
}
.chat-view-toggle-btn[aria-pressed="true"] {
background: rgba(var(--accent-rgb), 0.16);
color: var(--text);
font-weight: 600;
}
/* The partial-history banner draws its Load full history and dismiss buttons at
the right end of the top row, where the Chat / Terminal switch sits. */
.terminal-wrap:has(> .chat-view-toggle:not([hidden])) .history-trunc-bar {
padding-inline-end: 170px;
}
/* The keyboard accessory bar's keys write straight into the pane, which the chat
view hides, so the bar stays hidden while the chat view shows. */
body.chat-view-showing .keyboard-accessory-bar.visible {
display: none;
}
/* On touch devices the CJK input field is fixed over the bottom of the chat view, and its text
goes into the pane, so it stays hidden while the chat view shows. !important beats the inline
display that app.js _updateCjkInputState sets. */
body.chat-view-showing.touch-device #cjkInput.cjk-input-visible {
display: none !important;
}
@media (prefers-reduced-motion: reduce) {
.chat-view-status-dot { animation: none; }
.chat-view-toggle { transition: none; }
}
/* The conversation takes focus only so keys never reach the hidden terminal; it draws no ring. */
.chat-view-scroll:focus {
outline: none;
}
+1
View File
@@ -207,6 +207,7 @@ Object.assign(CodemanApp.prototype, {
headerA.el.classList.add('terminal-pane-a-header');
this._splitHeaders = { a: headerA, b: headerB };
this._setFilePreviewDocked?.(false);
parent.insertBefore(container, wrap);
wrap.insertBefore(headerA.el, wrap.firstChild);
container.appendChild(wrap);
+2
View File
@@ -342,6 +342,8 @@
if (ev.type === 'keydown' && global.app?.shouldToggleSessionSidebarFromShortcut?.(ev)) {
return false;
}
// Alt+Shift+C flips the main view's chat view, so it must never type into this pane.
if (ev.type === 'keydown' && global.app?.shouldToggleChatViewFromShortcut?.(ev)) return false;
// Tile grid chords (focus, toggle): acted on by the capture handler, so
// they must never reach this tile's PTY. Every event type, and before
// the Shift+Enter branch below.
+197 -3
View File
@@ -501,6 +501,79 @@
global.codemanCurrentSkinIsLight = currentSkinIsLight;
})(window);
// Codex's sidebar owns its tab bar and file picker. Their labels are UI
// chrome, so the ordinary path linkifier must never open a suffix of one.
function codexSidebarFileRow(terminal, row) {
const buffer = terminal.buffer.active;
const top = buffer.viewportY;
if (row < top) return null;
const line = buffer.getLine(row);
if (!line?.getCell) return null;
for (let headerRow = top; headerRow <= Math.min(row, top + 2); headerRow++) {
const header = buffer.getLine(headerRow);
if (!header?.translateToString(true).trimEnd().endsWith('+')) continue;
for (let divider = terminal.cols - 2; divider >= 0; divider--) {
if (header.getCell(divider)?.getChars() !== '│') continue;
if (buffer.getLine(headerRow + 1)?.getCell?.(divider)?.getChars() !== '│') continue;
const tabs = header.translateToString(true, divider + 1).trim();
if (tabs !== '+' && !tabs.endsWith('×') && !/×\s+\+$/.test(tabs)) continue;
if (row !== headerRow && line.getCell(divider)?.getChars() !== '│') continue;
const entries = [];
const addEntry = (from, to) => {
while (from < to && !line.getCell(from)?.getChars().trim()) from++;
while (to > from && !line.getCell(to - 1)?.getChars().trim()) {
if (line.getCell(to - 1)?.getWidth() === 0) break;
to--;
}
const label = line.translateToString(false, from, to).trim();
if (label && previewsInFileViewer(label)) entries.push({ label, start: from, end: to });
};
if (row === headerRow) {
let from = divider + 1;
for (let col = from; col < terminal.cols; col++) {
if (line.getCell(col)?.getChars() !== '×') continue;
addEntry(from, col);
from = col + 1;
}
return { divider, entries };
}
// The chooser can also be opened with a keyboard shortcut. Its file
// rows follow the heading and use either the normal or selected marker.
let inChooser = false;
for (let scan = headerRow + 1; scan < row; scan++) {
const text = buffer.getLine(scan)?.translateToString(true, divider + 1).trim();
if (text === 'Open in sidebar') inChooser = true;
if (inChooser && /^(?:Markdown files|Files)\s+\d+$/.test(text)) {
const file = line.translateToString(true, divider + 1);
const marker = file.match(/^\s*(?:›\s+)?·\s+/);
if (!marker) return null;
const from = divider + 1 + marker[0].length;
let end = terminal.cols;
// On wider panels Codex appends a styled directory after two spaces.
const titleCell = line.getCell(from);
for (let col = from + 1; col + 1 < terminal.cols; col++) {
const firstSpace = line.getCell(col);
const secondSpace = line.getCell(col + 1);
if (!firstSpace || !secondSpace || firstSpace.getChars().trim() || secondSpace.getChars().trim()) continue;
if (
firstSpace.getFgColor?.() !== titleCell?.getFgColor?.() ||
firstSpace.getFgColorMode?.() !== titleCell?.getFgColorMode?.() ||
firstSpace.isDim?.() !== titleCell?.isDim?.() ||
line.translateToString(true, col).trim() === 'Project root'
) {
end = col;
break;
}
}
addEntry(from, end);
return { divider, entries };
}
}
}
}
return null;
}
Object.assign(CodemanApp.prototype, {
// ═══════════════════════════════════════════════════════════════
// Terminal Setup — xterm.js config and input handling
@@ -1334,6 +1407,13 @@ Object.assign(CodemanApp.prototype, {
return false;
}
// Chat / Terminal view toggle (default Alt+Shift+C, chat-view.js): the same trap, so the
// chord does not also type ESC C into the session. Only while the active session can show
// the chat view.
if (ev.type === 'keydown' && this.shouldToggleChatViewFromShortcut?.(ev)) {
return false;
}
// Ctrl+V / Cmd+V: intercept before xterm sends ^V to PTY.
// Route through our paste trap which handles both images and text.
if ((ev.ctrlKey || ev.metaKey) && ev.key === 'v' && ev.type === 'keydown') {
@@ -2514,6 +2594,20 @@ Object.assign(CodemanApp.prototype, {
}
}
// Sidebar file tabs belong to the Codex files setting (_codexFilePreviewsEnabled): off,
// the row keeps master's links and its clicks reach Codex untouched.
if (self._supportsCodexResponseFiles?.(getSessionId()) && self._codexFilePreviewsEnabled?.()) {
const sidebar = codexSidebarFileRow(terminal, bufferLineNumber - 1);
if (sidebar) {
const lineEnd = bufferLineNumber * terminal.cols + terminal.cols;
const sidebarStart = bufferLineNumber * terminal.cols + sidebar.divider + 2;
for (let i = links.length - 1; i >= 0; i--) {
const { start, end } = links[i].range;
if (start.y * terminal.cols + start.x <= lineEnd && end.y * terminal.cols + end.x >= sidebarStart) links.splice(i, 1);
}
}
}
if (links.length > 0) {
console.debug(
'[LinkProvider] Found links:',
@@ -2974,6 +3068,7 @@ Object.assign(CodemanApp.prototype, {
},
showWelcome() {
this._chatViewHide?.();
// Phones get the session overview instead of the welcome screen: on a small
// screen "which session is blocked on me" beats "how do I start one". The
// gate lives in mobile-overview.js; every other device falls through
@@ -6613,9 +6708,83 @@ Object.assign(CodemanApp.prototype, {
}
},
_codexTerminalLinkLabel(terminal, clientX, clientY) {
const pos = this._clientPointToCell(clientX, clientY, terminal);
const buffer = terminal.buffer?.active;
if (!pos || !buffer) return null;
const row = pos.row + buffer.viewportY;
const line = buffer.getLine(row - 1);
if (!line) return null;
const col = pos.col - 1;
const sidebar = codexSidebarFileRow(terminal, row - 1);
if (sidebar && col > sidebar.divider) {
// A sidebar tab click is taken only with the Codex files setting on; off, it reaches Codex.
if (!this._codexFilePreviewsEnabled?.()) return null;
const entry = sidebar.entries.find(({ start, end }) => col >= start && col < end);
return entry ? { ...entry, row, sidebar: true } : null;
}
if (line.isWrapped || buffer.getLine(row)?.isWrapped) return null;
const underlined = (index) => {
const cell = line.getCell(index);
return cell?.getWidth() === 0 || Boolean(cell?.isUnderline?.());
};
if (!underlined(col)) return null;
let start = col;
let end = col + 1;
while (start > 0 && underlined(start - 1)) start--;
while (end < terminal.cols && underlined(end)) end++;
const label = line.translateToString(false, start, end).trim();
return label && label.length <= 240 ? { label, row, start, end } : null;
},
/**
* The parsed conversation behind a Codex click. `context=full` makes the server read and parse
* the whole rollout, so the messages are kept for the session until its next turn: one entry
* (the last session asked about), reused only while the session is idle and its `lastSubmitAt`
* is unchanged. A working session's rollout is still growing, so it is never cached.
*/
async _codexResponseMessages(sessionId) {
const session = this.sessions?.get?.(sessionId);
const key = session?.status === 'idle' ? `${session.lastSubmitAt || 0}` : null;
const cached = this._codexResponseMessagesCache;
if (key && cached?.sessionId === sessionId && cached.key === key) return cached.messages;
const response = await fetch(`/api/sessions/${encodeURIComponent(sessionId)}/last-response?context=full`, {
signal: AbortSignal.timeout(3000),
});
if (!response.ok) return null;
const { data } = await response.json();
const messages = Array.isArray(data?.messages) ? data.messages : null;
this._codexResponseMessagesCache = key && messages ? { sessionId, key, messages } : null;
return messages;
},
async _openCodexTerminalResponseFile(terminal, sessionId, point, clicked, stillCurrent, forward) {
let path;
try {
const messages = await this._codexResponseMessages(sessionId);
if (!stillCurrent()) return;
if (messages) path = this._findCodexResponseFile(messages, clicked.label, sessionId, clicked.sidebar);
} catch {
// Preserve the native click if the transcript cannot be resolved.
}
if (!stillCurrent()) return;
const current = this._codexTerminalLinkLabel(terminal, point.clientX, point.clientY);
if (!current || current.label !== clicked.label || current.row !== clicked.row ||
current.start !== clicked.start || current.end !== clicked.end || current.sidebar !== clicked.sidebar) return;
if (path) await this._openResponseFile(path, sessionId);
else forward();
},
// Desktop counterpart of the touchend tap branch: hand-encode an SGR report
// for a plain left-click when the server strips mouse DECSETs (see
// _shouldReportMouseToCli). Every skip below is a click that already has
// _shouldReportMouseToCli). With the Codex files setting on, in a session whose
// CLI publishes a Codex rollout transcript, a plain click on an underlined label
// or on a sidebar file tab is first resolved against the
// conversation (_openCodexTerminalResponseFile): a single previewable file
// opens in the preview, anything else is forwarded as the SGR report below
// once the lookup settles. Every skip below is a click that already has
// a meaning elsewhere: synthetic/compat clicks after a touch tap (touchend
// reported already), modified clicks (shift keeps xterm's selection
// override), double/triple clicks (word/line selection), drag-selections,
@@ -6637,12 +6806,37 @@ Object.assign(CodemanApp.prototype, {
if (ev.shiftKey || ev.altKey || ev.ctrlKey || ev.metaKey) return;
const mode = terminal.modes?.mouseTrackingMode;
if (mode && mode !== 'none') return;
if (!this._shouldReportMouseToCli(target.sessionId)) return;
if (terminal.hasSelection?.()) return;
if (target.linkHovered ?? this._linkHovered) return; // link provider hover/leave callbacks (registerFilePathLinkProvider)
if (performance.now() <= (this._trustedTapMouseSuppressUntil || 0)) return;
if (!ev.target?.closest?.('.xterm-screen')) return;
this._sendSyntheticSgrTap(ev.clientX, ev.clientY, target);
const sessionId = target.sessionId || this.activeSessionId;
const { clientX, clientY } = ev;
const forward = () => {
if (this._shouldReportMouseToCli(sessionId)) this._sendSyntheticSgrTap(clientX, clientY, target);
};
this._codexTerminalLinkClicks ??= new WeakMap();
const click = Symbol();
this._codexTerminalLinkClicks.set(terminal, click);
// Behind the Codex files setting (owner decision for 1.52.1): off, every click goes on to
// Codex as before, an underlined label in the pane included.
const link =
this._codexFilePreviewsEnabled?.() &&
this._supportsCodexResponseFiles?.(sessionId) &&
this._codexTerminalLinkLabel(terminal, clientX, clientY);
if (!link) {
forward();
return;
}
// A second click (a double-click selecting the word) supersedes this one through the
// selection it leaves: it returns at `ev.detail !== 1` before it can replace `click`.
const stillCurrent = () =>
this._codexTerminalLinkClicks.get(terminal) === click &&
!terminal.hasSelection?.() &&
(target.sessionId ? terminal.element?.isConnected : this.activeSessionId === sessionId && this.terminal === terminal);
void this._openCodexTerminalResponseFile(terminal, sessionId, { clientX, clientY }, link, stillCurrent, forward)
.catch((error) => console.error('Unable to open Codex terminal response file:', error));
},
/**
+3
View File
@@ -415,6 +415,8 @@ Object.assign(CodemanApp.prototype, {
grid.rows = 0;
grid.focusedId = focus;
document.querySelector('.main')?.classList.add('tiles-active');
// Selecting a tile never reaches selectSession(), so the chat view is told here.
this._chatViewSync?.();
const section = this._tileGridSection();
this.hideWelcome();
// Mount every tile and lay the grid out BEFORE any tile connects, so each
@@ -504,6 +506,7 @@ Object.assign(CodemanApp.prototype, {
grid.zoomedId = null;
grid.autoZoom = false;
document.querySelector('.main')?.classList.remove('tiles-active');
this._chatViewSync?.();
const section = document.getElementById('tileGrid');
if (section) {
section.style.gridTemplateColumns = '';
+9 -9
View File
@@ -1,13 +1,13 @@
{
"version": "1.52.0",
"version": "1.52.1",
"highlights": [
"Closing a tab can no longer signal every process of your account",
"The Files panel loads one folder at a time (#848)",
"iPhone keyboard suggestions, dictation and hold-delete work in the terminal (#839, fixes #830)",
"Mac app: server tabs (#816)",
"An open tab after a restart no longer locks everyone out (#838)",
"Missing lines above the live screen can be fetched again (#815, fixes #814)",
"An agent that exited is seen again on tmux 3.8 (#840)",
"`codeman tui` takes its window size back (#853)"
"Claude sessions start when Codeman runs as root (#863)",
"Multi-user mode can sign people in through a reverse proxy (#854, experimental)",
"A chat view for Claude sessions (#859, first part, opt-in)",
"Codex sessions can open the files they link in Codeman's preview (#850, opt-in)",
"Prompt uploads take `.html` and `.htm` (#869, from #868)",
"Markdown table columns no longer shrink to one letter per line (#866)",
"The installer gets past sudo in a headless run (#863)",
"Mac app: a server tab can be dragged into the last place"
]
}
+16 -54
View File
@@ -9,10 +9,9 @@
import { FastifyInstance } from 'fastify';
import { ApiErrorCode, createErrorResponse } from '../../types.js';
import { HookEventSchema, isValidWorkingDir } from '../schemas.js';
import { HookEventSchema } from '../schemas.js';
import { sanitizeHookData, parseBody } from '../route-helpers.js';
import { persistDockerCaseClaudeSessionId } from '../../docker-hosts.js';
import { getDataDir } from '../../config/instance.js';
import { noteClaudeConversationReport, takeConversationMove } from '../claude-conversation-report.js';
import {
sessionWaits,
hooksAvailableForMode,
@@ -138,56 +137,19 @@ export function registerHookEventRoutes(
}
}
// Start transcript watching if transcript_path is provided and safe
if (data && 'transcript_path' in data) {
const transcriptPath = String(data.transcript_path);
if (transcriptPath && isValidWorkingDir(transcriptPath)) {
ctx.startTranscriptWatcher(sessionId, transcriptPath);
}
}
// Sync Claude's current conversation id. Interactive PTY mode never emits
// `session_id` on stdout, so hooks are the only reliable way to learn that
// the user ran `/clear` (which spins up a new conversation jsonl).
let conversationChanged = false;
if (data && typeof data.session_id === 'string' && data.session_id) {
const session = ctx.sessions.get(sessionId);
const prevClaudeSessionId = session?.claudeSessionId;
const prevChainLength = session?.claudeSessionChain.length ?? 0;
// FIRST-HAND: this payload came from the CLI process itself and reached us
// because the pane's own $CODEMAN_SESSION_ID addressed it. No cwd, no
// timestamp, nothing a sibling pane on the same folder could win — so the
// response viewer can stop guessing entirely (see
// resolveActiveClaudeSessionIdFromHistory).
session?.adoptClaudeSessionId(data.session_id, { firstHand: true });
if (event === 'prompt_submitted') {
// Repairs `lastSubmitAt` for a pane driven straight from tmux: it was
// bumped only by input that flowed through Codeman's own write path, so
// it read 0 forever for those panes and every consumer of "when did this
// pane last submit" silently degraded.
// The prompt text tells a person's prompt from the keep-alive's (prompt-cache-keepwarm.ts).
session?.markPromptSubmitted(typeof data.prompt === 'string' ? data.prompt : undefined);
}
// Persist when the conversation actually moved: `/clear` emits no
// completion event, so without this the successor id is lost on restart
// and recovery falls back to the launch conversation.
if (
session &&
(session.claudeSessionId !== prevClaudeSessionId || session.claudeSessionChain.length !== prevChainLength)
) {
conversationChanged = true;
ctx.persistSessionState(session);
}
// Docker sessions: keep the case's resume seed following the LIVE
// conversation (post-/clear id switches), so a container stop/reboot
// relaunch resumes the right transcript.
if (session?.docker && session.claudeSessionId && session.claudeSessionId !== prevClaudeSessionId) {
void persistDockerCaseClaudeSessionId(
getDataDir(),
session.docker.containerName,
session.claudeSessionId
).catch(() => {});
}
// Follow the conversation the pane reports (transcript watcher, conversation id, persistence).
// The statusline exporter reports the same two fields (status-telemetry-routes.ts).
noteClaudeConversationReport(ctx, sessionId, data);
// Whether the conversation moved since the previous prompt. The statusline can adopt a `/clear`
// successor before this hook arrives, so this hook's own report may show no change.
const conversationMoved = event === 'prompt_submitted' && takeConversationMove(ctx.sessions.get(sessionId));
if (event === 'prompt_submitted' && data && typeof data.session_id === 'string' && data.session_id) {
// Repairs `lastSubmitAt` for a pane driven straight from tmux: it was
// bumped only by input that flowed through Codeman's own write path, so
// it read 0 forever for those panes and every consumer of "when did this
// pane last submit" silently degraded.
// The prompt text tells a person's prompt from the keep-alive's (prompt-cache-keepwarm.ts).
ctx.sessions.get(sessionId)?.markPromptSubmitted(typeof data.prompt === 'string' ? data.prompt : undefined);
}
// Sanitize forwarded data: only include known safe fields, limit size
@@ -317,7 +279,7 @@ export function registerHookEventRoutes(
// left out too: the summary files a `stop` as a warning, which the Away digest lists under
// Needs Attention, and that turn is Codeman's own, not the agent's.
const summaryTracker = ctx.runSummaryTrackers.get(sessionId);
if (summaryTracker && !keepAliveReason && (event !== 'prompt_submitted' || conversationChanged)) {
if (summaryTracker && !keepAliveReason && (event !== 'prompt_submitted' || conversationMoved)) {
summaryTracker.recordHookEvent(event, safeData);
}
+6 -2
View File
@@ -1,7 +1,7 @@
/**
* @fileoverview Self-service identity routes (multi-user + single-user).
*
* - GET /api/me : who am I ({ username, role, mustChangePassword }).
* - GET /api/me : who am I ({ username, role, mustChangePassword, viaTrustedProxy }).
* Works in single-user mode too, returning the synthetic
* admin so the frontend has one "am I admin" code path.
* - POST /api/me/password : change my own password (verifies the current one,
@@ -35,13 +35,17 @@ export function registerMeRoutes(app: FastifyInstance, ctx: AuthPort): void {
}
const user = getAuthUser(req);
const record = await findUser(user.username);
// A trusted-proxy sign-in never used the Codeman password, so a pending one-time
// password must not open the forced change-password modal (admin-ui.js).
const viaTrustedProxy = !!user.viaTrustedProxy;
return {
success: true,
data: {
username: user.username,
role: user.role,
mustChangePassword: !!record?.mustChangePassword,
mustChangePassword: viaTrustedProxy ? false : !!record?.mustChangePassword,
multiUser: true,
viaTrustedProxy,
},
};
});
+97 -177
View File
@@ -230,6 +230,7 @@ import {
import { readDeepSeekLastResponse } from '../../deepseek-transcript.js';
import { appendClaudeCustomTitle } from '../../claude-session-title.js';
import { UPLOADS_DIR } from '../paste-image-gc.js';
import { ClaudeTranscriptReader } from '../claude-response-transcript.js';
// Path to linked-cases registry (same file used by case-routes resolveCasePath)
const LINKED_CASES_FILE = dataPath('linked-cases.json');
@@ -437,14 +438,32 @@ export function stripInkRedrawBloat(buffer: string): string {
/**
* The text half of the document allowlist: these are judged on their encoding
* (valid UTF-8, no NUL byte) rather than on a signature, since plain text has none.
*
* HTML belongs here beside Markdown: AI tools write specifications, reports and
* plans as either, and handing one to a session as context is the same job as a
* .md. It is stored to be read, never rendered on Codeman's origin: file-raw
* serves .html/.htm as octet-stream with nosniff (a download), and html-view
* refuses a page in a hidden directory such as `.codeman-uploads`.
*/
const TEXT_UPLOAD_EXTS = new Set(['.txt', '.md', '.csv', '.tsv', '.json', '.log', '.yaml', '.yml', '.xml']);
const TEXT_UPLOAD_EXTS = new Set([
'.txt',
'.md',
'.csv',
'.tsv',
'.json',
'.log',
'.yaml',
'.yml',
'.xml',
'.html',
'.htm',
]);
/**
* Documents a user hands an agent to read: the office formats plus the text
* family. Curated on purpose, never SUPPORTED_ATTACHMENT_EXTENSIONS or
* EDITABLE_EXTENSIONS, which carry sh/py/js/html; a prompt upload is a thing
* to read, not a thing to run or serve. Each is judged on its bytes by
* EDITABLE_EXTENSIONS, which carry sh/py/js; a prompt upload is a thing
* to read, not a thing to run. Each is judged on its bytes by
* imageMagicMatchesExt (signature, or UTF-8 without NUL for text). The browser
* keeps its own copies (test/upload-document-list-parity.test.ts pins them).
*/
@@ -1085,6 +1104,14 @@ function wakeableHost(host: RemoteHost): WakeableRemote {
};
}
/**
* The transcript path a `context=full` read started a session's watcher on, per session.
* A hook moves the watcher whenever its own path changes, but a session without working hooks
* never does, so after a `/clear` the read moves the watcher it started itself. A watcher whose
* path no longer matches the entry was moved by a hook, and from then on the read leaves it alone.
*/
const readStartedWatchers = new WeakMap<Session, string>();
export function registerSessionRoutes(
app: FastifyInstance,
ctx: SessionPort & EventPort & ConfigPort & InfraPort & AuthPort & TabLayoutPort & KeepWarmPort,
@@ -2936,160 +2963,9 @@ export function registerSessionRoutes(
return best.sessionId;
}
interface ClaudeResponseMessage {
kind: 'prompt' | 'response';
label: 'Prompt' | 'Response';
role: 'user' | 'assistant';
text: string;
timestamp?: string;
turn: number;
queued?: boolean;
}
interface ClaudeTranscriptEntry {
type?: string;
timestamp?: string;
isMeta?: boolean;
isSidechain?: boolean;
isCompactSummary?: boolean;
message?: { content?: unknown };
// A prompt typed while Claude is working is absorbed mid-turn and recorded
// ONLY here — the CLI never re-emits it as a `user` row. Every field stays
// optional and unvalidated: `queued_command` is not a documented CLI
// contract, so a missing/renamed field must mean "skip", which is also what
// the CLI's own non-human queue entries (commandMode 'task-notification',
// no `origin` key) require. Shape observed on Claude Code 2.1.220-2.1.251.
attachment?: {
type?: string;
prompt?: string;
commandMode?: string;
timestamp?: string;
origin?: { kind?: string };
};
}
function extractClaudeText(content: unknown, separator: string): string {
if (typeof content === 'string') return content;
if (!Array.isArray(content)) return '';
return content
.filter(
(block): block is { type: string; text: string } =>
!!block &&
typeof block === 'object' &&
(block as { type?: string }).type === 'text' &&
typeof (block as { text?: string }).text === 'string'
)
.map((block) => block.text)
.join(separator);
}
function isClaudeSyntheticUserMessage(entry: ClaudeTranscriptEntry, text: string): boolean {
if (entry.isMeta || entry.isCompactSummary) return true;
return /^(?:<local-command|<command-name>|<task-notification>|<system-reminder>|<teammate-message\b|Another Claude session sent a message:|Base directory for this skill:)/i.test(
text
);
}
/**
* Claude writes an append-only event log: tool results arrive as user rows,
* thinking/tool_use rows carry no text, and a prompt typed while the agent is
* working is only ever recorded as an `attachment/queued_command` row. But one
* assistant row IS one whole model message: measured across ~/.claude/projects
* (CLI 2.1.220-2.1.251) no assistant row carries more than one content block
* and no message id carries more than one text block, so there is nothing to
* reassemble. Emit one card per row and group them with `turn` instead of
* concatenating a human turn's replies into a single card (#169), which fused
* up to 74 distinct model messages into one card. Splitting is safe for
* markdown: no adjacent pair of assistant text rows in the corpus continues a
* table, a list, or an open code fence.
*/
function parseClaudeResponseTranscript(
content: string,
full: boolean
): { text: string; timestamp: string; messages?: ClaudeResponseMessage[] } {
let lastText = '';
let lastTimestamp = '';
const messages: ClaudeResponseMessage[] = [];
// #169's replay guards, kept: they now SKIP a duplicated row instead of
// concatenating it into the previous card.
const currentUserFragments = new Set<string>();
const currentAssistantFragments = new Set<string>();
// Turn 0 is reserved for anything emitted before the first human prompt.
let turn = 0;
const pushUserMessage = (text: string, timestamp: string | undefined, queued: boolean): void => {
// A run of consecutive human inputs (a mid-turn queued burst) is ONE turn,
// so the viewer renders it under one badge instead of one badge per line.
if (messages.at(-1)?.role !== 'user') turn += 1;
const message: ClaudeResponseMessage = { kind: 'prompt', label: 'Prompt', role: 'user', text, timestamp, turn };
if (queued) message.queued = true;
messages.push(message);
currentUserFragments.add(text);
currentAssistantFragments.clear();
};
for (const line of content.split('\n')) {
if (!line) continue;
let entry: ClaudeTranscriptEntry;
try {
entry = JSON.parse(line) as ClaudeTranscriptEntry;
} catch {
continue;
}
// Sidechains belong to agents/forks, not the main conversation. Meta user
// rows include repeated image dimensions and other UI-generated context.
if (entry.isSidechain) continue;
// A prompt typed while Claude is working is absorbed mid-turn and lives
// ONLY in an attachment row, so it was lost outright. `origin.kind` and
// `commandMode` separate the human's queue entries from the CLI's own:
// measured over 57 real transcripts on 2026-09-01, 322 queued_command rows
// split 163 `prompt`/`human` and 159 `task-notification`, and not one of
// those 159 carries an `origin` key. The 163 human rows become 162 user
// cards here — one is a verbatim repeat inside a still-unanswered user run
// and is collapsed by the dedup guard below — out of 353 user cards total.
if (entry.type === 'attachment') {
if (!full) continue;
const queued = entry.attachment;
if (!queued || queued.type !== 'queued_command') continue;
if (queued.origin?.kind !== 'human' || queued.commandMode !== 'prompt') continue;
const text = typeof queued.prompt === 'string' ? queued.prompt.trim() : '';
if (!text || isClaudeSyntheticUserMessage(entry, text)) continue;
if (currentUserFragments.has(text)) continue;
pushUserMessage(text, queued.timestamp || entry.timestamp, true);
continue;
}
if (entry.type === 'user') {
const text = extractClaudeText(entry.message?.content, '\n').trim();
// A tool_result block has no text block and naturally drops out here.
if (!text || isClaudeSyntheticUserMessage(entry, text)) continue;
if (!full) continue;
// Claude replays the initial user row while restoring a transcript, and
// a CLI that also wrote an absorbed prompt as a user row would double it.
// Both collapse here. The same prompt sent again AFTER a reply is a
// legitimate second turn, because that reply cleared the set.
if (currentUserFragments.has(text)) continue;
pushUserMessage(text, entry.timestamp, false);
continue;
}
if (entry.type !== 'assistant') continue;
const text = extractClaudeText(entry.message?.content, '\n\n').trim();
if (!text) continue;
lastText = text;
lastTimestamp = entry.timestamp || '';
if (!full) continue;
// Replayed snapshots repeat an identical text block inside one turn.
if (currentAssistantFragments.has(text)) continue;
messages.push({ kind: 'response', label: 'Response', role: 'assistant', text, timestamp: entry.timestamp, turn });
currentAssistantFragments.add(text);
currentUserFragments.clear();
}
return full ? { text: lastText, timestamp: lastTimestamp, messages } : { text: lastText, timestamp: lastTimestamp };
}
// Each transcript's parse so far, so a read parses only what was appended since the last one
// (claude-response-transcript.ts). The chat view reads on every `transcript:update`.
const claudeTranscripts = new ClaudeTranscriptReader();
/**
* Where THIS session's claude keeps its conversations: `<config dir>/projects` and
@@ -3145,33 +3021,59 @@ export function registerSessionRoutes(
}
}
// Where each conversation's transcript was last found, keyed by projects folder and id. The scan
// below stats one path per project folder, and the chat view reads on every reload, so a hit here
// costs one stat. A path that no longer names a file is dropped and the scan runs again.
const transcriptPathCache = new LRUMap<string, string>({ maxSize: 256 });
/** Locate a top-level Claude transcript, including recovered tmux sessions. */
async function findClaudeTranscript(
projectsDir: string,
conversationId: string,
codemanSessionId: string
): Promise<{ sessionId: string; path: string } | null> {
let projectDirs: import('node:fs').Dirent[];
try {
projectDirs = await fs.readdir(projectsDir, { withFileTypes: true });
} catch {
return null;
}
let projectDirs: import('node:fs').Dirent[] | null = null;
const readProjectDirs = async (): Promise<import('node:fs').Dirent[] | null> => {
if (projectDirs) return projectDirs;
try {
projectDirs = await fs.readdir(projectsDir, { withFileTypes: true });
} catch {
return null;
}
return projectDirs;
};
const safeIds = [...new Set([conversationId, codemanSessionId])].filter((value) => /^[a-zA-Z0-9._-]+$/.test(value));
for (const candidateId of safeIds) {
for (const projectDir of projectDirs) {
const cacheKey = `${projectsDir}\0${candidateId}`;
const cached = transcriptPathCache.get(cacheKey);
if (cached) {
const stat = await fs.stat(cached).catch(() => null);
if (stat?.isFile()) return { sessionId: candidateId, path: cached };
transcriptPathCache.delete(cacheKey);
}
const dirs = await readProjectDirs();
if (!dirs) return null;
for (const projectDir of dirs) {
if (!projectDir.isDirectory()) continue;
const jsonlPath = join(projectsDir, projectDir.name, `${candidateId}.jsonl`);
try {
const stat = await fs.stat(jsonlPath);
if (stat.isFile()) return { sessionId: candidateId, path: jsonlPath };
if (stat.isFile()) {
transcriptPathCache.set(cacheKey, jsonlPath);
return { sessionId: candidateId, path: jsonlPath };
}
} catch {
/* continue */
}
}
}
// The fallback below is never cached: it picks among files by a prefix, and a new one can
// change the answer.
const allProjectDirs = await readProjectDirs();
if (!allProjectDirs) return null;
// If mux-sessions.json was lost or stale, reconcileSessions() historically
// recovered `codeman-40568a29` as `restored-40568a29` and used the server cwd.
// The tmux name still carries the first eight UUID characters, which safely
@@ -3182,7 +3084,7 @@ export function registerSessionRoutes(
const candidates: Array<{ sessionId: string; path: string; mtimeMs: number }> = [];
const uuidPattern = /^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;
for (const projectDir of projectDirs) {
for (const projectDir of allProjectDirs) {
if (!projectDir.isDirectory()) continue;
const dirPath = join(projectsDir, projectDir.name);
let files: import('node:fs').Dirent[];
@@ -3340,17 +3242,35 @@ export function registerSessionRoutes(
}
}
try {
const content = await fs.readFile(transcript.path, 'utf8');
const parsed = parseClaudeResponseTranscript(content, wantsMessages);
if (context === 'turn') {
return {
text: parsed.text,
timestamp: parsed.timestamp,
messages: selectLastAnsweredTurn(parsed.messages ?? []),
};
// The chat view lives on the watcher's events (tool starts, new lines). A watcher normally
// starts at the session's first hook or statusline report, so a session the server picked up
// mid-turn (a restart) has none until one of those arrives. Start one from the file just found
// when none runs. A watcher this read started itself follows the conversation to its new file
// after a `/clear`, since no hook or statusline report moves it. A watcher that a hook or a
// statusline report started or moved is never touched: the reported path stays the authority.
// A remote session's file is not here. The reads above await, so the session may have been
// deleted or detached meanwhile, and a watcher started for it then would never be stopped.
if (context === 'full' && !session.remote && ctx.sessions.get(session.id) === session) {
const current = ctx.getTranscriptPath(session.id);
if (current === null) {
ctx.startTranscriptWatcher(session.id, transcript.path);
readStartedWatchers.set(session, transcript.path);
} else if (readStartedWatchers.get(session) === current) {
if (current !== transcript.path) {
ctx.startTranscriptWatcher(session.id, transcript.path);
readStartedWatchers.set(session, transcript.path);
}
} else {
readStartedWatchers.delete(session);
}
return parsed;
}
try {
const parsed = await claudeTranscripts.read(transcript.path);
if (context === 'turn') {
return { text: parsed.text, timestamp: parsed.timestamp, messages: selectLastAnsweredTurn(parsed.messages) };
}
return wantsMessages ? parsed : { text: parsed.text, timestamp: parsed.timestamp };
} catch {
return wantsMessages ? { text: '', timestamp: '', messages: [] } : { text: '', timestamp: '' };
}
@@ -6378,7 +6298,7 @@ export function registerSessionRoutes(
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Could not convert HEIC image to JPEG');
}
} else if (!imageMagicMatchesExt(imageBytes, ext)) {
// A foreign extension with no image MIME (a script, an HTML page, a video
// A foreign extension with no image MIME (a script, a binary, a video
// without its flag) was never going to be an image: say so, rather than
// the ".png" the default extension would name. Decided only HERE, after
// the sniff, so anything the image path ever accepted by its bytes (a
+15 -2
View File
@@ -29,10 +29,14 @@ import {
} from '../../usage-telemetry.js';
import { SessionPromptCache, SessionStatusTelemetry } from '../sse-events.js';
import { setLatestPlanUsage } from '../plan-usage-latest.js';
import type { SessionPort, EventPort, KeepWarmPort } from '../ports/index.js';
import type { SessionPort, EventPort, KeepWarmPort, ConfigPort } from '../ports/index.js';
import { noteClaudeConversationReport } from '../claude-conversation-report.js';
import { getCli } from '../../config/cli-registry/index.js';
export function registerStatusTelemetryRoutes(app: FastifyInstance, ctx: SessionPort & EventPort & KeepWarmPort): void {
export function registerStatusTelemetryRoutes(
app: FastifyInstance,
ctx: SessionPort & EventPort & KeepWarmPort & Pick<ConfigPort, 'startTranscriptWatcher'>
): void {
// Last broadcast telemetry signature per session — the statusline fires on
// every assistant message, so we only rebroadcast when the value changes.
const lastSig = new Map<string, string>();
@@ -65,6 +69,15 @@ export function registerStatusTelemetryRoutes(app: FastifyInstance, ctx: Session
session.noteReportedModel('statusline', payload?.model?.display_name);
}
// The conversation the pane runs. Claude Code runs the statusline about a second after a
// `/clear`, with the new conversation's id and transcript path, so the transcript watcher and
// the chat view move to it at once; a hook would report it only with the next prompt.
// The exporter can post out of order, so this report moves the session back to an earlier
// conversation only when the session's last move is more than a few seconds old (forwardOnly).
if (session && reportsStatusLine) {
noteClaudeConversationReport(ctx, sessionId, data, { forwardOnly: true });
}
// The context size drives auto-compact and auto-clear. A render without one (the exporter
// can post before the first API response) keeps the last report instead of wiping it.
const status = reportsStatusLine ? parseSessionStatus(payload) : null;
+5
View File
@@ -775,6 +775,11 @@ export const StatusTelemetrySchema = z.object({
sessionId: z.string().min(1).max(100),
data: z
.object({
// The conversation the pane runs, as every hook reports it (claude-conversation-report.ts).
// Claude Code runs the statusline again right after a `/clear`, so this is how the server
// learns of the new conversation before the next prompt. Bounded like any path.
session_id: z.string().max(200).nullish(),
transcript_path: z.string().max(4096).nullish(),
rate_limits: z
.object({
five_hour: RateLimitWindowSchema,
+17
View File
@@ -34,6 +34,7 @@
import { homedir } from 'node:os';
import { join } from 'node:path';
import { trustedProxySecretFilePath, trustedProxySecretFileRealPath } from '../config/trusted-proxy.js';
const SENSITIVE_PATTERNS: RegExp[] = [
// System account databases.
@@ -81,6 +82,9 @@ const SENSITIVE_PATTERNS: RegExp[] = [
// Named individually so the surrounding trees stay attachable (see above).
/\/\.claude\/\.credentials\.json$/,
/\/\.codeman[^/]*\/hook-secret$/,
// Trusted reverse-proxy secret under its documented name (the configured path, whatever
// its name, is checked separately in isSensitivePath).
/\/\.codeman[^/]*\/proxy-secret$/,
/\/\.codeman[^/]*\/users\.json$/,
// The data dir's `.env` is the CODEMAN_USERNAME/PASSWORD fallback `codeman attach`
// reads. Named here as well as in DOTENV_PATTERNS so `allowDotenv` (the File
@@ -153,6 +157,18 @@ const DOTENV_PATTERNS: RegExp[] = [/\/\.env$/, /\/\.env\./];
*/
const HOME_SENSITIVE_MEMBERS = ['.claude.json', '.claude/settings.json', '.claude/settings.local.json'];
/**
* Whether `absPath` is the configured trusted-proxy secret file
* (`CODEMAN_TRUSTED_PROXY_SECRET_FILE`, any name and location). The variable is removed
* from `process.env` once the secret is read, so the path comes from the trusted-proxy
* module, which keeps it, as configured and with symlinks resolved (resolved once).
*/
function isTrustedProxySecretFile(absPath: string): boolean {
const file = trustedProxySecretFilePath();
if (!file) return false;
return absPath === file || absPath === trustedProxySecretFileRealPath();
}
/**
* Returns true if the given ABSOLUTE, symlink-resolved path matches the
* sensitive-file blocklist and must not be served to the browser.
@@ -162,6 +178,7 @@ const HOME_SENSITIVE_MEMBERS = ['.claude.json', '.claude/settings.json', '.claud
export function isSensitivePath(absPath: string, opts: { allowDotenv?: boolean } = {}): boolean {
if (!opts.allowDotenv && DOTENV_PATTERNS.some((pattern) => pattern.test(absPath))) return true;
if (SENSITIVE_PATTERNS.some((pattern) => pattern.test(absPath))) return true;
if (isTrustedProxySecretFile(absPath)) return true;
const home = homedir();
return HOME_SENSITIVE_MEMBERS.some((member) => absPath === join(home, member));
}
+67 -2
View File
@@ -186,6 +186,7 @@ import {
import {
CleanupManager,
KeyedDebouncer,
KeyedThrottle,
StaleExpirationMap,
startEventLoopMonitor,
isSafePushEndpoint,
@@ -216,6 +217,7 @@ import {
sendLostWebviewFramePage,
} from './middleware/auth.js';
import { isMultiUserMode } from '../config/multiuser.js';
import { getTrustedProxyConfig, initTrustedProxySecret, trustedProxyConfigError } from '../config/trusted-proxy.js';
import { bootstrapInitialAdmin, findUser, hasUsers, resolveClaudeModeForUsername } from '../user-store.js';
import { installRouteErrorHandler } from './route-error-handler.js';
import { installEmptyApiPostParser } from './request-body-parser.js';
@@ -280,6 +282,8 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
// while capping growth of `sseClientsById` and blocking pathological inputs.
const SSE_CLIENT_ID_RE = /^[A-Za-z0-9_-]{8,64}$/;
const CODEX_USAGE_POLL_INTERVAL_MS = 5 * 60_000;
/** Longest a session's `transcript:update` broadcast waits behind the one before it. */
const TRANSCRIPT_UPDATE_THROTTLE_MS = 750;
// Copilot's quota is read over the network from GitHub, and a monthly figure moves slowly.
const COPILOT_USAGE_POLL_INTERVAL_MS = 10 * 60_000;
@@ -430,6 +434,13 @@ export class WebServer extends EventEmitter {
private respawnTimers: Map<string, { timer: NodeJS.Timeout; endAt: number; startedAt: number }> = new Map();
private runSummaryTrackers: Map<string, RunSummaryTracker> = new Map();
private transcriptWatchers: Map<string, TranscriptWatcher> = new Map();
/**
* Per-session throttle for the `transcript:update` broadcast: the first update in a quiet
* period goes out at once, and a burst after it collapses into one trailing event per
* TRANSCRIPT_UPDATE_THROTTLE_MS. A busy turn writes several lines a second, and every SSE
* client gets every broadcast.
*/
private readonly transcriptUpdateThrottle = new KeyedThrottle(TRANSCRIPT_UPDATE_THROTTLE_MS);
// Store session listener references for explicit cleanup (prevents memory leaks)
private sessionListenerRefs: Map<string, SessionListenerRefs> = new Map();
private scheduledRuns: Map<string, ScheduledRun> = new Map();
@@ -586,6 +597,7 @@ export class WebServer extends EventEmitter {
private hookSecretFailures: StaleExpirationMap<string, number> | null = null;
private userFailures: StaleExpirationMap<string, number> | null = null;
private userIpFailures: StaleExpirationMap<string, number> | null = null;
private proxySecretFailures: StaleExpirationMap<string, number> | null = null;
private pushStore: PushSubscriptionStore = new PushSubscriptionStore();
/** ntfy / Slack / Discord / generic webhook for the push events; config in webhook.json (0600). */
private webhookNotifier = new WebhookNotifier(() => readWebhookConfig(getDataDir()), webviewFetch);
@@ -1119,6 +1131,7 @@ export class WebServer extends EventEmitter {
this.hookSecretFailures = authState.hookSecretFailures;
this.userFailures = authState.userFailures;
this.userIpFailures = authState.userIpFailures;
this.proxySecretFailures = authState.proxySecretFailures;
}
// Bodyless API POSTs may arrive as empty chunked streams through a proxy.
@@ -1477,6 +1490,9 @@ export class WebServer extends EventEmitter {
* Creates a new watcher or updates an existing one with the new transcript path.
*/
private startTranscriptWatcher(sessionId: string, transcriptPath: string): void {
// Cleanup stops the watcher before it removes the session from the map. A hook, statusline
// report or full read that lands in between must not start a watcher that nothing would stop.
if (this.cleaningUp.has(sessionId)) return;
let watcher = this.transcriptWatchers.get(sessionId);
if (!watcher) {
@@ -1503,6 +1519,10 @@ export class WebServer extends EventEmitter {
this.broadcast(SseEvent.TranscriptToolStart, { sessionId, toolName, timestamp: Date.now() });
});
watcher.on('transcript:update', () => {
this.broadcastTranscriptUpdate(sessionId);
});
watcher.on('transcript:tool_end', (toolName: string, isError: boolean) => {
this.broadcast(SseEvent.TranscriptToolEnd, {
sessionId,
@@ -1530,8 +1550,9 @@ export class WebServer extends EventEmitter {
/**
* Read My Mind intent capture: fold one transcript user prompt into the
* case's intent profile (docs/readmymind-plan.md). Opt-in via
* `readMyMindEnabled` (default OFF) and claude-only; the mode gate is
* belt-and-braces since only hook-fed sessions have a transcript watcher.
* `readMyMindEnabled` (default OFF) and claude-only. The mode gate is needed:
* a transcript watcher is started by hook reports, statusline reports and a
* full transcript read (the chat view), not only for hook-fed Claude sessions.
*/
private async captureIntentPrompt(sessionId: string, text: string): Promise<void> {
const session = this.sessions.get(sessionId);
@@ -1548,10 +1569,18 @@ export class WebServer extends EventEmitter {
}
}
/** Broadcast `transcript:update` for a session, throttled (see `transcriptUpdateThrottle`). */
private broadcastTranscriptUpdate(sessionId: string): void {
this.transcriptUpdateThrottle.fire(sessionId, () => {
this.broadcast(SseEvent.TranscriptUpdate, { sessionId, timestamp: Date.now() });
});
}
/**
* Stop the transcript watcher for a session.
*/
private stopTranscriptWatcher(sessionId: string): void {
this.transcriptUpdateThrottle.cancelKey(sessionId);
const watcher = this.transcriptWatchers.get(sessionId);
if (watcher) {
watcher.removeAllListeners(); // Prevent memory leaks from attached listeners
@@ -2094,6 +2123,7 @@ export class WebServer extends EventEmitter {
order: entry.order,
kind: entry.kind,
external: entry.capabilities.external,
transcript: entry.capabilities.transcript,
enabled,
available: enabled && installed,
};
@@ -2160,6 +2190,17 @@ export class WebServer extends EventEmitter {
'</head>',
() => `<script>window.__codemanTranscriptPageKeys=${JSON.stringify(pageKeyClis)};</script>\n</head>`
);
// Which run modes the chat view can show (chat-view.js): the CLIs whose conversation Codeman
// reads from a Claude-format transcript, read off the `transcript` capability, never an id
// list here. Disabled entries are kept (`listClis`), like the wheel map below: disabling a CLI
// never ends its running sessions. Ids only, so JSON.stringify alone is enough.
const chatViewClis = listClis()
.filter((entry) => entry.capabilities.transcript === 'claude-jsonl')
.map((entry) => entry.id);
html = html.replace(
'</head>',
() => `<script>window.__codemanChatViewModes=${JSON.stringify(chatViewClis)};</script>\n</head>`
);
// Which run modes keep their PTY rows under a phone keyboard (inline renderers,
// the `keyboardHold` capability; `_keyboardHoldEligible` in terminal-ui.js). Same
// shape and reasoning as the page-key list above.
@@ -3470,6 +3511,14 @@ export class WebServer extends EventEmitter {
}
async start(): Promise<void> {
// Trusted reverse-proxy sign-in (opt-in): read the secret now, which also removes it
// and the file path from process.env, and refuse to start on a configured setup that
// can't be used, so a typo never falls back silently to password sign-in. Not skipped
// in test mode: the refusal itself is under test.
initTrustedProxySecret();
const proxyConfigError = trustedProxyConfigError(isMultiUserMode());
if (proxyConfigError) throw new Error(proxyConfigError);
// Multi-user first boot: create the initial admin from CODEMAN_USERNAME/PASSWORD
// if there are no users yet, else refuse to start (there would be no way in).
if (isMultiUserMode() && !this.testMode) {
@@ -3661,6 +3710,17 @@ export class WebServer extends EventEmitter {
}
}
// Trusted reverse-proxy sign-in (opt-in): say when it is on. An unusable setup never
// gets here (refused at the top of start()).
const proxyConfig = getTrustedProxyConfig(isMultiUserMode());
if (proxyConfig) {
console.log(
palette.muted(
`Trusted-proxy sign-in enabled (experimental): loopback requests with the proxy secret sign in as the account named in ${proxyConfig.userHeader}.`
)
);
}
// Set API URL for child processes (MCP server, spawned sessions)
const apiHost =
this.host === '0.0.0.0' || this.host === 'localhost' || this.host === '::1' ? '127.0.0.1' : this.host;
@@ -4856,6 +4916,7 @@ export class WebServer extends EventEmitter {
this.respawnTimers.clear();
this.runSummaryTrackers.clear();
this.transcriptWatchers.clear();
this.transcriptUpdateThrottle.dispose();
await this.editHistorySync.flushAll().catch((err) => {
console.warn('[EditHistory] Saving on shutdown failed:', getErrorMessage(err));
});
@@ -4886,6 +4947,10 @@ export class WebServer extends EventEmitter {
this.userIpFailures.dispose();
this.userIpFailures = null;
}
if (this.proxySecretFailures) {
this.proxySecretFailures.dispose();
this.proxySecretFailures = null;
}
this.activePlanOrchestrators.clear();
this.cleaningUp.clear();
this.killingSessions.clear();
+8 -2
View File
@@ -5,7 +5,7 @@
* and referenced by the frontend (`SSE_EVENTS` in `constants.js`).
* Both files MUST be kept in sync.
*
* 163 event constants organized by category:
* 165 event constants organized by category:
* - **Core** (1): init
* - **Transport** (1): sse:heartbeat
* - **Session lifecycle** (25): created, updated, deleted, terminal, idle, working, ...
@@ -21,7 +21,7 @@
* - **Scheduled** (6): created, updated, completed, stopped, log, deleted
* - **Cron jobs** (4): jobsChanged, jobDeleted, runCreated, runUpdated
* - **Teams** (4): created, updated, removed, taskUpdated
* - **Transcript** (4): complete, plan_mode, tool_start, tool_end
* - **Transcript** (5): complete, plan_mode, tool_start, tool_end, update
* - **Plan orchestration** (5): started, progress, subagent, completed, cancelled
* - **Tunnel** (7): started, stopped, progress, error, qrRotated, qrRegenerated, qrAuthUsed
* - **Image / attachments** (2): image:detected, attachment:detected
@@ -326,6 +326,11 @@ export const TranscriptPlanMode = 'transcript:plan_mode' as const;
export const TranscriptToolStart = 'transcript:tool_start' as const;
/** Tool invocation ended in transcript. */
export const TranscriptToolEnd = 'transcript:tool_end' as const;
/**
* New lines arrived in a session's transcript (throttled per session in server.ts). The chat
* view re-reads the conversation on it, so an answer shows while its turn is still running.
*/
export const TranscriptUpdate = 'transcript:update' as const;
// ─── Plan Orchestration ──────────────────────────────────────────────────────
@@ -643,6 +648,7 @@ export const SseEvent = {
TranscriptPlanMode,
TranscriptToolStart,
TranscriptToolEnd,
TranscriptUpdate,
// Plan orchestration
PlanStarted,
+11 -1
View File
@@ -45,6 +45,7 @@
import { createHash } from 'node:crypto';
import { WEBVIEW_PROXY_PREFIX } from '../config/webview-limits.js';
import { stripBasePath } from '../config/base-path.js';
import { resolveTrustedProxyUserHeader } from '../config/trusted-proxy.js';
/** Headers that are per-connection and must never be relayed in either direction. */
const HOP_BY_HOP = new Set([
@@ -76,6 +77,12 @@ const DROP_REQUEST_HEADERS = new Set([
'origin',
'referer',
'x-codeman-hook-secret',
// Trusted reverse-proxy sign-in headers. The auth middleware already deletes them from
// every request (takeTrustedProxyHeaders); listed here too so the relay never forwards
// them even if that ever changes. A custom username header name
// (CODEMAN_TRUSTED_PROXY_USER_HEADER) is added per request in buildUpstreamRequestHeaders.
'x-codeman-proxy-secret',
'x-codeman-user',
]);
/** Response headers dropped on the way back to the browser. */
@@ -409,10 +416,13 @@ export function buildUpstreamRequestHeaders(
}
): Record<string, string> {
const headers: Record<string, string> = {};
// The configured trusted-proxy username header (the default name is already in
// DROP_REQUEST_HEADERS). Only ever a name that passed validation.
const proxyUserHeader = resolveTrustedProxyUserHeader();
for (const [key, value] of Object.entries(incoming)) {
const lower = key.toLowerCase();
if (DROP_REQUEST_HEADERS.has(lower)) continue;
if (DROP_REQUEST_HEADERS.has(lower) || lower === proxyUserHeader) continue;
if (value === undefined) continue;
headers[lower] = Array.isArray(value) ? value.join(', ') : value;
}
+47
View File
@@ -0,0 +1,47 @@
/**
* @fileoverview The chat view's strings in Chinese (zh-CN), run through the real translator.
*
* chat-view.js looks its strings up itself (`_chatViewT`), because i18n.js skips the
* `data-i18n-skip` conversation. Pinned here:
* - each string the chat view draws reads in Chinese, and the numbers in it survive;
* - the setting that shows or hides the Chat / Terminal switch reads in Chinese.
*
* Port: N/A.
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { JSDOM } from 'jsdom';
import { afterAll, describe, expect, it } from 'vitest';
const I18N = readFileSync(resolve(import.meta.dirname, '../src/web/public/i18n.js'), 'utf8');
type Api = { t(s: string, vars?: Record<string, string>): string; configure(o: Record<string, string>): void };
const dom = new JSDOM('<!doctype html><html><body></body></html>', {
runScripts: 'outside-only',
url: 'http://localhost/',
});
vm.runInContext(I18N, dom.getInternalVMContext(), { filename: 'i18n.js' });
const api = (dom.window as unknown as { CodemanI18n: Api }).CodemanI18n;
api.configure({ language: 'zh-CN' });
afterAll(() => dom.window.close());
describe('the chat view in zh-CN', () => {
it('translates the fold button, the empty thread and the dialog notice', () => {
expect(api.t('No messages yet.')).toBe('还没有消息。');
expect(api.t('Show all (3 lines)')).toBe('显示全部(3 行)');
expect(api.t('Claude is waiting for your answer in the terminal.')).toBe('Claude 正在终端中等待你的回答。');
// The notification drawer shows the same sentence without the period.
expect(api.t('Codex is waiting for your answer in the terminal')).toBe('Codex 正在终端中等待你的回答');
});
it('translates the Chat / Terminal switch setting', () => {
expect(api.t('Show the Chat / Terminal switch')).toBe('显示聊天 / 终端开关');
expect(
api.t(
'Show the Chat / Terminal switch at the top right of a Claude session. Alt+Shift+C switches views without it. Not on phones.'
)
).toBe('在 Claude 会话右上角显示聊天 / 终端开关。没有它时,Alt+Shift+C 也能切换视图。手机上不可用。');
});
});
+824
View File
@@ -0,0 +1,824 @@
/**
* @fileoverview The chat view (chat-view.js): a session's conversation as its main view.
*
* What is pinned, and why:
* - The pure helpers (`CodemanChatView` in constants.js): keep-warm turns are never drawn, a
* growing thread appends instead of redrawing, and long prompts fold.
* - Which sessions can show it comes from `window.__codemanChatViewModes` (the transcript
* capability), and remote and adopted sessions never do.
* - The chat view covers the terminal without removing it, and a session remembers its view.
* A focus that lands on the hidden terminal moves to the conversation.
* - A dialog in the pane shows the "waiting in the terminal" notice.
* - Codeman's own keep-alive turn shows no status line.
* - The toggle chord is swallowed by the xterm key handler, so it never types into the session.
*
* The real constants.js and chat-view.js run inside a JSDOM window.
*
* Port: none.
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { JSDOM } from 'jsdom';
import { describe, expect, it, vi } from 'vitest';
const read = (name: string) => readFileSync(resolve(import.meta.dirname, '../src/web/public', name), 'utf8');
type Msg = { role: string; text: string; turn?: number; keepAlive?: boolean; queued?: boolean };
interface ChatHelpers {
visibleMessages: (m: unknown) => Msg[];
messageKey: (m: Msg) => string;
renderPlan: (a: string[], b: string[]) => { mode: string; from?: number };
promptFold: (t: string) => { folded: boolean; head: string; totalLines: number };
promptText: (t: string) => string;
elapsed: (ms: number) => string;
}
function loadHelpers(): ChatHelpers {
const context = vm.createContext({ window: {}, globalThis: {} });
vm.runInContext(read('constants.js'), context, { filename: 'constants.js' });
return (context.window as { CodemanChatView: ChatHelpers }).CodemanChatView;
}
describe('CodemanChatView helpers', () => {
const h = loadHelpers();
it('leaves out keep-warm turns and messages without text', () => {
const shown = h.visibleMessages([
{ role: 'user', text: 'Fix it', turn: 1 },
{ role: 'assistant', text: 'Done.', turn: 1 },
{ role: 'user', text: 'nudge', turn: 2, keepAlive: true },
{ role: 'assistant', text: 'ok', turn: 2, keepAlive: true },
{ role: 'assistant', text: ' ', turn: 3 },
null,
]);
expect(shown.map((m) => m.text)).toEqual(['Fix it', 'Done.']);
expect(h.visibleMessages(undefined)).toEqual([]);
});
it('appends when the thread only grew, and redraws when it changed', () => {
expect(h.renderPlan(['a', 'b'], ['a', 'b'])).toEqual({ mode: 'none' });
expect(h.renderPlan(['a', 'b'], ['a', 'b', 'c'])).toEqual({ mode: 'append', from: 2 });
expect(h.renderPlan([], ['a'])).toEqual({ mode: 'append', from: 0 });
expect(h.renderPlan(['a', 'b'], ['a', 'x', 'c'])).toEqual({ mode: 'replace' });
expect(h.renderPlan(['a', 'b'], ['a'])).toEqual({ mode: 'replace' });
});
it('keys a message by role, turn and text', () => {
const a = h.messageKey({ role: 'user', text: 'hi', turn: 1 });
expect(h.messageKey({ role: 'user', text: 'hi', turn: 1 })).toBe(a);
expect(h.messageKey({ role: 'user', text: 'hi', turn: 2 })).not.toBe(a);
expect(h.messageKey({ role: 'assistant', text: 'hi', turn: 1 })).not.toBe(a);
});
it('folds a prompt over 12 lines to its first 6, and one enormous line too', () => {
const short = Array.from({ length: 12 }, (_, i) => `line ${i}`).join('\n');
expect(h.promptFold(short).folded).toBe(false);
const long = Array.from({ length: 30 }, (_, i) => `line ${i}`).join('\n');
const fold = h.promptFold(long);
expect(fold.folded).toBe(true);
expect(fold.totalLines).toBe(30);
expect(fold.head.split('\n')).toHaveLength(6);
const wide = h.promptFold('x'.repeat(5000));
expect(wide.folded).toBe(true);
expect(wide.head.length).toBeLessThanOrEqual(801);
});
it("unwraps Claude Code's pasted_content tag so a pasted prompt keeps its lines", () => {
expect(h.promptText('<pasted_content id="a9da">\nline 1\nline 2\n</pasted_content>')).toBe('line 1\nline 2');
expect(h.promptText('before <pasted_content>x</pasted_content> after')).toBe('before x after');
// Claude Code 2.1.331 repeats the id on the closing tag.
expect(h.promptText('<pasted_content id="a9da">\nA\nB\n</pasted_content id="a9da">')).toBe('A\nB');
expect(h.promptText('a <pasted_content id="1"> left open')).toBe('a <pasted_content id="1"> left open');
expect(h.promptText('plain')).toBe('plain');
});
it('formats the running time like the CLI', () => {
expect(h.elapsed(0)).toBe('0s');
expect(h.elapsed(14_900)).toBe('14s');
expect(h.elapsed(125_000)).toBe('2m 05s');
expect(h.elapsed(3_780_000)).toBe('1h 03m');
expect(h.elapsed(-5)).toBe('0s');
});
});
// ─── The module in a DOM ──────────────────────────────────────────────────────
type Api = ReturnType<typeof vi.fn>;
interface ChatApp {
activeSessionId: string | null;
sessions: Map<string, Record<string, unknown>>;
pendingHooks: Map<string, Set<string>>;
_api: Api;
_apiJson: Api;
showToast: Api;
_sendInputAsync: Api;
loadAppSettingsFromStorage: () => Record<string, unknown>;
_chatViewReload: () => void;
onChatViewTurnEvent: (id: string, idle: boolean, keepAlive?: boolean) => void;
chatViewEligible: (id: string) => boolean;
chatViewModeFor: (id: string) => string;
setChatViewMode: (id: string, mode: string) => void;
onChatViewActiveSession: (id: string) => void;
onChatViewHooksChanged: (id: string) => void;
_onChatViewTranscriptUpdate: (d: { sessionId: string }) => void;
_chatViewFetch: () => Promise<void>;
_chatViewForget: (id: string) => void;
_chatViewPruneModes: (ids: Set<string>) => void;
_chatViewHide: () => void;
_chatViewRenderStatus: () => void;
shouldToggleChatViewFromShortcut: (e: Partial<KeyboardEvent>) => boolean;
_chatView: {
root: HTMLElement;
toggle: HTMLElement;
thread: HTMLElement;
dialog: HTMLElement;
scroller: HTMLElement;
status: HTMLElement;
statusText: HTMLElement;
statusTimer: unknown;
};
}
function loadModule(opts: { messages?: Msg[][] } = {}) {
const dom = new JSDOM(
`<!doctype html><body><input type="file" id="attachFileInput" accept="image/*,.pdf">
<div class="terminal-wrap"><div id="terminalContainer"></div><textarea id="cjkInput"></textarea></div></body>`,
{ runScripts: 'outside-only', pretendToBeVisual: true, url: 'http://localhost/' }
);
const win = dom.window as unknown as Window & { eval: (s: string) => unknown; [k: string]: unknown };
win.__codemanChatViewModes = ['claude'];
// The window has a Date of its own. Tie it to the test's clock, so vi.setSystemTime reaches
// the module's elapsed times.
(win.Date as DateConstructor).now = () => Date.now();
win.eval('class CodemanApp {}; window.CodemanApp = CodemanApp;');
win.eval(read('constants.js'));
win.eval(read('chat-view.js'));
const proto = (win.CodemanApp as { prototype: object }).prototype;
const pages = [...(opts.messages ?? [[]])];
const app = Object.assign(Object.create(proto), {
activeSessionId: 's1',
sessions: new Map<string, Record<string, unknown>>([
['s1', { id: 's1', mode: 'claude', status: 'idle' }],
['s2', { id: 's2', mode: 'claude', status: 'idle', remote: { hostId: 'h' } }],
['s3', { id: 's3', mode: 'claude', status: 'idle', adopt: { target: 'x' } }],
['s4', { id: 's4', mode: 'codex', status: 'idle' }],
['s5', { id: 's5', mode: 'claude', status: 'idle', docker: { caseName: 'box' } }],
]),
pendingHooks: new Map<string, Set<string>>(),
loadAppSettingsFromStorage: () => ({}),
_getResponseViewerAgentLabel: () => 'Claude',
_buildResponseViewerMessage: (text: string, role: string, _label: string, meta?: { continuation?: boolean }) => {
const div = win.document.createElement('div');
div.className = `rv-message rv-msg-${role}`;
if (meta?.continuation) div.classList.add('rv-msg-cont');
const body = win.document.createElement('div');
body.className = 'rv-text';
body.textContent = text;
div.appendChild(body);
return div;
},
_bindResponseViewerInteractions: () => {},
_api: vi.fn(async () => ({ ok: true, status: 200, json: async () => ({ success: true }) })),
_apiJson: vi.fn(async () => ({ messages: pages.length > 1 ? pages.shift() : pages[0] })),
showToast: vi.fn(),
_sendInputAsync: vi.fn(),
terminal: { focus: vi.fn() },
}) as ChatApp;
return { dom, win, app };
}
const settle = () => new Promise((r) => setTimeout(r, 0));
describe('chat view module', () => {
it('is offered only for sessions whose run mode has a Claude transcript, local or Docker', () => {
const { app } = loadModule();
expect(app.chatViewEligible('s1')).toBe(true);
expect(app.chatViewEligible('s5')).toBe(true); // Docker
expect(app.chatViewEligible('s2')).toBe(false); // remote
expect(app.chatViewEligible('s3')).toBe(false); // adopted
expect(app.chatViewEligible('s4')).toBe(false); // not in __codemanChatViewModes
expect(app.chatViewEligible('missing')).toBe(false);
});
it('is not offered on a phone, even one turned to landscape', () => {
const { win, app } = loadModule();
// A phone in landscape is wider than the phone breakpoint, so its width says "desktop".
win.MobileDetection = { isHandheldDevice: () => true, getDeviceType: () => 'desktop' };
expect(app.chatViewEligible('s1')).toBe(false);
win.MobileDetection = { isHandheldDevice: () => false, getDeviceType: () => 'desktop' };
expect(app.chatViewEligible('s1')).toBe(true);
});
it('opens in Chat when the device setting says so, unless the session remembers Terminal', () => {
const { win, app } = loadModule();
app.loadAppSettingsFromStorage = () => ({ chatViewDefault: true });
expect(app.chatViewModeFor('s1')).toBe('chat');
win.localStorage.setItem('codeman:chatViewModes', JSON.stringify({ s1: 'terminal' }));
expect(app.chatViewModeFor('s1')).toBe('terminal');
});
it('marks the body while Chat shows, so the keyboard accessory bar stays hidden', () => {
const { win, app } = loadModule();
app.onChatViewActiveSession('s1');
expect(win.document.body.classList.contains('chat-view-showing')).toBe(false);
app.setChatViewMode('s1', 'chat');
expect(win.document.body.classList.contains('chat-view-showing')).toBe(true);
app.setChatViewMode('s1', 'terminal');
expect(win.document.body.classList.contains('chat-view-showing')).toBe(false);
});
it('moves a focus that lands in the hidden terminal to the conversation', () => {
const { win, app } = loadModule();
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
const inner = win.document.createElement('textarea');
win.document.getElementById('terminalContainer')!.appendChild(inner);
inner.focus();
expect(win.document.activeElement).toBe(app._chatView.scroller);
});
it('moves a focus that lands on the CJK input field to the conversation', () => {
// With CJK input on, terminal.focus() lands on #cjkInput, outside #terminalContainer.
const { win, app } = loadModule();
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
(win.document.getElementById('cjkInput') as HTMLTextAreaElement).focus();
expect(win.document.activeElement).toBe(app._chatView.scroller);
});
it('keeps a dropped file from opening in the browser while Chat shows', () => {
const { win, app } = loadModule();
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
// The Chat / Terminal switch is a sibling of the chat view root, so it needs the guard too.
for (const target of [app._chatView.root, app._chatView.toggle]) {
for (const type of ['dragover', 'drop']) {
const ev = new win.Event(type, { bubbles: true, cancelable: true });
target.dispatchEvent(ev);
expect(ev.defaultPrevented).toBe(true);
}
}
});
it('hides the chat view, its switch and the body mark when the home screen shows', () => {
const { win, app } = loadModule();
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
expect(app._chatView.root.hidden).toBe(false);
app._chatViewHide();
expect(app._chatView.root.hidden).toBe(true);
expect(app._chatView.toggle.hidden).toBe(true);
expect(win.document.body.classList.contains('chat-view-showing')).toBe(false);
});
it('starts in Terminal, covers the terminal once Chat is picked, and remembers the choice', async () => {
const { win, app } = loadModule({ messages: [[{ role: 'user', text: 'Hi', turn: 1 }]] });
app.onChatViewActiveSession('s1');
expect(app.chatViewModeFor('s1')).toBe('terminal');
// The switch is off by default (no showChatViewSwitch on this device); its own tests are below.
expect(app._chatView.toggle.hidden).toBe(true);
expect(app._chatView.root.hidden).toBe(true);
app.setChatViewMode('s1', 'chat');
await settle();
expect(app._chatView.root.hidden).toBe(false);
// The terminal stays in the DOM underneath: nothing is removed or resized.
expect(win.document.getElementById('terminalContainer')).not.toBeNull();
expect(win.document.querySelector('.terminal-wrap')!.classList.contains('chat-view-active')).toBe(true);
expect(app._apiJson).toHaveBeenCalledWith('/api/sessions/s1/last-response?context=full');
expect(JSON.parse(win.localStorage.getItem('codeman:chatViewModes')!)).toEqual({ s1: 'chat' });
// The per-session turn state goes with the session too.
const state = app as unknown as Record<string, Map<string, unknown> | Set<string>>;
state._chatViewTurnStarts = new Map([['s1', 1]]);
state._chatViewIdleSeen = new Set(['s1']);
state._chatViewKeepAliveTurns = new Set(['s1']);
// A detach sends the same event as a delete, so the view choice outlives it.
app._chatViewForget('s1');
expect(JSON.parse(win.localStorage.getItem('codeman:chatViewModes')!)).toEqual({ s1: 'chat' });
for (const key of ['_chatViewTurnStarts', '_chatViewIdleSeen', '_chatViewKeepAliveTurns']) {
expect(state[key].has('s1')).toBe(false);
}
});
it("drops the view choices of sessions that are not in the init's session list", () => {
const { app, win } = loadModule();
win.localStorage.setItem('codeman:chatViewModes', JSON.stringify({ s1: 'chat', gone: 'terminal' }));
app.setChatViewMode('s1', 'chat');
app.setChatViewMode('gone', 'terminal');
app._chatViewPruneModes(new Set(['s1', 's2']));
expect(JSON.parse(win.localStorage.getItem('codeman:chatViewModes')!)).toEqual({ s1: 'chat' });
win.localStorage.clear();
expect(app.chatViewModeFor('gone')).toBe('terminal');
expect(app.chatViewModeFor('s1')).toBe('chat');
});
it('prunes the view choices from handleInit in app.js', () => {
const appJs = read('app.js');
const start = appJs.indexOf(' handleInit(data) {');
const init = appJs.slice(start, appJs.indexOf('\n }\n', start));
expect(init).toContain('this._chatViewPruneModes?.(new Set(data.sessions.map((s) => s.id)));');
});
it('hides the Chat / Terminal switch when the device has no showChatViewSwitch setting (off by default)', () => {
const { app } = loadModule();
app.loadAppSettingsFromStorage = () => ({});
app.onChatViewActiveSession('s1');
expect(app._chatView.toggle.hidden).toBe(true);
app.loadAppSettingsFromStorage = () => ({ showChatViewSwitch: true });
app._chatViewSync();
expect(app._chatView.toggle.hidden).toBe(false);
});
it('hides the switch when the setting is off, while Alt+Shift+C still switches views', async () => {
const { win, app } = loadModule({ messages: [[{ role: 'user', text: 'Hi', turn: 1 }]] });
app.loadAppSettingsFromStorage = () => ({ showChatViewSwitch: false });
app.onChatViewActiveSession('s1');
expect(app._chatView.toggle.hidden).toBe(true);
app.toggleChatView();
await settle();
expect(app.chatViewModeFor('s1')).toBe('chat');
expect(app._chatView.root.hidden).toBe(false);
expect(app._chatView.toggle.hidden).toBe(true);
expect(win.document.body.classList.contains('chat-view-showing')).toBe(true);
app.toggleChatView();
expect(app.chatViewModeFor('s1')).toBe('terminal');
expect(app._chatView.root.hidden).toBe(true);
// A settings save re-syncs: turning the setting back on shows the switch again.
app.loadAppSettingsFromStorage = () => ({ showChatViewSwitch: true });
app._chatViewSync();
expect(app._chatView.toggle.hidden).toBe(false);
});
it('hides the toggle for a session that cannot show the chat view', () => {
const { app } = loadModule();
app.onChatViewActiveSession('s1');
app.activeSessionId = 's4';
app.onChatViewActiveSession('s4');
expect(app._chatView.toggle.hidden).toBe(true);
expect(app._chatView.root.hidden).toBe(true);
});
it('draws the conversation without keep-warm turns, folds long prompts and appends new messages', async () => {
const long = Array.from({ length: 20 }, (_, i) => `log ${i}`).join('\n');
const first: Msg[] = [
{ role: 'user', text: long, turn: 1 },
{ role: 'assistant', text: 'Looked at it.', turn: 1 },
{ role: 'assistant', text: 'Checked the tests too.', turn: 1 },
{ role: 'user', text: 'keep-warm nudge', turn: 2, keepAlive: true },
{ role: 'assistant', text: 'keep-warm reply', turn: 2, keepAlive: true },
];
const second: Msg[] = [...first, { role: 'user', text: 'Next', turn: 3 }];
const { app } = loadModule({ messages: [first, second] });
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
await settle();
const nodes = Array.from(app._chatView.thread.children) as HTMLElement[];
expect(nodes).toHaveLength(3);
expect(nodes[0].querySelector('.chat-view-show-all')!.textContent).toBe('Show all (20 lines)');
expect(nodes[0].textContent).not.toContain('log 10');
expect(app._chatView.thread.textContent).not.toContain('keep-warm');
// One badge per speaker per turn: Claude's second message in the turn continues the first.
expect(nodes[1].classList.contains('rv-msg-cont')).toBe(false);
expect(nodes[2].classList.contains('rv-msg-cont')).toBe(true);
await app._chatViewFetch();
const after = Array.from(app._chatView.thread.children);
expect(after).toHaveLength(4);
expect(after[0]).toBe(nodes[0]); // appended, not redrawn
(nodes[0].querySelector('.chat-view-show-all') as HTMLButtonElement).click();
expect(app._chatView.thread.children[0].textContent).toContain('log 19');
});
it('puts the Working line right under the last message, inside the scrolling list', () => {
const { app } = loadModule();
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
const view = app._chatView as unknown as { status: HTMLElement; thread: HTMLElement; scroller: HTMLElement };
expect(view.status.parentElement).toBe(view.scroller);
expect(view.thread.nextElementSibling).toBe(view.status);
});
it('counts a turn already running when the page loaded from the last Enter, not from the page load', () => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-11-24T12:00:00Z'));
const { app } = loadModule();
app.sessions.set('s1', {
id: 's1',
mode: 'claude',
status: 'busy',
workingDir: '/work',
lastSubmitAt: Date.now() - 73_000,
});
app.setChatViewMode('s1', 'chat');
const a = app as unknown as {
onChatViewTurnEvent: (id: string, idle: boolean) => void;
_chatView: { statusText: HTMLElement };
};
// A working event for a session this page never saw idle says nothing about the turn's start.
a.onChatViewTurnEvent('s1', false);
app.onChatViewActiveSession('s1');
expect(a._chatView.statusText.textContent).toBe('Working · 1m 13s');
// Stop the status line's ticking before the real clock comes back.
app.setChatViewMode('s1', 'terminal');
vi.useRealTimers();
});
it('counts a turn this page saw start from its session:working event', () => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-11-24T12:00:00Z'));
try {
const { app } = loadModule();
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
app.onChatViewTurnEvent('s1', true);
vi.setSystemTime(Date.now() + 30_000);
const session = app.sessions.get('s1')!;
session.status = 'busy';
// An older Enter, which must not be the start of the turn the page saw begin.
session.lastSubmitAt = Date.now() - 60_000;
app.onChatViewTurnEvent('s1', false);
vi.setSystemTime(Date.now() + 5_000);
app._chatViewRenderStatus();
expect(app._chatView.statusText.textContent).toBe('Working · 5s');
app.setChatViewMode('s1', 'terminal');
} finally {
vi.useRealTimers();
}
});
it("shows no status line during Codeman's keep-alive turn", () => {
const { app } = loadModule();
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
const session = app.sessions.get('s1')!;
session.status = 'busy';
app.onChatViewTurnEvent('s1', false, true);
expect(app._chatView.status.hidden).toBe(true);
session.status = 'idle';
app.onChatViewTurnEvent('s1', true, true);
// A real turn shows it again.
session.status = 'busy';
app.onChatViewTurnEvent('s1', false);
expect(app._chatView.status.hidden).toBe(false);
session.status = 'idle';
app.onChatViewTurnEvent('s1', true);
});
/** A Chat session that is busy, on a device that is touch or not, with app.js's focus rule. */
function loadForFocus(touch: boolean) {
const loaded = loadModule();
const { win, app } = loaded;
// The rule the app applies to a tab switch (app.js), run as written.
const appJs = read('app.js');
const method = appJs.match(/\n {2}_shouldFocusTerminalForTabSwitch\(\) \{[\s\S]*?\n {2}\}\n/)![0];
Object.assign(app, win.eval(`({${method}})`) as object);
win.MobileDetection = {
isHandheldDevice: () => false,
getDeviceType: () => (touch ? 'tablet' : 'desktop'),
isTouchDevice: () => touch,
};
win.KeyboardHandler = { keyboardVisible: false };
app.sessions.get('s1')!.status = 'busy';
app.setChatViewMode('s1', 'terminal');
return loaded;
}
const nextFrame = (win: Window) => new Promise<void>((r) => win.requestAnimationFrame(() => r()));
it('follows the tab-switch focus rule on a touch device: no focus on a switch to Chat', async () => {
const { win, app } = loadForFocus(true);
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
await nextFrame(win);
expect(win.document.activeElement).not.toBe(app._chatView.scroller);
});
it('moves a focus left in the terminal to the conversation on a switch to Chat, on a touch device', async () => {
const { win, app } = loadForFocus(true);
const inner = win.document.createElement('textarea');
win.document.getElementById('terminalContainer')!.appendChild(inner);
inner.focus();
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
await nextFrame(win);
expect(win.document.activeElement).toBe(app._chatView.scroller);
});
it('moves a focus left on the CJK input field to the conversation on a switch to Chat, on a touch device', async () => {
const { win, app } = loadForFocus(true);
(win.document.getElementById('cjkInput') as HTMLTextAreaElement).focus();
expect(win.document.activeElement?.id).toBe('cjkInput');
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
await nextFrame(win);
expect(win.document.activeElement).toBe(app._chatView.scroller);
});
it('focuses the conversation on a desktop, on a switch to Chat', async () => {
const { win, app } = loadForFocus(false);
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
await nextFrame(win);
expect(win.document.activeElement).toBe(app._chatView.scroller);
});
it('unfolds a long prompt in place, with the badge it was drawn with', () => {
const { win, app } = loadModule();
const a = app as unknown as {
_buildResponseViewerMessage: (t: string, r: string, l: string, m?: { continuation?: boolean }) => HTMLElement;
_chatViewBuildMessage: (m: Msg, label: string, continuation: boolean) => HTMLElement;
};
// As the real builder does: a prompt that is not a continuation carries its "You" badge.
const build = a._buildResponseViewerMessage;
a._buildResponseViewerMessage = (text, role, label, meta) => {
const el = build(text, role, label, meta);
if (!meta?.continuation) {
const badge = win.document.createElement('div');
badge.className = 'rv-role rv-role-user';
el.prepend(badge);
}
return el;
};
const long = Array.from({ length: 30 }, (_, i) => `line ${i}`).join('\n');
const el = a._chatViewBuildMessage({ role: 'user', text: long, turn: 1 }, 'Claude', true);
expect(el.classList.contains('rv-msg-cont')).toBe(true);
(el.querySelector('.chat-view-show-all') as HTMLButtonElement).click();
expect(el.querySelector(':scope > .rv-role')).toBeNull();
expect(el.classList.contains('rv-msg-cont')).toBe(true);
expect(el.querySelector('.chat-view-show-all')).toBeNull();
expect(el.textContent).toContain('line 29');
});
it('shows the waiting notice while a permission prompt or question is pending', () => {
const { app } = loadModule();
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
expect(app._chatView.dialog.hidden).toBe(true);
app.pendingHooks.set('s1', new Set(['elicitation_dialog']));
app.onChatViewHooksChanged('s1');
expect(app._chatView.dialog.hidden).toBe(false);
app.pendingHooks.set('s1', new Set(['idle_prompt']));
app.onChatViewHooksChanged('s1');
expect(app._chatView.dialog.hidden).toBe(true);
// Claude's AskUserQuestion, plan approval and permission dialogs arrive as permission_prompt.
app.pendingHooks.set('s1', new Set(['permission_prompt']));
app.onChatViewHooksChanged('s1');
expect(app._chatView.dialog.hidden).toBe(false);
});
it('re-reads on transcript:update only for its own session and only while showing', () => {
const { app } = loadModule();
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
const reload = vi.spyOn(app, '_chatViewReload').mockImplementation(() => {});
app._onChatViewTranscriptUpdate({ sessionId: 's1' });
expect(reload).toHaveBeenCalledTimes(1);
app._onChatViewTranscriptUpdate({ sessionId: 's2' });
expect(reload).toHaveBeenCalledTimes(1);
app.setChatViewMode('s1', 'terminal');
app._onChatViewTranscriptUpdate({ sessionId: 's1' });
expect(reload).toHaveBeenCalledTimes(1);
});
it('reads nothing once hidden, even for a re-read armed while Chat showed', async () => {
vi.useFakeTimers();
try {
const { app } = loadModule();
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
await vi.advanceTimersByTimeAsync(0);
const reads = app._apiJson.mock.calls.length;
app._onChatViewTranscriptUpdate({ sessionId: 's1' });
app.setChatViewMode('s1', 'terminal');
await vi.advanceTimersByTimeAsync(300);
expect(app._apiJson.mock.calls.length).toBe(reads);
} finally {
vi.useRealTimers();
}
});
/** A read of the conversation that stays pending until the test resolves it. */
function deferredRead() {
let resolve!: (v: { messages: Msg[] }) => void;
const promise = new Promise<{ messages: Msg[] }>((r) => (resolve = r));
return { promise, resolve };
}
it('reads once more when an update arrived while a read was in flight', async () => {
vi.useFakeTimers();
try {
const { app } = loadModule();
const first = deferredRead();
app._apiJson.mockImplementationOnce(() => first.promise);
app.setChatViewMode('s1', 'chat');
expect(app._apiJson).toHaveBeenCalledTimes(1);
// The update's debounced read finds the first one still in flight.
app._onChatViewTranscriptUpdate({ sessionId: 's1' });
await vi.advanceTimersByTimeAsync(300);
expect(app._apiJson).toHaveBeenCalledTimes(1);
first.resolve({ messages: [{ role: 'user', text: 'Hi', turn: 1 }] });
await vi.advanceTimersByTimeAsync(300);
expect(app._apiJson).toHaveBeenCalledTimes(2);
app.setChatViewMode('s1', 'terminal');
} finally {
vi.useRealTimers();
}
});
it('drops a read that finishes after the user switched to another session', async () => {
vi.useFakeTimers();
try {
const { app } = loadModule();
const s1Read = deferredRead();
app._apiJson.mockImplementationOnce(() => s1Read.promise);
app.setChatViewMode('s1', 'chat');
app.setChatViewMode('s5', 'chat');
app.activeSessionId = 's5';
app.onChatViewActiveSession('s5');
s1Read.resolve({ messages: [{ role: 'assistant', text: 'Answer for s1 only', turn: 1 }] });
// Checked before the debounced read for s5 runs, which would redraw the thread anyway.
await vi.advanceTimersByTimeAsync(0);
expect(app._chatView.thread.textContent).not.toContain('Answer for s1 only');
await vi.advanceTimersByTimeAsync(300);
expect(app._chatView.thread.textContent).not.toContain('Answer for s1 only');
app.setChatViewMode('s5', 'terminal');
} finally {
vi.useRealTimers();
}
});
describe('the Alt+Shift+C chord', () => {
const chord = { altKey: true, shiftKey: true, key: 'C', code: 'KeyC' };
/** The module with app.js's shortcut matcher, run as written, and a registry holding the chord. */
function loadForChord(disabled = false) {
const loaded = loadModule();
const { win, app } = loaded;
const method = read('app.js').match(/\n {2}matchesShortcutEvent\(e, shortcut\) \{[\s\S]*?\n {2}\}\n/)![0];
Object.assign(app, win.eval(`({${method}})`) as object, {
getShortcutRegistry: () => [
{ id: 'toggle-chat-view', bindings: [{ modifiers: ['alt', 'shift'], key: 'C', code: 'KeyC' }], disabled },
],
});
return loaded;
}
it('applies to an active session that can show the chat view', () => {
const { app } = loadForChord();
expect(app.shouldToggleChatViewFromShortcut(chord)).toBe(true);
});
it('reaches the terminal in a session that cannot show the chat view', () => {
const { app } = loadForChord();
app.sessions.set('s6', { id: 's6', mode: 'shell', status: 'idle' });
app.activeSessionId = 's6';
expect(app.shouldToggleChatViewFromShortcut(chord)).toBe(false);
});
it('reaches the tiles while the tile grid owns the terminal', () => {
const { app } = loadForChord();
(app as unknown as { _tilesOwnTerminal: () => boolean })._tilesOwnTerminal = () => true;
expect(app.shouldToggleChatViewFromShortcut(chord)).toBe(false);
});
it('needs a modifier', () => {
const { app } = loadForChord();
expect(app.shouldToggleChatViewFromShortcut({ key: 'C', code: 'KeyC' })).toBe(false);
});
it('does nothing when the user disabled the shortcut', () => {
const { app } = loadForChord(true);
expect(app.shouldToggleChatViewFromShortcut(chord)).toBe(false);
});
});
it('stays hidden while the tile grid owns the terminal, so the keyboard bar shows for the tiles', () => {
const { win, app } = loadModule();
const a = app as unknown as {
_tileGrid?: { open: boolean };
_tilesOwnTerminal: () => boolean;
_chatViewSync: () => void;
};
a._tilesOwnTerminal = () => !!a._tileGrid?.open;
app.setChatViewMode('s1', 'chat');
app.onChatViewActiveSession('s1');
expect(win.document.body.classList.contains('chat-view-showing')).toBe(true);
a._tileGrid = { open: true };
a._chatViewSync();
expect(win.document.body.classList.contains('chat-view-showing')).toBe(false);
expect(app._chatView.root.hidden).toBe(true);
a._tileGrid = { open: false };
a._chatViewSync();
expect(win.document.body.classList.contains('chat-view-showing')).toBe(true);
expect(app._chatView.root.hidden).toBe(false);
});
});
describe('chat view wiring', () => {
it("swallows the toggle chord in the xterm key handler and in Pane B's", () => {
const terminalUi = read('terminal-ui.js');
expect(terminalUi).toMatch(/shouldToggleChatViewFromShortcut\?\.\(ev\)\)\s*\{\s*return false;/);
const tile = read('terminal-tile.js');
expect(tile).toContain(
"if (ev.type === 'keydown' && global.app?.shouldToggleChatViewFromShortcut?.(ev)) return false;"
);
});
it('re-reads the conversation after an SSE reconnect onto the session on screen', () => {
const app = read('app.js');
expect(app).toMatch(
/void this\._onSessionNeedsRefresh\(\{ id: restoreId \}\);[\s\S]{0,300}?this\._chatViewReload\?\.\(\{ immediate: true \}\);/
);
});
it('hides the chat view when the home screen shows', () => {
const terminalUi = read('terminal-ui.js');
expect(terminalUi).toMatch(/\n {2}showWelcome\(\) \{\n {4}this\._chatViewHide\?\.\(\);/);
});
it('keeps the chat view layers under the narrow-width sidebar drawer', () => {
// The drawer (z-index 12, mobile.css) is a sibling of .terminal-wrap: the chat view's 20 and 21
// must stay inside the terminal area's own stacking context.
const css = read('styles.css');
expect(css).toMatch(/\n\.terminal-wrap \{[^}]*isolation: isolate;[^}]*\}/);
});
it('binds Alt+Shift+C to the toggle in the shortcut registry', () => {
const app = read('app.js');
expect(app).toMatch(
/id: 'toggle-chat-view',[\s\S]*?modifiers: \['alt', 'shift'\], key: 'C', code: 'KeyC'[\s\S]*?action: 'toggleChatView'/
);
expect(app).toContain('toggleChatView: () => this.toggleChatView?.()');
});
it('keeps chatViewDefault per device and out of the server PUT', () => {
const settings = read('settings-ui.js');
expect(settings).toMatch(/'showEditHistory', 'chatViewDefault',/);
expect(settings).toContain('chatViewDefault: _cvd,');
const schemas = readFileSync(resolve(import.meta.dirname, '../src/web/schemas.ts'), 'utf8');
expect(schemas).not.toContain('chatViewDefault');
});
it('keeps showChatViewSwitch per device, out of the server PUT, and off when absent', () => {
const settings = read('settings-ui.js');
expect(settings).toMatch(/'showEditHistory', 'chatViewDefault', 'showChatViewSwitch',/);
expect(settings).toContain('showChatViewSwitch: _scvs,');
expect(settings).toContain(
"document.getElementById('appSettingsShowChatViewSwitch').checked = settings.showChatViewSwitch === true;"
);
const schemas = readFileSync(resolve(import.meta.dirname, '../src/web/schemas.ts'), 'utf8');
expect(schemas).not.toContain('showChatViewSwitch');
// A settings save re-syncs the chat view, so the switch follows the new value at once.
expect(settings).toMatch(/this\._chatViewSync\?\.\(\);/);
const html = read('index.html');
expect(html).toContain('id="appSettingsShowChatViewSwitch"');
});
it('passes the keep-alive flag of session:working and session:idle to the chat view', () => {
const app = read('app.js');
expect(app).toContain('this.onChatViewTurnEvent?.(data.id, true, data.keepAlive);');
expect(app).toContain('this.onChatViewTurnEvent?.(data.id, false, data.keepAlive);');
});
it('hides the CJK input field on a touch device while Chat shows', () => {
// The field is fixed over the bottom of the chat view there, and its text goes into the pane.
const css = read('styles.css');
expect(css).toMatch(
/\nbody\.chat-view-showing\.touch-device #cjkInput\.cjk-input-visible \{\s*display: none !important;\s*\}/
);
});
it("starts the chat layer and its switch below Pane A's split header", () => {
const css = read('styles.css');
expect(css).toMatch(/\.terminal-pane-a-header ~ \.chat-view \{\s*top: 28px;\s*\}/);
expect(css).toMatch(/\.terminal-pane-a-header ~ \.chat-view-toggle \{\s*top: 36px;\s*\}/);
});
it('centres the empty notice over the Response Viewer paragraph margin', () => {
// The notice is a <p> directly inside .response-viewer-body, whose `> p` margin rule
// outranks `.chat-view-empty` alone and left it against the window's left edge.
const css = read('styles.css');
expect(css).toMatch(/\.chat-view-scroll > \.chat-view-empty \{\s*margin-left: auto;\s*margin-right: auto;\s*\}/);
});
it('loads chat-view.js after local-model-ui.js', () => {
const html = read('index.html');
expect(html.indexOf('src="chat-view.js"')).toBeGreaterThan(html.indexOf('src="local-model-ui.js"'));
});
});
@@ -0,0 +1,51 @@
/**
* @fileoverview A Docker session's reported transcript path is watched on the host
* (src/web/claude-conversation-report.ts).
*
* Claude in a Docker case runs with `HOME=/home/agent`, so a hook or the statusline reports a
* transcript under `/home/agent/.claude/projects`, which does not exist on the host. The case
* mounts the host's `~/.claude/projects` there, so the watcher must follow the host's copy.
*/
import { homedir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it, vi } from 'vitest';
import { hostTranscriptPath, noteClaudeConversationReport } from '../src/web/claude-conversation-report.js';
import { CONTAINER_CLAUDE_DIR } from '../src/docker-hosts.js';
import type { Session } from '../src/session.js';
const docker = { docker: { containerName: 'codeman-case' } } as unknown as Pick<Session, 'docker'>;
const reported = `${CONTAINER_CLAUDE_DIR}/projects/-workspace-app/abc.jsonl`;
describe('hostTranscriptPath', () => {
it("maps a Docker session's container path into the host's projects folder", () => {
expect(hostTranscriptPath(docker, reported)).toBe(
join(homedir(), '.claude', 'projects', '-workspace-app', 'abc.jsonl')
);
});
it('leaves a local session, a path outside the projects folder and a path with `..` as reported', () => {
expect(hostTranscriptPath({ docker: undefined }, reported)).toBe(reported);
expect(hostTranscriptPath(undefined, reported)).toBe(reported);
expect(hostTranscriptPath(docker, '/home/agent/elsewhere/abc.jsonl')).toBe('/home/agent/elsewhere/abc.jsonl');
const escape = `${CONTAINER_CLAUDE_DIR}/projects/../../.ssh/id_rsa`;
expect(hostTranscriptPath(docker, escape)).toBe(escape);
});
});
describe('noteClaudeConversationReport', () => {
it("starts a Docker session's watcher on the host path", () => {
const startTranscriptWatcher = vi.fn();
const session = { ...docker, claudeSessionChain: [], adoptClaudeSessionId: vi.fn() };
const ctx = {
sessions: new Map([['s1', session]]),
startTranscriptWatcher,
persistSessionState: vi.fn(),
} as unknown as Parameters<typeof noteClaudeConversationReport>[0];
noteClaudeConversationReport(ctx, 's1', { transcript_path: reported });
expect(startTranscriptWatcher).toHaveBeenCalledWith(
's1',
join(homedir(), '.claude', 'projects', '-workspace-app', 'abc.jsonl')
);
});
});
+216
View File
@@ -0,0 +1,216 @@
/**
* @fileoverview The incremental Claude transcript reader behind `last-response`
* (src/web/claude-response-transcript.ts).
*
* Every read must answer what a parse of the whole file answers, whatever the file did between
* reads: grew, grew by half a line, shrank, was replaced, or was rewritten in place. A read must
* also parse only the bytes appended since the last one, and overlapping reads of one file must
* share their passes.
*/
import { appendFileSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import fs from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
ClaudeResponseParser,
ClaudeTranscriptReader,
parseClaudeResponseTranscript,
} from '../src/web/claude-response-transcript.js';
import { KEEP_WARM_NUDGE } from '../src/prompt-cache-keepwarm.js';
const user = (text: string, extra: Record<string, unknown> = {}) =>
JSON.stringify({ type: 'user', timestamp: '2026-11-27T10:00:00Z', message: { content: text }, ...extra });
const assistant = (text: string, ts = '2026-11-27T10:00:01Z') =>
JSON.stringify({ type: 'assistant', timestamp: ts, message: { content: [{ type: 'text', text }] } });
const toolUse = () =>
JSON.stringify({ type: 'assistant', message: { content: [{ type: 'tool_use', id: 't', name: 'Bash', input: {} }] } });
const toolResult = () =>
JSON.stringify({ type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 't', content: 'ok' }] } });
const queued = (prompt: string) =>
JSON.stringify({
type: 'attachment',
attachment: { type: 'queued_command', prompt, commandMode: 'prompt', origin: { kind: 'human' } },
});
/** A conversation that exercises turns, queued prompts, replays, keep-warm turns and tool rows. */
const LINES = [
user('first prompt'),
user('first prompt'), // a replayed row, collapsed
toolUse(),
toolResult(),
assistant('first answer'),
assistant('first answer'), // a replayed snapshot, collapsed
user('second prompt'),
queued('queued while working'),
assistant('second answer — with ünïcödé and 漢字 to cut mid-character'),
JSON.stringify({ type: 'user', isSidechain: true, message: { content: 'sidechain' } }),
user(KEEP_WARM_NUDGE),
assistant('ok'),
'{ not json',
user('<system-reminder>synthetic</system-reminder>'),
user('third prompt'),
assistant('third answer'),
];
describe('ClaudeResponseParser', () => {
it('answers the same whether fed at once or line by line, and its answers never change later', () => {
const whole = parseClaudeResponseTranscript(LINES.join('\n') + '\n');
const parser = new ClaudeResponseParser();
const early = (() => {
for (const line of LINES.slice(0, 5)) parser.feedLine(line);
return parser.result();
})();
for (const line of LINES.slice(5)) parser.feedLine(line);
expect(parser.result()).toEqual(whole);
expect(early.messages).toHaveLength(2);
expect(whole.text).toBe('third answer');
expect(whole.messages.map((m) => m.text)).toEqual([
'first prompt',
'first answer',
'second prompt',
'queued while working',
'second answer — with ünïcödé and 漢字 to cut mid-character',
KEEP_WARM_NUDGE,
'ok',
'third prompt',
'third answer',
]);
expect(whole.messages.filter((m) => m.keepAlive).map((m) => m.text)).toEqual([KEEP_WARM_NUDGE, 'ok']);
});
it('leaves the original untouched when a clone parses more', () => {
const parser = new ClaudeResponseParser();
parser.feedLine(user('p'));
const copy = parser.clone();
copy.feedLine(assistant('a'));
expect(parser.result().messages).toHaveLength(1);
expect(copy.result().messages).toHaveLength(2);
});
});
describe('ClaudeTranscriptReader', () => {
let dir: string;
let file: string;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'claude-transcript-reader-'));
file = join(dir, 'conversation.jsonl');
});
afterEach(() => {
vi.restoreAllMocks();
rmSync(dir, { recursive: true, force: true });
});
const whole = () => parseClaudeResponseTranscript(LINES.join('\n') + '\n');
it('answers a parse of the whole file after each append, at any byte boundary', async () => {
const bytes = Buffer.from(LINES.join('\n') + '\n', 'utf8');
// A tiny chunk size makes reads cut lines and multi-byte characters.
const reader = new ClaudeTranscriptReader({ chunkBytes: 7 });
writeFileSync(file, '');
for (let cut = 0; cut < bytes.length; ) {
const next = Math.min(bytes.length, cut + 1 + ((cut * 37) % 53));
appendFileSync(file, bytes.subarray(cut, next));
cut = next;
const expected = parseClaudeResponseTranscript(bytes.subarray(0, cut).toString('utf8'));
// A cut inside a multi-byte character leaves a line that is not JSON either way.
expect(await reader.read(file)).toEqual(expected);
}
expect(await reader.read(file)).toEqual(whole());
});
it('parses only the bytes appended since the last read', async () => {
writeFileSync(file, LINES.slice(0, 8).join('\n') + '\n');
const reader = new ClaudeTranscriptReader();
await reader.read(file);
const expected = whole();
const feed = vi.spyOn(ClaudeResponseParser.prototype, 'feedLine');
appendFileSync(file, LINES.slice(8).join('\n') + '\n');
expect(await reader.read(file)).toEqual(expected);
// Only the appended lines; the empty string after the last newline is never fed.
expect(feed.mock.calls.map(([line]) => line)).toEqual(LINES.slice(8));
feed.mockClear();
expect(await reader.read(file)).toEqual(expected);
expect(feed).not.toHaveBeenCalled();
});
it('answers a last line that has no newline yet, and parses it once its newline arrives', async () => {
writeFileSync(file, `${user('p')}\n${assistant('a')}`);
const reader = new ClaudeTranscriptReader();
expect((await reader.read(file)).text).toBe('a');
appendFileSync(file, `\n${assistant('b')}\n`);
expect(await reader.read(file)).toEqual(
parseClaudeResponseTranscript(`${user('p')}\n${assistant('a')}\n${assistant('b')}\n`)
);
});
it('starts again from byte 0 when the file shrank', async () => {
writeFileSync(file, LINES.join('\n') + '\n');
const reader = new ClaudeTranscriptReader();
await reader.read(file);
writeFileSync(file, `${user('new')}\n${assistant('fresh')}\n`);
expect(await reader.read(file)).toEqual(parseClaudeResponseTranscript(`${user('new')}\n${assistant('fresh')}\n`));
});
it('starts again from byte 0 when another file replaced it', async () => {
writeFileSync(file, `${user('p')}\n${assistant('a')}\n`);
const reader = new ClaudeTranscriptReader();
await reader.read(file);
const replacement = join(dir, 'replacement.jsonl');
writeFileSync(replacement, LINES.join('\n') + '\n');
renameSync(replacement, file);
expect(await reader.read(file)).toEqual(whole());
});
it('starts again from byte 0 when the file was rewritten in place to a larger size', async () => {
writeFileSync(file, `${user('p')}\n${assistant('a')}\n`);
const reader = new ClaudeTranscriptReader();
await reader.read(file);
const handle = await fs.open(file, 'r+');
await handle.truncate(0);
await handle.write(LINES.join('\n') + '\n', 0);
await handle.close();
expect(await reader.read(file)).toEqual(whole());
});
it('shares one pass between reads asked for while a read runs', async () => {
writeFileSync(file, LINES.join('\n') + '\n');
const reader = new ClaudeTranscriptReader();
const open = vi.spyOn(fs, 'open');
const results = await Promise.all([reader.read(file), reader.read(file), reader.read(file), reader.read(file)]);
for (const result of results) expect(result).toEqual(whole());
// The first read, then one pass for every read that waited on it.
expect(open).toHaveBeenCalledTimes(2);
});
it('sees bytes appended while an earlier read ran', async () => {
writeFileSync(file, `${user('p')}\n`);
const reader = new ClaudeTranscriptReader();
const first = reader.read(file);
appendFileSync(file, `${assistant('late')}\n`);
const second = reader.read(file);
await first;
expect((await second).text).toBe('late');
});
it('rejects for a missing file, and reads it once it exists', async () => {
const reader = new ClaudeTranscriptReader();
await expect(reader.read(file)).rejects.toThrow();
writeFileSync(file, `${assistant('there')}\n`);
expect((await reader.read(file)).text).toBe('there');
});
it('awaits between chunks, so a large first read does not hold the event loop in one step', async () => {
const big = Array.from({ length: 4000 }, (_, i) => `${user(`p${i}`)}\n${assistant(`a${i}`)}`).join('\n') + '\n';
writeFileSync(file, big);
const reader = new ClaudeTranscriptReader({ chunkBytes: 16 * 1024 });
let ticks = 0;
const timer = setInterval(() => ticks++, 0);
const result = await reader.read(file);
clearInterval(timer);
expect(result).toEqual(parseClaudeResponseTranscript(big));
expect(ticks).toBeGreaterThan(0);
});
});
+35
View File
@@ -460,6 +460,41 @@ describe('cross-field integrity', () => {
expect(CliEntrySchema.safeParse(wrong).success).toBe(false);
});
it('holds a rootValue to the values its param declares', () => {
// `rootValue` swaps one declared value for another when the server runs as root (claude's
// bypass mode, which Claude Code refuses under uid 0). A key or a replacement outside
// `values` is a swap that can never apply, or one that launches with a value no arg tests.
const withRootValue = (rootValue: Record<string, string>): Record<string, unknown> => {
const entry = baseEntry('claude');
const params = (entry.launch as { params: Record<string, Record<string, unknown>> }).params;
params.claudeMode.rootValue = rootValue;
return entry;
};
expect(CliEntrySchema.safeParse(withRootValue({ 'dangerously-skip-permissions': 'normal' })).success).toBe(true);
expect(CliEntrySchema.safeParse(withRootValue({})).success).toBe(true);
expect(CliEntrySchema.safeParse(withRootValue({ 'no-such-mode': 'normal' })).success, 'unknown key').toBe(false);
expect(
CliEntrySchema.safeParse(withRootValue({ 'dangerously-skip-permissions': 'no-such-mode' })).success,
'unknown replacement'
).toBe(false);
expect(
CliEntrySchema.safeParse(withRootValue({ 'dangerously-skip-permissions': 'dangerously-skip-permissions' }))
.success,
'a value replaced by itself'
).toBe(false);
expect(
CliEntrySchema.safeParse(withRootValue({ 'dangerously-skip-permissions': 'auto', auto: 'normal' })).success,
'a replacement that is replaced again'
).toBe(false);
});
it('takes a rootValue on an enum param only', () => {
expectRejected((e) => {
const params = (e.launch as { params: Record<string, Record<string, unknown>> }).params;
params.rootToggle = { type: 'bool', rootValue: { true: 'false' } };
}, 'the strict bool spec has no rootValue key');
});
it('rejects a profile name this build does not implement', () => {
expectRejected((e) => {
(e.discovery as Record<string, unknown>).launcherProfile = 'no-such-profile';
+225
View File
@@ -0,0 +1,225 @@
// test/codex-file-previews-setting.test.ts
// Port: none (static analysis plus vm-loaded modules, runs in CI, no browser/server).
//
// `codexFilePreviewsEnabled` (App Settings > Header & Panels > Codex files) gates four
// behaviours together, per device, default OFF:
// 1. the Response files header button (never on phones, even when on),
// 2. taking a click on a file tab in Codex's own sidebar (and suppressing the
// ordinary linkifier on those rows),
// 3. the Dock control on file previews,
// 4. taking a click on a file name Codex underlined in the pane (owner decision for 1.52.1).
// With it off none of the four exists. Each surface's off-state behaviour is also
// pinned next to its own tests (response-viewer-file-links, terminal-link-provider-target,
// file-preview-window); this file pins the setting's own wiring and the off-state of all
// three through the real reader.
import { describe, it, expect, vi } from 'vitest';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { join } from 'node:path';
import vm from 'node:vm';
import { JSDOM } from 'jsdom';
import { performance } from 'node:perf_hooks';
const HERE = fileURLToPath(new URL('.', import.meta.url));
const PUBLIC = join(HERE, '../src/web/public');
const read = (file: string) => readFileSync(join(PUBLIC, file), 'utf8');
describe('codexFilePreviewsEnabled stays per-device: display key, stripped from the PUT, absent from the schema', () => {
const settingsUi = read('settings-ui.js');
const schemas = readFileSync(join(HERE, '../src/web/schemas.ts'), 'utf8');
it('is in the client-side displayKeys merge policy', () => {
const start = settingsUi.indexOf('const displayKeys = new Set([');
const displayKeys = settingsUi.slice(start, settingsUi.indexOf('])', start));
expect(displayKeys).toContain("'codexFilePreviewsEnabled'");
});
it('is stripped out of the object saveAppSettings() PUTs and never declared in the .strict() schema', () => {
expect(settingsUi).toContain('codexFilePreviewsEnabled: _cfp,');
expect(schemas).not.toContain('codexFilePreviewsEnabled');
});
it('is loaded into and saved from its App Settings chip, default OFF', () => {
const index = read('index.html');
expect(index).toMatch(
/<label class="set-chip"[^>]*data-preview="header"[^>]*><input type="checkbox" id="appSettingsCodexFilePreviews">/
);
expect(settingsUi).toContain(
"document.getElementById('appSettingsCodexFilePreviews').checked = settings.codexFilePreviewsEnabled ?? defaults.codexFilePreviewsEnabled ?? false;"
);
expect(settingsUi).toContain(
"codexFilePreviewsEnabled: document.getElementById('appSettingsCodexFilePreviews').checked,"
);
});
});
describe('with the Codex files setting off (nothing stored), none of the four behaviours exists', () => {
function loadApp() {
const { window } = new JSDOM(`<!doctype html>
<button id="responseFilesBtn" class="btn-icon-header btn-response-files btn-response-files--hidden" hidden></button>
<main class="main"><div class="terminal-wrap"><div id="terminalContainer"></div></div></main>
<div id="filePreviewOverlay" class="visible"><button id="filePreviewDockBtn" hidden aria-pressed="false"></button></div>`);
const { document } = window;
const fetchSpy = vi.fn();
const context = vm.createContext({
console: { ...console, debug: vi.fn(), log: vi.fn() },
performance,
setInterval: vi.fn(),
clearInterval: vi.fn(),
setTimeout,
clearTimeout,
requestAnimationFrame: vi.fn(),
HTMLCanvasElement: class HTMLCanvasElement {},
fetch: fetchSpy,
AbortSignal,
document,
NodeFilter: window.NodeFilter,
// Nothing stored on this device: the setting reads its default.
localStorage: { length: 0, key: vi.fn(), getItem: () => null, setItem: vi.fn(), removeItem: vi.fn() },
window: {
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
matchMedia: () => ({ matches: true }), // a wide desktop: docking would otherwise apply
__codemanCliCatalog: [{ id: 'codex', transcript: 'codex-rollout' }],
},
MobileDetection: { isHandheldDevice: () => false, isTouchDevice: () => false, getDeviceType: () => 'desktop' },
});
const addEventListener = vi.spyOn(document, 'addEventListener').mockImplementation(() => {});
try {
vm.runInContext(
['constants.js', 'app.js', 'settings-ui.js', 'panels-ui.js', 'terminal-ui.js'].map(read).join('\n') +
'\nglobalThis.__CodemanApp = CodemanApp;',
context
);
} finally {
addEventListener.mockRestore();
}
const CodemanApp = (context as unknown as { __CodemanApp: { prototype: object } }).__CodemanApp;
const app = Object.assign(Object.create(CodemanApp.prototype), {
$: (id: string) => document.getElementById(id),
activeSessionId: 'codex-1',
sessions: new Map([['codex-1', { mode: 'codex' }]]),
});
return { app, document, fetchSpy };
}
it('reads OFF from the real device settings with nothing stored', () => {
const { app } = loadApp();
expect(app._codexFilePreviewsEnabled()).toBe(false);
});
it('1. keeps the Response files button hidden in a Codex session', () => {
const { app, document } = loadApp();
app._syncResponseFilesButton();
expect(document.getElementById('responseFilesBtn')!.classList.contains('btn-response-files--hidden')).toBe(true);
});
it('2. takes no click on a Codex sidebar file tab', () => {
const { app } = loadApp();
const cols = 80;
const lines = [' '.repeat(42) + '│ Brief.docx × +', ' '.repeat(42) + '│ body'];
const terminal = {
cols,
buffer: {
active: {
viewportY: 0,
length: lines.length,
getLine: (row: number) =>
lines[row] === undefined
? undefined
: {
isWrapped: false,
getCell: (col: number) => ({
getChars: () => lines[row][col] ?? ' ',
getWidth: () => 1,
isUnderline: () => false,
}),
translateToString: (trim?: boolean, start = 0, end = cols) => {
const text = lines[row].padEnd(cols).slice(start, end);
return trim ? text.trimEnd() : text;
},
},
},
},
};
app._clientPointToCell = (col: number, row: number) => ({ col, row });
expect(app._codexTerminalLinkLabel(terminal, 46, 1)).toBeNull();
app._codexFilePreviewsEnabled = () => true; // the same click, setting on: taken
expect(app._codexTerminalLinkLabel(terminal, 46, 1)).toMatchObject({ label: 'Brief.docx', sidebar: true });
});
it('3. never docks a preview', () => {
const { app, document } = loadApp();
const overlay = document.getElementById('filePreviewOverlay')!;
app.toggleFilePreviewDock();
app._setFilePreviewDocked(true);
expect(overlay.classList.contains('is-docked')).toBe(false);
expect(overlay.parentElement).toBe(document.body);
app._codexFilePreviewsEnabled = () => true; // the same call, setting on: docks
app._setFilePreviewDocked(true);
expect(overlay.classList.contains('is-docked')).toBe(true);
});
it('4. passes a click on a file name Codex underlined in the pane on to Codex', () => {
const { app } = loadApp();
const cols = 40;
const text = '• Word brief';
const terminal = {
cols,
modes: { mouseTrackingMode: 'none' },
hasSelection: () => false,
buffer: {
active: {
viewportY: 0,
length: 2,
getLine: (row: number) =>
row > 1
? undefined
: {
isWrapped: false,
getCell: (col: number) => ({
getChars: () => (row === 0 ? (text[col] ?? ' ') : ' '),
getWidth: () => 1,
isUnderline: () => row === 0 && col >= 2 && col < 12,
}),
translateToString: (trim?: boolean, start = 0, end = cols) => {
const line = (row === 0 ? text : '').padEnd(cols).slice(start, end);
return trim ? line.trimEnd() : line;
},
},
},
},
};
app.terminal = terminal;
app._clientPointToCell = () => ({ col: 5, row: 1 });
app._shouldReportMouseToCli = () => true;
app._sendSyntheticSgrTap = vi.fn();
app._openCodexTerminalResponseFile = vi.fn().mockResolvedValue(undefined);
const click = { isTrusted: true, button: 0, detail: 1, clientX: 50, clientY: 10, target: { closest: () => ({}) } };
app._handleDesktopTerminalClick(click);
expect(app._openCodexTerminalResponseFile).not.toHaveBeenCalled();
expect(app._sendSyntheticSgrTap).toHaveBeenCalledTimes(1);
app._codexFilePreviewsEnabled = () => true; // the same click, setting on: looked up first
app._handleDesktopTerminalClick(click);
expect(app._openCodexTerminalResponseFile).toHaveBeenCalledTimes(1);
expect(app._openCodexTerminalResponseFile.mock.calls[0][3]).toMatchObject({ label: 'Word brief' });
expect(app._sendSyntheticSgrTap).toHaveBeenCalledTimes(1);
});
it('flips the Dock button of an open preview when the setting changes, not only at the next open', () => {
const { app, document } = loadApp();
const dockBtn = document.getElementById('filePreviewDockBtn')!;
app._codexFilePreviewsEnabled = () => true;
app.applyHeaderVisibilitySettings();
expect(dockBtn.hidden).toBe(false);
app._codexFilePreviewsEnabled = () => false;
app.applyHeaderVisibilitySettings();
expect(dockBtn.hidden).toBe(true);
});
it('keeps Response files off phones even with the setting on', () => {
const mobileCss = read('mobile.css');
const phoneBlock = mobileCss.slice(mobileCss.indexOf('@media (max-width: 599px)'));
expect(phoneBlock).toMatch(/\.btn-icon-header\.btn-response-files,[\s\S]*?display: none !important;/);
});
});
+8
View File
@@ -472,6 +472,14 @@ async function stripWalk(browser: Browser) {
same(await order(), [14, 12, 13, 11]) && (await page.textContent(sel(12, '.name'))) === 'twelve',
await order()
);
// As far right as it goes: the clamp stops the tab with its centre on the last tab's centre,
// which must still count as passing it.
await page.mouse.move(await centre(14), 22);
await page.mouse.down();
await page.mouse.move((await centre(11)) + 400, 22, { steps: 12 });
await page.mouse.up();
check('dragged past the end, a tab lands in the last place', same(await take(), [{ cmd: 'move', id: 14, to: 3 }]));
check('and shows there', same(await order(), [12, 13, 11, 14]), await order());
// 8. Many tabs and long names.
const many = Array.from({ length: 30 }, (_, i) => tab(100 + i, 'server-' + i, { active: i === 0 }));
+131
View File
@@ -24,6 +24,7 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { JSDOM } from 'jsdom';
import { describe, expect, it, vi } from 'vitest';
const PUBLIC = resolve(import.meta.dirname, '../src/web/public');
@@ -407,3 +408,133 @@ describe('file viewer on phones', () => {
expect(phone).toMatch(/#filePreviewExpandBtn,\s*\.file-preview-resize\s*\{\s*display: none;/);
});
});
describe('file preview dock lifecycle', () => {
function setup(layout: string, wide = true, codexFiles = true) {
const { window } = new JSDOM(`<!doctype html><main class="main ${layout}">
<div class="terminal-wrap"><div id="terminalContainer"></div></div>
</main><div id="filePreviewOverlay" class="visible">
<button id="filePreviewDockBtn" aria-pressed="false"></button>
</div>`);
const { document } = window;
const CodemanApp = function CodemanApp() {};
const context = vm.createContext({
CodemanApp,
document,
window: {
matchMedia: () => ({ matches: wide }),
innerWidth: 1400,
addEventListener: vi.fn(),
TerminalTile: class {
async connect() {}
destroy() {}
},
},
SPLIT_PANE_MIN_WIDTH: 1000,
});
vm.runInContext(panelsJs, context);
const splitJs = readFileSync(resolve(PUBLIC, 'terminal-split.js'), 'utf8');
vm.runInContext(splitJs, context);
const app = Object.assign(Object.create(CodemanApp.prototype), {
$: (id: string) => document.getElementById(id),
_resetFilePreviewEdit: vi.fn(),
_updateSplitButtonState: vi.fn(),
_buildSplitPaneHeader: () => ({ el: document.createElement('div') }),
_renderSplitChrome: vi.fn(),
_installSplitDividerDrag: vi.fn(),
activeSessionId: 'pane-a',
sessions: new Map([['pane-b', { pid: 1 }]]),
terminal: { focus: vi.fn() },
_codexFilePreviewsEnabled: () => codexFiles,
});
const overlay = document.getElementById('filePreviewOverlay')!;
const main = document.querySelector('.main')!;
const wrap = document.querySelector('.terminal-wrap')!;
const dockButton = document.getElementById('filePreviewDockBtn')!;
return { app, document, main, overlay, wrap, dockButton };
}
it('docks beside the terminal and returns to its original parent on close', () => {
const { app, document, main, overlay, wrap, dockButton } = setup('');
app.toggleFilePreviewDock();
expect(overlay.parentElement).toBe(main);
expect(wrap.nextElementSibling).toBe(overlay);
expect(dockButton.getAttribute('aria-pressed')).toBe('true');
app.closeFilePreview();
expect(overlay.parentElement).toBe(document.body);
expect(overlay.classList.contains('visible')).toBe(false);
expect(dockButton.getAttribute('aria-pressed')).toBe('false');
});
it('handles Escape inside the dock and leaves terminal Escape alone', () => {
const { app, document, overlay, wrap, dockButton } = setup('');
app.toggleFilePreviewDock();
const escape = { target: wrap, preventDefault: vi.fn(), stopPropagation: vi.fn() };
expect(app._maybeCloseDockedFilePreviewOnEscape(escape)).toBe(false);
expect(escape.preventDefault).not.toHaveBeenCalled();
expect(overlay.classList.contains('visible')).toBe(true);
expect(app._maybeCloseDockedFilePreviewOnEscape({ ...escape, target: dockButton })).toBe(true);
expect(escape.preventDefault).toHaveBeenCalledOnce();
expect(escape.stopPropagation).toHaveBeenCalledOnce();
expect(app.terminal.focus).toHaveBeenCalledOnce();
expect(overlay.parentElement).toBe(document.body);
});
it('stays floating during a split and survives closing and reopening the preview', () => {
const { app, document, main, overlay } = setup('');
app.toggleFilePreviewDock();
expect(overlay.parentElement).toBe(main);
app.openSplitPane('pane-b');
const split = document.querySelector('.terminal-split-container');
expect(split).not.toBeNull();
expect(overlay.parentElement).toBe(document.body);
app._setFilePreviewDocked(true);
expect(overlay.parentElement).toBe(document.body);
app.closeSplitPane();
expect(split?.isConnected).toBe(false);
expect(overlay.isConnected).toBe(true);
app.closeFilePreview();
overlay.classList.add('visible');
app.toggleFilePreviewDock();
expect(overlay.parentElement).toBe(main);
});
it.each([
['', false],
['tiles-active', true],
['webview-active', true],
])('stays floating when docking is unavailable (layout %s, wide %s)', (layout, wide) => {
const { app, document, overlay } = setup(layout, wide);
app._setFilePreviewDocked(true);
expect(overlay.parentElement).toBe(document.body);
expect(app._isFilePreviewDocked()).toBe(false);
});
it('never docks while the Codex files setting is off', () => {
const { app, document, overlay } = setup('', true, false);
app.toggleFilePreviewDock();
app._setFilePreviewDocked(true);
expect(overlay.parentElement).toBe(document.body);
expect(overlay.classList.contains('is-docked')).toBe(false);
expect(app._isFilePreviewDocked()).toBe(false);
});
it('sits in page flow when docked, under modals and the response viewer', () => {
// The floating overlay's z-index 5100 would put a docked pane above every
// modal backdrop (1000) and the response viewer sheet (5000).
const docked = stylesCss.match(
/\.main:not\(\.tiles-active, \.webview-active\) > \.file-preview-overlay\.is-docked \{([^}]*)\}/
);
expect(docked).not.toBeNull();
expect(docked![1]).toMatch(/z-index:\s*auto;/);
});
it('ships the Dock button hidden, and hidden means hidden at every width', () => {
expect(indexHtml).toMatch(/<button type="button" class="btn-icon-sm" id="filePreviewDockBtn" hidden/);
expect(stylesCss).toMatch(/#filePreviewDockBtn\[hidden\] \{\s*display: none !important;/);
expect(panelsJs).toContain('if (dockBtn) dockBtn.hidden = !this._codexFilePreviewsEnabled?.();');
});
});
@@ -41,6 +41,9 @@ const SCANNED_FILES = [
// The harness a local model is paired with arrives as a label in the payload
// (`Candidate.cliLabel`); the card names no CLI and compares no id.
'local-model-ui.js',
// Which sessions can show the chat view comes from the injected transcript capability
// (window.__codemanChatViewModes), never from an id here.
'chat-view.js',
];
/**
+156
View File
@@ -197,6 +197,162 @@ describe('install.sh runtime safety', () => {
});
});
describe('install.sh and a /dev/tty that exists but cannot be opened', () => {
// The /dev/tty node is there on every Linux and macOS, also for a process with no controlling
// terminal (`su - user -c`, cron, a CI runner, cloud-init). `[[ -e /dev/tty ]]` says yes
// there, and the `< /dev/tty` behind it fails before the command runs. Measured 2026-11-27 in
// a fresh ubuntu:24.04 container: a headless run with a working passwordless sudo ended on
// "Failed to obtain sudo privileges", because `sudo -v < /dev/tty` never started sudo.
// The fix is one probe, `tty_openable`, which OPENS the node.
/** A file test on the node (`[[ -e /dev/tty ]]`, `test -c /dev/tty`): true with no terminal behind it. */
const NODE_TEST = /(?:\[\[?|\btest)\s+!?\s*-[a-zA-Z]\s+"?\/dev\/tty"?/;
/**
* Every command that takes its stdin from /dev/tty, and the ones that do not sit directly
* under `if tty_openable; then`. The probe itself and the two readers are the exceptions:
* read_reply and read_secret run only after has_tty said yes, and with stdin not a terminal
* that IS tty_openable.
*/
function ttyRedirects(source: string): { sites: string[]; unguarded: string[] } {
const exempt = (line: string): boolean =>
/^\s*\{ : < \/dev\/tty; \} 2>\/dev\/null$/.test(line) || /^\s*read -rs? "\$1" < \/dev\/tty$/.test(line);
const lines = source.split('\n');
const indentOf = (line: string): number => line.length - line.trimStart().length;
const sites: string[] = [];
const unguarded: string[] = [];
lines.forEach((line, i) => {
if (/^\s*#/.test(line) || !/<\s*\/dev\/tty\b/.test(line) || exempt(line)) return;
sites.push(line.trim());
// The enclosing statement: the nearest line above with less indentation.
let j = i - 1;
while (j >= 0 && (lines[j].trim() === '' || indentOf(lines[j]) >= indentOf(line))) j--;
if (j < 0 || lines[j].trim() !== 'if tty_openable; then') unguarded.push(`${i + 1}: ${line.trim()}`);
});
return { sites, unguarded };
}
it('never tests the /dev/tty node, only whether it opens', () => {
const offenders = CODE_LINES.filter((line) => NODE_TEST.test(line));
expect(
offenders,
`a file test on /dev/tty says nothing about a controlling terminal; use tty_openable:\n ${offenders.join('\n ')}`
).toEqual([]);
expect(SOURCE).toMatch(/^tty_openable\(\) \{\n {4}\{ : < \/dev\/tty; \} 2>\/dev\/null\n\}$/m);
});
it('takes stdin from /dev/tty only directly under `if tty_openable; then`', () => {
const { sites, unguarded } = ttyRedirects(SOURCE);
expect(unguarded, `redirect from /dev/tty without the open probe:\n ${unguarded.join('\n ')}`).toEqual([]);
// Anti-vacuity: both sudo sites are among what was checked.
expect(sites.filter((line) => /\bsudo -v\b/.test(line)).length).toBe(2);
expect(sites.length).toBeGreaterThanOrEqual(5);
});
it('fails for a sudo site that redirects from /dev/tty behind a bare -e test (anti-vacuity)', () => {
// The shape ensure_sudo had when the headless install died.
const old = [
'ensure_sudo() {',
' if [[ -e /dev/tty ]]; then',
' if ! sudo -v 2>/dev/null < /dev/tty; then',
' die "Failed to obtain sudo privileges."',
' fi',
' fi',
'}',
];
expect(old.filter((line) => NODE_TEST.test(line))).toEqual([' if [[ -e /dev/tty ]]; then']);
expect(ttyRedirects(old.join('\n')).unguarded).toEqual(['3: if ! sudo -v 2>/dev/null < /dev/tty; then']);
// And the same site behind the probe passes.
old[1] = ' if tty_openable; then';
expect(ttyRedirects(old.join('\n'))).toEqual({
sites: ['if ! sudo -v 2>/dev/null < /dev/tty; then'],
unguarded: [],
});
});
/**
* Drive the sudo helpers in a real bash that has NO controlling terminal: `detached` puts
* the child in a session of its own, which is what `su -c`, cron and a CI runner do. `sudo`
* is a shell function that records its arguments and answers from the environment, so no
* real sudo runs. Each stub reads stdin's state the way the real one would.
*/
function driveSudo(body: string, sudo: { n: number; v: number }) {
const driver = `
set -euo pipefail
export CODEMAN_INSTALL_SH_LIB=1
. "$1"
[[ -e /dev/tty ]] && echo "node=present"
if { : < /dev/tty; } 2>/dev/null; then echo "tty=open"; else echo "tty=closed"; fi
sudo() {
echo "sudo $*"
case "$1" in
-n) return "$SUDO_N_RC" ;;
-v) return "$SUDO_V_RC" ;;
esac
return 0
}
NO_ADMIN=0
${body}
`;
const env = { ...process.env, SUDO_N_RC: String(sudo.n), SUDO_V_RC: String(sudo.v) };
return spawnSync('bash', ['-c', driver, 'bash', INSTALL_SH], {
encoding: 'utf-8',
timeout: 30_000,
env,
detached: true,
});
}
// As root the helpers return before they reach sudo, so there is nothing to drive.
const asUser = it.skipIf(process.getuid?.() === 0);
asUser('reproduces the condition: the node is there and does not open', () => {
const result = driveSudo('true', { n: 0, v: 0 });
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toContain('node=present');
expect(result.stdout).toContain('tty=closed');
});
asUser('ensure_sudo passes on a passwordless sudo with no terminal, without validating', () => {
const result = driveSudo('ensure_sudo; echo "ensure=ok"', { n: 0, v: 1 });
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toContain('ensure=ok');
expect(result.stdout).toContain('sudo -n true');
// `sudo -v` wants a password wherever one sudoers entry of the account asks for one,
// even when `sudo <command>` does not, so a sudo that already runs is not validated.
expect(result.stdout).not.toContain('sudo -v');
});
asUser('ensure_sudo falls back to a plain `sudo -v` when the terminal cannot be opened', () => {
const result = driveSudo('ensure_sudo; echo "ensure=ok"', { n: 1, v: 0 });
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toContain('sudo -v');
expect(result.stdout).toContain('ensure=ok');
});
asUser('ensure_sudo names the missing terminal when sudo would have to ask', () => {
const result = driveSudo('ensure_sudo; echo "ensure=ok"', { n: 1, v: 1 });
expect(result.status).toBe(1);
expect(result.stdout).not.toContain('ensure=ok');
expect(result.stderr).toContain('Failed to obtain sudo privileges. Try running the script directly');
});
asUser('sudo_session_try reaches sudo instead of failing on the redirect', () => {
// -n fails, so the keepalive loop it starts ends at once and the driver does not wait for it.
const result = driveSudo('sudo_session_try >/dev/null; echo "try=$?"', { n: 1, v: 0 });
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toContain('try=0');
expect(result.stderr).not.toContain('/dev/tty');
});
asUser('sudo_session_start says to run it directly when there is no terminal to ask on', () => {
const result = driveSudo('sudo_session_start >/dev/null', { n: 1, v: 1 });
expect(result.status).toBe(1);
expect(result.stderr).toContain('Failed to obtain sudo privileges. Try running the script directly');
expect(result.stderr).not.toContain('/dev/tty');
});
});
describe('install.sh DeepSeek identity probe', () => {
it('greps for the same banner the registry identity regex demands', () => {
// dsh_banner_probe is the ONE hand-written identity check left in the script (the
+94
View File
@@ -0,0 +1,94 @@
/**
* @fileoverview KeyedThrottle (src/utils/keyed-throttle.ts), the per-key throttle behind the
* server's `transcript:update` broadcast.
*
* Pinned: the first call sends at once, a burst inside the interval collapses into one trailing
* send at the interval's end, the trailing send runs the newest send it was given, a call after
* the interval sends at once, keys are independent, and cancelKey()/dispose() drop a pending
* trailing send.
*
* Port: N/A
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { KeyedThrottle } from '../src/utils/index.js';
describe('KeyedThrottle', () => {
let throttle: KeyedThrottle;
let sends: Array<{ key: string; at: number }>;
const fire = (key: string) => throttle.fire(key, () => sends.push({ key, at: Date.now() }));
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(10_000);
throttle = new KeyedThrottle(750);
sends = [];
});
afterEach(() => {
throttle.dispose();
vi.useRealTimers();
});
it('sends the first call at once', () => {
fire('a');
expect(sends).toEqual([{ key: 'a', at: 10_000 }]);
});
it('collapses a burst into one trailing send at the end of the interval', () => {
fire('a');
vi.advanceTimersByTime(100);
fire('a');
fire('a');
vi.advanceTimersByTime(300);
fire('a');
expect(sends).toHaveLength(1);
vi.advanceTimersByTime(349);
expect(sends).toHaveLength(1);
vi.advanceTimersByTime(1);
expect(sends).toEqual([
{ key: 'a', at: 10_000 },
{ key: 'a', at: 10_750 },
]);
vi.advanceTimersByTime(5000);
expect(sends).toHaveLength(2);
});
it('runs the newest send it was given when the trailing send fires', () => {
const labels: string[] = [];
throttle.fire('a', () => labels.push('first'));
throttle.fire('a', () => labels.push('second'));
throttle.fire('a', () => labels.push('third'));
vi.advanceTimersByTime(750);
expect(labels).toEqual(['first', 'third']);
});
it('sends at once again once the interval has passed', () => {
fire('a');
vi.advanceTimersByTime(800);
fire('a');
expect(sends.map((s) => s.at)).toEqual([10_000, 10_800]);
});
it('throttles each key on its own', () => {
fire('a');
fire('b');
expect(sends.map((s) => s.key)).toEqual(['a', 'b']);
});
it('drops a pending trailing send on cancelKey() and dispose()', () => {
fire('a');
fire('a');
fire('b');
fire('b');
throttle.cancelKey('a');
vi.advanceTimersByTime(1000);
expect(sends.map((s) => s.key)).toEqual(['a', 'b', 'b']);
fire('c');
fire('c');
throttle.dispose();
vi.advanceTimersByTime(1000);
expect(sends.map((s) => s.key)).toEqual(['a', 'b', 'b', 'c']);
});
});
+8 -1
View File
@@ -42,7 +42,14 @@ const MOBILE_VISIBLE_ALLOWLIST = new Set<string>(['btn-file-viewer']);
// it's excluded from the default-visible enumeration rather than mobile-hidden.
// The edit history button is opt-in the same way, but it IS here: its panel is
// desktop-sized, so it stays off phones even when the setting is on.
const KNOWN_PHONE_HIDDEN = ['btn-settings', 'btn-lifecycle-log', 'btn-session-manager', 'btn-edit-history'];
// Response files (Codex files setting) is opt-in too and likewise stays off phones.
const KNOWN_PHONE_HIDDEN = [
'btn-settings',
'btn-lifecycle-log',
'btn-session-manager',
'btn-edit-history',
'btn-response-files',
];
function attrOf(openTag: string, name: string): string {
const m = openTag.match(new RegExp(`${name}="([^"]*)"`));
+1 -1
View File
@@ -612,7 +612,7 @@ describe('mobile prompt composer', () => {
bar.composePrompt();
const fileInput = document.querySelector('.paste-file-input') as HTMLInputElement;
expect(fileInput.getAttribute('accept')).toBe(
'image/*,video/*,.pdf,.docx,.pptx,.xlsx,.zip,.txt,.md,.csv,.tsv,.json,.log,.yaml,.yml,.xml'
'image/*,video/*,.pdf,.docx,.pptx,.xlsx,.zip,.txt,.md,.csv,.tsv,.json,.log,.yaml,.yml,.xml,.html,.htm'
);
expect((document.querySelector('.paste-image') as HTMLButtonElement).textContent).toBe('📎 Attach');
const video = new document.defaultView!.File(['clip'], 'clip.mov', { type: 'video/quicktime' });
+41 -4
View File
@@ -1,14 +1,21 @@
/**
* @fileoverview `npm run release` moves README.zh-CN.md aside for the publish, so npmjs.com
* renders README.md, and always puts it back (scripts/npm-release.mjs).
* @fileoverview `npm run release` moves the translated READMEs (README.zh-CN.md, README.ja.md)
* aside for the publish, so npmjs.com renders README.md, and always puts them back
* (scripts/npm-release.mjs).
*
* Port: N/A (no server).
*/
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import { ASIDE_NAME, HIDDEN_README, publishWithReadmeAside } from '../scripts/npm-release.mjs';
import {
ASIDE_NAME,
HIDDEN_README,
HIDDEN_READMES,
asideName,
publishWithReadmeAside,
} from '../scripts/npm-release.mjs';
const roots: string[] = [];
function fixture(): string {
@@ -96,6 +103,36 @@ describe('publishWithReadmeAside', () => {
expect(existsSync(join(root, HIDDEN_README))).toBe(false);
});
it('hides the Japanese README too and restores every translation after the publish', () => {
const root = fixture();
writeFileSync(join(root, 'README.ja.md'), 'japanese\n');
let present: string[] = [];
const code = publishWithReadmeAside({
root,
log: quiet,
publish: () => {
present = ['README.md', ...HIDDEN_READMES].filter((name) => existsSync(join(root, name)));
return 0;
},
});
expect(code).toBe(0);
expect(HIDDEN_READMES).toContain('README.ja.md');
expect(present).toEqual(['README.md']);
expect(readFileSync(join(root, HIDDEN_README), 'utf8')).toBe('chinese\n');
expect(readFileSync(join(root, 'README.ja.md'), 'utf8')).toBe('japanese\n');
for (const name of HIDDEN_READMES) expect(existsSync(join(root, asideName(name)))).toBe(false);
});
it('no aside name is one npm treats as a readme', () => {
for (const name of HIDDEN_READMES) expect(/^readme/i.test(asideName(name))).toBe(false);
});
it('every translated root README is moved aside for the publish', () => {
const root = join(import.meta.dirname, '..');
const translated = readdirSync(root).filter((name) => /^readme\./i.test(name) && name !== 'README.md');
expect([...translated].sort()).toEqual([...HIDDEN_READMES].sort());
});
it('package.json routes npm run release through the wrapper', () => {
const pkg = JSON.parse(readFileSync(join(import.meta.dirname, '..', 'package.json'), 'utf8'));
expect(pkg.scripts.release).toBe('node scripts/npm-release.mjs');
+13 -1
View File
@@ -263,6 +263,16 @@ describe('WebServer.renderIndexHtml', () => {
}
});
it('injects the chat view modes from the transcript capability, in solo windows too', async () => {
for (const solo of [undefined, 'sess-123']) {
const { server } = makeServer();
const html = await render(server, solo);
const match = html.match(/window\.__codemanChatViewModes=(\[[^<]*\]);/);
expect(match).not.toBeNull();
expect(JSON.parse(match![1])).toEqual(['claude']);
}
});
it('escapes the solo id so it cannot break out of the inline <script>', async () => {
const { server } = makeServer({});
const html = await render(server, 'a</script><b>');
@@ -358,6 +368,7 @@ describe('WebServer.renderIndexHtml', () => {
order: number;
kind: string;
external: boolean;
transcript?: string;
enabled: boolean;
available: boolean;
}>;
@@ -366,6 +377,7 @@ describe('WebServer.renderIndexHtml', () => {
label: 'Codex',
kind: 'agent',
external: true,
transcript: 'codex-rollout',
});
// claude is `kind: 'agent'` too; `external` is what keeps its Respawn/Ralph options visible.
expect(catalog.find((entry) => entry.id === 'claude')).toMatchObject({ kind: 'agent', external: false });
@@ -373,7 +385,7 @@ describe('WebServer.renderIndexHtml', () => {
expect(
catalog.every((entry) =>
Object.keys(entry).every((key) =>
['id', 'label', 'shortBadge', 'order', 'kind', 'external', 'enabled', 'available'].includes(key)
['id', 'label', 'shortBadge', 'order', 'kind', 'external', 'transcript', 'enabled', 'available'].includes(key)
)
)
).toBe(true);
+244 -3
View File
@@ -30,6 +30,8 @@ import { describe, expect, it, vi } from 'vitest';
const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>');
const { document, NodeFilter } = dom.window;
const fetchResponse = vi.fn();
function loadCodemanAppClass() {
const constants = readFileSync(resolve(import.meta.dirname, '../src/web/public/constants.js'), 'utf8');
const source = readFileSync(resolve(import.meta.dirname, '../src/web/public/app.js'), 'utf8');
@@ -42,14 +44,25 @@ function loadCodemanAppClass() {
clearTimeout,
requestAnimationFrame: vi.fn(),
HTMLCanvasElement: class HTMLCanvasElement {},
fetch: vi.fn(),
fetch: fetchResponse,
document,
NodeFilter,
marked,
localStorage: { length: 0, key: vi.fn(), getItem: vi.fn(), setItem: vi.fn(), removeItem: vi.fn() },
window: { addEventListener: vi.fn(), removeEventListener: vi.fn() },
window: {
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
__codemanCliCatalog: [{ id: 'custom-codex', transcript: 'codex-rollout' }],
},
MobileDetection: {},
});
vm.runInContext(`${constants}\n${source}\nglobalThis.__CodemanApp = CodemanApp;`, context);
const terminalUi = readFileSync(resolve(import.meta.dirname, '../src/web/public/terminal-ui.js'), 'utf8');
const addEventListener = vi.spyOn(document, 'addEventListener').mockImplementation(() => {});
try {
vm.runInContext(`${constants}\n${source}\n${terminalUi}\nglobalThis.__CodemanApp = CodemanApp;`, context);
} finally {
addEventListener.mockRestore();
}
return (context as { __CodemanApp: { prototype: { _linkifyFilePaths(root: unknown): void } } }).__CodemanApp;
}
@@ -341,3 +354,231 @@ describe('response viewer file-path linkifier', () => {
expect(APP_SOURCE).toMatch(/openFilePreview\(target \|\| filePath, sessionId\)/);
});
});
describe('Codex response files', () => {
it('lists previewable files once and opens their encoded URI in the originating session', () => {
const app = Object.create(CodemanApp.prototype);
app._sanitizeHtml = (html: string) => html;
app.openFilePreview = vi.fn();
app.activeSessionId = 'another-session';
app.sessions = new Map([['codex-session', { workingDir: '/work/project', paneCwd: '/work/project/live' }]]);
const body = document.createElement('div');
app._renderResponseFiles(
body,
[
'[Word brief](</work/project/Brief %231.docx>)\n\n[Image](out/image.png)',
'[Duplicate](/work/project/live/out/image.png) [PDF](file:///work/project/Export%20one.pdf)',
'[Web](https://example.com/x.pdf) [Network](file://remote/share/x.pdf) [Code](src/app.ts)',
],
'codex-session'
);
const links = Array.from(body.querySelectorAll('button'));
expect(links.map((link) => link.textContent)).toEqual(['Word brief', 'Image', 'PDF']);
// Buttons, not <a href="#">: under <base href> a middle-click on "#" opened the app root.
expect(body.querySelector('a')).toBeNull();
expect(links.every((link) => link.type === 'button')).toBe(true);
expect(app.openFilePreview).not.toHaveBeenCalled();
for (const link of links) link.click();
expect(app.openFilePreview.mock.calls).toEqual([
['/work/project/Brief #1.docx', 'codex-session', null, { dock: true }],
['/work/project/live/out/image.png', 'codex-session', null, { dock: true }],
['/work/project/Export one.pdf', 'codex-session', null, { dock: true }],
]);
});
it('shows an empty state when the response contains no previewable files', () => {
const app = Object.create(CodemanApp.prototype);
app._renderMarkdown = renderChat;
const body = document.createElement('div');
app._renderResponseFiles(body, ['No files in this response.'], 'codex-session');
expect(body.textContent).toBe('No previewable files in the latest response.');
});
});
describe('Codex terminal response link matching', () => {
function appForTranscript() {
const app = Object.create(CodemanApp.prototype);
app._sanitizeHtml = (html: string) => html;
app.sessions = new Map([['codex-session', { workingDir: '/work/project', paneCwd: '/work/project/live' }]]);
return app;
}
it('uses the explicit destination behind an underlined label', () => {
const app = appForTranscript();
const session = 'codex-session';
expect(
app._findCodexResponseFile(
[
{ role: 'assistant', text: 'See [Word brief](<out/Word draft.docx>).' },
{ role: 'assistant', text: 'Repeated [Word brief](file:///work/project/live/out/Word%20draft.docx).' },
],
'Word brief',
session
)
).toBe('/work/project/live/out/Word draft.docx');
});
it('resolves a native sidebar filename only when its destination is unique', () => {
const app = appForTranscript();
const session = 'codex-session';
const message = { role: 'assistant', text: '[Preview image](file:///work/project/Image%20draft.png)' };
expect(app._findCodexResponseFile([message], 'Image draft.png', session, true)).toBe(
'/work/project/Image draft.png'
);
expect(
app._findCodexResponseFile(
[
message,
{
role: 'assistant',
text: '[Other](<out/Image draft.png>)',
},
],
'Image draft.png',
session,
true
)
).toBeNull();
});
it('renders only potential sidebar matches, including URI-encoded filenames', () => {
const app = appForTranscript();
const render = vi.spyOn(app, '_renderMarkdown');
const texts = [
'Unrelated message.',
'Only a prefix: Word',
'Only an extension: .docx',
'[Download](file:///work/Word%20draft.docx)',
];
const messages = texts.map((text) => ({ role: 'assistant', text }));
expect(app._findCodexResponseFile(messages, 'Word…draft.docx', 'codex-session', true)).toBe(
'/work/Word draft.docx'
);
expect(render).toHaveBeenCalledExactlyOnceWith(texts[3], { localFileLinks: true });
});
it('resolves an abbreviated native tab only when one path matches both visible ends', () => {
const app = appForTranscript();
const session = 'codex-session';
const name = 'Interview panel plan - requisition 2026943.docx';
const exact = { role: 'assistant', text: `[Download](<out/${name}>)` };
const near = { role: 'assistant', text: '[Wrong extension](<out/Interview draft 2026943.pdf>)' };
const label = 'Interview…26943.docx';
expect(app._findCodexResponseFile([exact, near], label, session, true)).toBe(`/work/project/live/out/${name}`);
expect(
app._findCodexResponseFile(
[
exact,
{
role: 'assistant',
text: '[Another draft](<other/Interview alternate 2026943.docx>)',
},
],
label,
session,
true
)
).toBeNull();
});
it.each([
'[Word brief](out/different.docx)',
'[Word brief](https://example.test/report.docx)',
'[Word brief](src/script.ts)',
])('declines an ambiguous label when another reference is %s', (other) => {
const app = appForTranscript();
expect(
app._findCodexResponseFile(
[
{ role: 'assistant', text: '[Word brief](out/report.docx)' },
{ role: 'assistant', text: other },
],
'Word brief',
'codex-session'
)
).toBeNull();
});
});
describe('response viewer modes', () => {
function setup(mode: string) {
document.body.innerHTML = `<div id="responseViewerBackdrop"></div><div id="responseViewer">
<h2 id="responseViewerTitle"></h2><button id="responseViewerMore" style="display:none"></button>
<div id="responseViewerBody"></div></div>`;
const app = Object.create(CodemanApp.prototype);
app.activeSessionId = 'session';
app.sessions = new Map([['session', { mode, workingDir: '/work', paneCwd: '/work/live' }]]);
app._sanitizeHtml = (html: string) => html;
app._buildResponseViewerMessage = () => document.createElement('div');
app._bindResponseViewerInteractions = vi.fn();
app.openFilePreview = vi.fn();
app.terminal = { focus: vi.fn() };
const focused = { focus: vi.fn() };
app._focusedPane = () => ({ terminal: focused });
app._shouldFocusTerminalForTabSwitch = () => true;
app._codexFilePreviewsEnabled = () => true;
fetchResponse.mockReset().mockResolvedValue({
ok: true,
json: async () => ({ data: { text: '[Plan](out/plan.docx)' } }),
});
return { app, focused };
}
it('restores More for a normal response without hasContext', async () => {
const { app } = setup('claude');
await app.toggleResponseViewer();
expect(document.querySelector<HTMLElement>('#responseViewerMore')?.style.display).toBe('');
});
it('opens the file picker for a registered rollout reader and returns focus to the originating pane', async () => {
const { app, focused } = setup('custom-codex');
await app.toggleResponseViewer(true);
expect(document.getElementById('responseViewer')?.dataset.filesOnly).toBe('true');
expect(document.getElementById('responseViewerTitle')?.textContent).toBe('Response files');
document.querySelector<HTMLButtonElement>('#responseViewerBody button')?.click();
expect(app.openFilePreview).toHaveBeenCalledWith('/work/live/out/plan.docx', 'session', null, { dock: true });
expect(focused.focus).toHaveBeenCalledOnce();
expect(app.terminal.focus).not.toHaveBeenCalled();
});
it('does not open the file picker while the Codex files setting is off', async () => {
const { app } = setup('custom-codex');
delete app._codexFilePreviewsEnabled; // the real reader: the device settings, default OFF
app.loadAppSettingsFromStorage = () => ({});
app.getDefaultSettings = () => ({});
expect(app._codexFilePreviewsEnabled()).toBe(false);
await app.toggleResponseViewer(true);
expect(fetchResponse).not.toHaveBeenCalled();
expect(document.getElementById('responseViewer')?.classList.contains('visible')).toBe(false);
});
it('hides the Response files button while the setting is off, even in a Codex session', () => {
const { app } = setup('custom-codex');
document.body.insertAdjacentHTML(
'beforeend',
'<button id="responseFilesBtn" class="btn-icon-header btn-response-files btn-response-files--hidden" hidden></button>'
);
const button = document.getElementById('responseFilesBtn')!;
app._codexFilePreviewsEnabled = () => false;
app._syncResponseFilesButton();
expect(button.classList.contains('btn-response-files--hidden')).toBe(true);
app._codexFilePreviewsEnabled = () => true;
app._syncResponseFilesButton();
expect(button.classList.contains('btn-response-files--hidden')).toBe(false);
expect(button.hidden).toBe(false);
app.activeSessionId = 'claude-session';
app._syncResponseFilesButton();
expect(button.hidden).toBe(true); // the setting alone never shows it outside a Codex session
});
it('closes the file picker without focusing an xterm when the keyboard is hidden', async () => {
const { app, focused } = setup('custom-codex');
app._shouldFocusTerminalForTabSwitch = () => false;
await app.toggleResponseViewer(true);
expect(app.closeResponseViewer()).toBe(true);
expect(focused.focus).not.toHaveBeenCalled();
expect(app.terminal.focus).not.toHaveBeenCalled();
});
});
+86
View File
@@ -0,0 +1,86 @@
/**
* @fileoverview Table columns in rendered markdown never shrink below a readable width
* (src/web/public/styles.css).
*
* Rendered markdown sets `overflow-wrap: anywhere` so that a long path in prose wraps, and
* table cells inherited it. `anywhere` also counts every letter as a break point when the
* browser computes a cell's minimum width, and the header cells never wrap. In a table
* whose headers filled the width, the column under an empty header shrank to one letter per
* line. Cells now use `break-word`, so a column is never narrower than its longest word.
*
* Under `break-word`, a token with no break point sets its column's width. Chromium never
* breaks after `/`, so a URL, an identifier or a hash in backticks made the whole table
* scroll sideways on a phone. Inline code and links in a cell therefore break anywhere,
* like a linkified path (`a.rv-path`, `word-break: break-all`) always did. That lets their
* column shrink the same way, so a cell holding one gets a minimum width.
*
* jsdom has no layout, so this pins the declarations. Firefox and Chromium were measured
* when the change was made, in a 360 px column: URL, identifier and hash tables fit as they
* did on master, a path column went from 48 px to 80 px, and a `-v` column from 52 px to
* 80 px.
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
const publicCss = (name: string) =>
readFileSync(resolve(import.meta.dirname, '../src/web/public', name), 'utf8').replace(/\/\*[\s\S]*?\*\//g, '');
/** The selectors of a rule, split on the commas outside `:is()`, `:has()` and `:not()`. */
function selectorList(prelude: string): string[] {
const parts: string[] = [];
let depth = 0;
let start = 0;
for (let i = 0; i < prelude.length; i++) {
if (prelude[i] === '(') depth++;
else if (prelude[i] === ')') depth--;
else if (prelude[i] === ',' && depth === 0) {
parts.push(prelude.slice(start, i).trim());
start = i + 1;
}
}
parts.push(prelude.slice(start).trim());
return parts;
}
/** Every rule whose selector list contains `selector`, in cascade order across both sheets. */
function rulesFor(selector: string): string[] {
const bodies: string[] = [];
for (const css of [publicCss('styles.css'), publicCss('mobile.css')]) {
for (const match of css.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
if (selectorList(match[1]).includes(selector)) bodies.push(match[2]);
}
}
return bodies;
}
/** The value the last rule naming `selector` gives `property`, or undefined. */
function lastValue(selector: string, property: string): string | undefined {
let value: string | undefined;
for (const body of rulesFor(selector)) {
for (const decl of body.split(';')) {
const [name, ...rest] = decl.split(':');
if (name.trim() === property) value = rest.join(':').trim();
}
}
return value;
}
describe('rendered markdown table cells', () => {
it('still wraps long words in prose anywhere', () => {
expect(lastValue('.rv-text', 'overflow-wrap')).toBe('anywhere');
});
it.each(['.rv-text td', '.rv-text th', '.rv-table-wrap td', '.rv-table-wrap th'])(
'%s wraps between words, so its column is never narrower than its longest word',
(selector) => {
expect(lastValue(selector, 'overflow-wrap')).toBe('break-word');
}
);
it('breaks inline code and links in a cell anywhere, and gives their cell a minimum width', () => {
expect(lastValue('.rv-text a.rv-path', 'word-break')).toBe('break-all');
expect(lastValue('.rv-table-wrap td :is(code, a:not(.rv-path-link))', 'overflow-wrap')).toBe('anywhere');
expect(lastValue('.rv-table-wrap td:has(code, a:not(.rv-path-link))', 'min-width')).toBe('6em');
});
});
+430
View File
@@ -0,0 +1,430 @@
/**
* @fileoverview A Codeman server that runs as root (uid 0) starts local Claude sessions
* without the permission bypass.
*
* Claude Code exits on `--dangerously-skip-permissions` under uid 0 ("cannot be used with
* root/sudo privileges for security reasons"). That flag is the default permission mode, so
* a server installed and started as root (a VPS, an LXC container) showed a dead pane for
* every local Claude session. Measured 2026-11-27 with the public installer in a fresh
* `ubuntu:24.04` container.
*
* What is pinned here:
* - the pure rule (`applyRootValues`) and the registry data it reads (`rootValue`);
* - the uid helper is hermetic under vitest and only a stub makes it say "root";
* - under uid 0 the LOCAL command lines (tmux fresh + resume, direct PTY, one-shot) carry
* no bypass flag, and say so in one log line;
* - under any other uid every command line is byte-identical to the golden pins;
* - `auto`, `allowedTools` and `normal` are untouched under root;
* - remote and Docker pane commands never read the server's uid.
*
* Port: none (pure functions over registry data).
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
import { applyRootValues, describeRootValueChanges } from '../src/config/cli-registry/root-launch.js';
import { getCli } from '../src/config/cli-registry/registry.js';
import { STOCK_CLIS } from '../src/config/cli-registry/stock.js';
import { DEFAULT_AGENT_IMAGE, defaultDockerCommandForMode, toSessionDocker } from '../src/docker-hosts.js';
import { buildInteractiveArgs, buildPromptArgs, directLaunchClaudeMode } from '../src/session-cli-builder.js';
import { buildSpawnCommandFromRegistry } from '../src/session-cli-registry-bridge.js';
import {
buildDockerLaunchCommand,
buildRemoteLaunchCommand,
buildSpawnCommand,
serverRootSpawnOptions,
type DockerLaunchOptions,
} from '../src/tmux-manager.js';
import type { ClaudeMode, DockerCase, DockerHost, SessionMode, SessionRemote } from '../src/types.js';
import { serverRunsAsRoot, stubServerUidForTest } from '../src/utils/server-uid.js';
const SID = '0f9c2b14-1111-2222-3333-444455556666';
const BYPASS = '--dangerously-skip-permissions';
/** The golden pins of test/cli-registry-spawn-golden.test.ts, restated: the command lines of a launch that is not root. */
const GOLDEN_FRESH = `claude ${BYPASS} --session-id "${SID}"`;
const GOLDEN_RESUME = `claude ${BYPASS} --resume "abc-123-def" || claude ${BYPASS} --session-id "${SID}"`;
function claudeLaunch() {
const entry = getCli('claude');
if (!entry) throw new Error('no claude entry');
return entry.launch;
}
/** The local tmux pane command, built the way `createSession` and `respawnPane` build it. */
function localCommand(extra: Partial<Parameters<typeof buildSpawnCommand>[0]> = {}, launchedElsewhere = false): string {
const mode = (extra.mode ?? 'claude') as SessionMode;
return buildSpawnCommand({
mode,
sessionId: SID,
claudeCliVersion: null,
...extra,
...serverRootSpawnOptions({ mode, sessionId: SID, launchedElsewhere }),
});
}
afterEach(() => {
stubServerUidForTest(null);
vi.restoreAllMocks();
});
describe('serverRunsAsRoot', () => {
it('never reads the real uid under vitest, so the suite is the same when run as root', () => {
const getuid = vi.spyOn(process, 'getuid').mockReturnValue(0);
expect(serverRunsAsRoot()).toBe(false);
expect(getuid).not.toHaveBeenCalled();
});
it('answers from the stubbed uid, asked again on every call', () => {
stubServerUidForTest(0);
expect(serverRunsAsRoot()).toBe(true);
stubServerUidForTest(1000);
expect(serverRunsAsRoot()).toBe(false);
// A platform with no uid at all (process.getuid is absent on Windows).
stubServerUidForTest(undefined);
expect(serverRunsAsRoot()).toBe(false);
stubServerUidForTest(null);
expect(serverRunsAsRoot()).toBe(false);
});
});
describe('the registry data', () => {
it('declares the swap on the claude permission mode, and on nothing else', () => {
const declared = STOCK_CLIS.flatMap((entry) =>
Object.entries(entry.launch.params).flatMap(([param, spec]) =>
spec.type === 'enum' && spec.rootValue ? [{ cli: entry.id as string, param, rootValue: spec.rootValue }] : []
)
);
// A new line here is a decision about what another CLI does under root, to be measured first.
expect(declared).toEqual([
{ cli: 'claude', param: 'claudeMode', rootValue: { 'dangerously-skip-permissions': 'normal' } },
]);
});
});
describe('applyRootValues', () => {
it('hands back the very object it was given when the launch is not root', () => {
const params = { claudeMode: 'dangerously-skip-permissions' };
const result = applyRootValues(claudeLaunch(), params, false);
expect(result.params).toBe(params);
expect(result.changes).toEqual([]);
});
it('swaps the bypass mode for normal under root, whether it was sent or is the default', () => {
for (const params of [{}, { claudeMode: 'dangerously-skip-permissions' }, { claudeMode: 'no-such-mode' }]) {
const before = { ...params };
const result = applyRootValues(claudeLaunch(), params, true);
expect(result.params.claudeMode).toBe('normal');
expect(result.changes).toEqual([{ param: 'claudeMode', from: 'dangerously-skip-permissions', to: 'normal' }]);
expect(params, 'the caller object is never mutated').toEqual(before);
}
});
it('leaves every other mode alone under root', () => {
for (const claudeMode of ['auto', 'allowedTools', 'normal']) {
const params = { claudeMode, allowedTools: 'Read' };
const result = applyRootValues(claudeLaunch(), params, true);
expect(result.params, claudeMode).toBe(params);
expect(result.changes, claudeMode).toEqual([]);
}
});
it('keeps the other params of a launch it changes', () => {
const result = applyRootValues(claudeLaunch(), { model: 'opus', resumeId: 'abc-123-def' }, true);
expect(result.params).toEqual({ model: 'opus', resumeId: 'abc-123-def', claudeMode: 'normal' });
});
it('does nothing for a launch spec that declares no rootValue', () => {
const codex = getCli('codex');
if (!codex) throw new Error('no codex entry');
const params = { dangerouslyBypassApprovals: true };
expect(applyRootValues(codex.launch, params, true).params).toBe(params);
});
it('ignores a replacement the param does not declare (a hand-built spec the schema never saw)', () => {
const launch = {
params: { m: { type: 'enum' as const, values: ['a', 'b'], default: 'a', rootValue: { a: 'zzz' } } },
variants: [{ id: 'new', args: [] }],
};
const params = {};
const result = applyRootValues(launch, params, true);
expect(result.params).toBe(params);
expect(result.changes).toEqual([]);
});
it('describes the swap in one line that names the cause and the way out', () => {
const line = describeRootValueChanges('Claude Code session 0f9c2b14', [
{ param: 'claudeMode', from: 'dangerously-skip-permissions', to: 'normal' },
]);
expect(line).toContain('Claude Code session 0f9c2b14');
expect(line).toContain('claudeMode "dangerously-skip-permissions" as "normal"');
expect(line).toContain('runs as root (uid 0)');
expect(line).toContain('normal user');
expect(line).not.toContain('\n');
});
});
describe('the local tmux pane command under a server that runs as root', () => {
it('starts a fresh session without the bypass flag', () => {
stubServerUidForTest(0);
vi.spyOn(console, 'warn').mockImplementation(() => {});
expect(localCommand()).toBe(`claude --session-id "${SID}"`);
expect(localCommand({ claudeMode: 'dangerously-skip-permissions' })).toBe(`claude --session-id "${SID}"`);
});
it('drops the flag from BOTH halves of the resume fallback', () => {
stubServerUidForTest(0);
vi.spyOn(console, 'warn').mockImplementation(() => {});
const command = localCommand({ resumeSessionId: 'abc-123-def' });
expect(command).toBe(`claude --resume "abc-123-def" || claude --session-id "${SID}"`);
expect(command).not.toContain(BYPASS);
});
it('is exactly the command an explicit normal mode gives, with every other flag kept', () => {
stubServerUidForTest(0);
vi.spyOn(console, 'warn').mockImplementation(() => {});
const rest = {
model: 'opus[1m]',
effort: 'max' as const,
advisorModel: 'opus',
sessionName: 'w3-myapp',
claudeCliVersion: '2.1.300',
resumeSessionId: 'abc-123-def',
statusLineCommand: '/tmp/exporter.sh',
};
const underRoot = localCommand(rest);
stubServerUidForTest(1000);
expect(underRoot).toBe(localCommand({ ...rest, claudeMode: 'normal' }));
expect(underRoot).toContain('--model "opus[1m]"');
expect(underRoot).toContain("--effort 'max'");
expect(underRoot).toContain('--name "w3-myapp"');
});
it('says so in one log line per launch', () => {
stubServerUidForTest(0);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
localCommand();
expect(warn).toHaveBeenCalledTimes(1);
const line = String(warn.mock.calls[0][0]);
expect(line).toMatch(/^\[TmuxManager\] Claude Code session 0f9c2b14 /);
expect(line).toContain('claudeMode "dangerously-skip-permissions" as "normal"');
expect(line).toContain('runs as root (uid 0)');
localCommand({ resumeSessionId: 'abc-123-def' });
expect(warn).toHaveBeenCalledTimes(2);
});
it('leaves auto, allowedTools and normal exactly as they are, and logs nothing', () => {
const cases: Array<{ claudeMode: ClaudeMode; allowedTools?: string }> = [
{ claudeMode: 'auto' },
{ claudeMode: 'allowedTools', allowedTools: 'Bash(git:*), Read' },
{ claudeMode: 'allowedTools' },
{ claudeMode: 'normal' },
];
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
for (const options of cases) {
stubServerUidForTest(1000);
const asUser = localCommand(options);
const resumedAsUser = localCommand({ ...options, resumeSessionId: 'abc-123-def' });
stubServerUidForTest(0);
expect(localCommand(options), options.claudeMode).toBe(asUser);
expect(localCommand({ ...options, resumeSessionId: 'abc-123-def' }), options.claudeMode).toBe(resumedAsUser);
}
expect(warn).not.toHaveBeenCalled();
stubServerUidForTest(0);
expect(localCommand({ claudeMode: 'auto' })).toBe(`claude --permission-mode auto --session-id "${SID}"`);
expect(localCommand({ claudeMode: 'allowedTools', allowedTools: 'Bash(git:*), Read' })).toBe(
`claude --allowedTools "Bash(git:*), Read" --session-id "${SID}"`
);
});
it('renders every CLI that declares no rootValue the same as for a normal user', () => {
const untouched = STOCK_CLIS.filter(
(entry) => !Object.values(entry.launch.params).some((spec) => spec.type === 'enum' && spec.rootValue)
).map((entry) => entry.id as SessionMode);
expect(untouched.length).toBeGreaterThanOrEqual(10);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
for (const mode of untouched) {
// Each CLI's own bypass switch is on, so a swap that leaked to another entry would show.
const options = {
mode,
codexConfig: { dangerouslyBypassApprovals: true },
antigravityConfig: { dangerouslySkipPermissions: true },
geminiConfig: { approvalMode: 'yolo' as const },
grokConfig: { alwaysApprove: true },
copilotConfig: { allowAll: true },
};
stubServerUidForTest(1000);
const asUser = localCommand(options);
stubServerUidForTest(0);
expect(localCommand(options), mode).toBe(asUser);
}
expect(warn).not.toHaveBeenCalled();
});
});
describe('the local tmux pane command under any other uid', () => {
it('adds nothing to the launch options, so the command is byte-identical', () => {
for (const uid of [1000, 501, 1, undefined]) {
stubServerUidForTest(uid);
expect(serverRootSpawnOptions({ mode: 'claude', sessionId: SID, launchedElsewhere: false })).toEqual({});
expect(localCommand()).toBe(GOLDEN_FRESH);
expect(localCommand({ resumeSessionId: 'abc-123-def' })).toBe(GOLDEN_RESUME);
}
});
it('is unchanged without a stub too (the hermetic default)', () => {
expect(localCommand()).toBe(GOLDEN_FRESH);
expect(localCommand({ resumeSessionId: 'abc-123-def' })).toBe(GOLDEN_RESUME);
});
it('never swaps on the bridge unless the caller said the launch runs as root', () => {
// The bridge also renders commands that run under another account (the remote omp
// relaunch), so it must not ask for the uid itself.
stubServerUidForTest(0);
const entry = getCli('claude');
if (!entry) throw new Error('no claude entry');
const onRootValue = vi.fn();
expect(
buildSpawnCommandFromRegistry(entry, { mode: 'claude', sessionId: SID, claudeCliVersion: null, onRootValue })
).toBe(GOLDEN_FRESH);
expect(onRootValue).not.toHaveBeenCalled();
expect(
buildSpawnCommandFromRegistry(entry, {
mode: 'claude',
sessionId: SID,
claudeCliVersion: null,
runsAsServerRoot: true,
onRootValue,
})
).toBe(`claude --session-id "${SID}"`);
expect(onRootValue).toHaveBeenCalledTimes(1);
});
});
describe('remote and Docker launches', () => {
const remote: SessionRemote = {
hostId: 'gpu-box',
label: 'GPU Box',
host: '10.0.0.42',
username: 'ubuntu',
remotePath: '/home/ubuntu/work',
};
const HOST: DockerHost = { id: 'local', label: 'Local', image: DEFAULT_AGENT_IMAGE };
const CASE: DockerCase = {
name: 'myproj',
type: 'docker',
hostId: 'local',
hostWorkspacePath: '/home/user/cases/myproj',
};
function dockerOpts(runsAsRoot?: boolean): DockerLaunchOptions {
const docker = { ...toSessionDocker(HOST, CASE), ...(runsAsRoot === undefined ? {} : { runsAsRoot }) };
return {
mode: 'claude',
docker,
sessionId: '1a2b3c4d5e6f',
createContext: {
docker,
sessionId: '1a2b3c4d5e6f',
instance: '',
userArgs: ['--user', '1000:0'],
credentialMounts: [],
extraMounts: [],
envCreate: { HOME: '/home/agent' },
addHostGateway: true,
gatewayAlias: 'host.docker.internal',
},
execEnv: { TERM: 'xterm-256color', CODEMAN_SESSION_ID: '1a2b3c4d', CODEMAN_MUX: '1' },
execEnvNames: [],
};
}
it('add nothing to the launch options, whatever the server uid', () => {
stubServerUidForTest(0);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
expect(serverRootSpawnOptions({ mode: 'claude', sessionId: SID, launchedElsewhere: true })).toEqual({});
// The local command built beside a remote or Docker launch is discarded; it must not log a swap that never ran.
expect(localCommand({}, true)).toBe(GOLDEN_FRESH);
expect(warn).not.toHaveBeenCalled();
});
it('keep the remote claude pane command, bypass flag included, under a root server', () => {
const build = (claudeMode?: ClaudeMode) =>
buildRemoteLaunchCommand({ mode: 'claude', remote, sessionId: SID, claudeMode });
stubServerUidForTest(1000);
const asUser = { fresh: build(), auto: build('auto'), normal: build('normal') };
stubServerUidForTest(0);
expect(build()).toBe(asUser.fresh);
expect(build('auto')).toBe(asUser.auto);
expect(build('normal')).toBe(asUser.normal);
expect(asUser.fresh).toContain(`claude ${BYPASS} --session-id ${SID}`);
expect(asUser.normal).not.toContain(BYPASS);
});
it('keep the Docker pane command: the CONTAINER uid decides there, not the server uid', () => {
stubServerUidForTest(1000);
const asUser = { user: buildDockerLaunchCommand(dockerOpts()), root: buildDockerLaunchCommand(dockerOpts(true)) };
stubServerUidForTest(0);
expect(buildDockerLaunchCommand(dockerOpts())).toBe(asUser.user);
expect(buildDockerLaunchCommand(dockerOpts(true))).toBe(asUser.root);
expect(asUser.user).toContain(BYPASS);
expect(asUser.root).not.toContain(BYPASS);
expect(defaultDockerCommandForMode('claude')).toBe(`exec claude ${BYPASS}`);
expect(defaultDockerCommandForMode('claude', true)).toBe('exec claude');
});
});
describe('claude processes the server starts directly (direct PTY fallback, one-shot)', () => {
it('carry no bypass flag under root, and log it', () => {
stubServerUidForTest(0);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
expect(buildInteractiveArgs(SID, 'dangerously-skip-permissions')).toEqual(['--session-id', SID]);
expect(buildPromptArgs('hello')).toEqual(['-p', '--verbose', '--output-format', 'stream-json', 'hello']);
expect(warn).toHaveBeenCalledTimes(2);
expect(String(warn.mock.calls[0][0])).toMatch(/^\[Session\] .*runs as root \(uid 0\)/);
});
it('are unchanged under any other uid', () => {
for (const uid of [1000, undefined, null]) {
stubServerUidForTest(uid);
expect(buildInteractiveArgs(SID, 'dangerously-skip-permissions')).toEqual([BYPASS, '--session-id', SID]);
expect(buildPromptArgs('hello')).toEqual(['-p', '--verbose', BYPASS, '--output-format', 'stream-json', 'hello']);
}
});
it('keep auto, allowedTools and normal under root', () => {
stubServerUidForTest(0);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
expect(buildInteractiveArgs(SID, 'auto')).toEqual(['--permission-mode', 'auto', '--session-id', SID]);
expect(buildInteractiveArgs(SID, 'allowedTools', undefined, 'Read')).toEqual([
'--allowedTools',
'Read',
'--session-id',
SID,
]);
expect(buildInteractiveArgs(SID, 'normal')).toEqual(['--session-id', SID]);
expect(buildPromptArgs('hello', undefined, 'auto')).toEqual([
'-p',
'--verbose',
'--permission-mode',
'auto',
'--output-format',
'stream-json',
'hello',
]);
expect(warn).not.toHaveBeenCalled();
});
it('directLaunchClaudeMode is pure: the caller says whether the server is root', () => {
const onChange = vi.fn();
expect(directLaunchClaudeMode('dangerously-skip-permissions', false, onChange)).toBe(
'dangerously-skip-permissions'
);
expect(onChange).not.toHaveBeenCalled();
expect(directLaunchClaudeMode('dangerously-skip-permissions', true, onChange)).toBe('normal');
expect(onChange).toHaveBeenCalledTimes(1);
for (const mode of ['auto', 'allowedTools', 'normal'] as const) {
expect(directLaunchClaudeMode(mode, true, onChange)).toBe(mode);
}
expect(onChange).toHaveBeenCalledTimes(1);
});
});
+21
View File
@@ -963,6 +963,27 @@ describe('file-routes', () => {
expect(res.headers['x-content-type-options']).toBe('nosniff');
});
it('serves an uploaded HTML page as inert octet-stream with nosniff, never as text/html', async () => {
// Prompt uploads admit .html/.htm as documents, so a page a user attached sits
// in the workspace. Reading it back must never run it on this origin: html has
// no entry in file-raw's MIME table, so it falls through to octet-stream, which
// a browser downloads, and nosniff stops it guessing text/html from the bytes.
for (const name of ['spec.html', 'report.htm']) {
const content = Buffer.from('<script>fetch("/api/sessions")</script>');
mockedCreateReadStream.mockReturnValue(Readable.from([content]) as never);
mockedStat.mockResolvedValue({ size: content.length } as never);
const res = await harness.app.inject({
method: 'GET',
url: `/api/sessions/${harness.ctx._sessionId}/file-raw?path=.codeman-uploads/paste-1-ab-${name}`,
});
expect(res.statusCode, name).toBe(200);
expect(res.headers['content-type'], name).toBe('application/octet-stream');
expect(res.headers['x-content-type-options'], name).toBe('nosniff');
}
});
it('rejects path traversal in raw file serving', async () => {
mockedRealpathSync.mockImplementation(
(p: string) => (p === harness.ctx._session.workingDir ? p : '/etc/shadow') as never
+4
View File
@@ -336,6 +336,10 @@ describe('html-view routes', () => {
writeFileSync(join(workspace, '.cache', 'r.html'), '<p>r</p>');
writeFileSync(join(workspace, '.cache', 'token.json'), '{}');
expect((await open(join(workspace, '.cache', 'r.html'))).statusCode).toBe(403);
// A page attached through a prompt upload lands here, and is never rendered.
mkdirSync(join(workspace, '.codeman-uploads'));
writeFileSync(join(workspace, '.codeman-uploads', 'paste-1-ab-spec.html'), '<p>spec</p>');
expect((await open(join(workspace, '.codeman-uploads', 'paste-1-ab-spec.html'))).statusCode).toBe(403);
mkdirSync(join(root, '.hidden'));
writeFileSync(join(root, '.hidden', 'r.html'), '<p>r</p>');
expect((await open(join(root, '.hidden', 'r.html'))).statusCode).toBe(403);
@@ -8,13 +8,15 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import Fastify, { type FastifyInstance } from 'fastify';
import fastifyCookie from '@fastify/cookie';
import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
import { mkdirSync, mkdtempSync, renameSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
import fsPromises from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
import { registerSessionRoutes } from '../../src/web/routes/session-routes.js';
import { ApiErrorCode, httpStatusForErrorCode } from '../../src/types.js';
import { createMockRouteContext, type MockRouteContext } from '../mocks/index.js';
import { KEEP_WARM_NUDGE } from '../../src/prompt-cache-keepwarm.js';
interface LocalHarness {
app: FastifyInstance;
@@ -239,6 +241,261 @@ describe('GET /api/sessions/:id/last-response (claude)', () => {
]);
});
it('starts a transcript watcher for the chat view when the session has none, and only then', async () => {
const sessionId = harness.ctx._session.id;
const session = harness.ctx._session as typeof harness.ctx._session & {
claudeSessionId: string;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
session.claudeSessionId = sessionId;
session.adoptClaudeSessionId = vi.fn();
writeTranscript(sessionId, [userEntry('Hi'), assistantEntry('Hello.', '2026-07-21T00:00:01Z')]);
const start = harness.ctx.startTranscriptWatcher as ReturnType<typeof vi.fn>;
const current = harness.ctx.getTranscriptPath as ReturnType<typeof vi.fn>;
// The brief view and agent pollers read without starting anything.
await getLastResponse(sessionId, false);
expect(start).not.toHaveBeenCalled();
await getLastResponse(sessionId, true);
expect(start).toHaveBeenCalledTimes(1);
expect(start.mock.calls[0][0]).toBe(sessionId);
expect(String(start.mock.calls[0][1])).toMatch(new RegExp(`${sessionId}\\.jsonl$`));
// A watcher already running (a hook reported its path) is left alone.
current.mockReturnValue('/some/path.jsonl');
await getLastResponse(sessionId, true);
expect(start).toHaveBeenCalledTimes(1);
});
it('moves a watcher it started itself to the new file after /clear', async () => {
const sessionId = harness.ctx._session.id;
const session = harness.ctx._session as typeof harness.ctx._session & {
claudeSessionId: string;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
session.claudeSessionId = sessionId;
session.adoptClaudeSessionId = vi.fn();
writeTranscript(sessionId, [userEntry('Hi'), assistantEntry('Hello.', '2026-07-21T00:00:01Z')]);
const start = harness.ctx.startTranscriptWatcher as ReturnType<typeof vi.fn>;
const current = harness.ctx.getTranscriptPath as ReturnType<typeof vi.fn>;
await getLastResponse(sessionId, true);
expect(start).toHaveBeenCalledTimes(1);
const fileA = String(start.mock.calls[0][1]);
current.mockReturnValue(fileA);
// The same file again: nothing to move.
await getLastResponse(sessionId, true);
expect(start).toHaveBeenCalledTimes(1);
// A /clear starts a new conversation file, and no hook moves the watcher onto it.
const clearedId = 'b0c1d2e3-0000-4000-8000-000000000001';
session.claudeSessionId = clearedId;
writeTranscript(clearedId, [userEntry('After clear'), assistantEntry('Fresh.', '2026-07-21T00:00:02Z')]);
await getLastResponse(sessionId, true);
expect(start).toHaveBeenCalledTimes(2);
expect(start.mock.calls[1][0]).toBe(sessionId);
expect(String(start.mock.calls[1][1])).toMatch(new RegExp(`${clearedId}\\.jsonl$`));
});
it('never moves a watcher whose path a hook set', async () => {
const sessionId = harness.ctx._session.id;
const session = harness.ctx._session as typeof harness.ctx._session & {
claudeSessionId: string;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
session.claudeSessionId = sessionId;
session.adoptClaudeSessionId = vi.fn();
writeTranscript(sessionId, [userEntry('Hi'), assistantEntry('Hello.', '2026-07-21T00:00:01Z')]);
const start = harness.ctx.startTranscriptWatcher as ReturnType<typeof vi.fn>;
const current = harness.ctx.getTranscriptPath as ReturnType<typeof vi.fn>;
// A hook started the watcher on a path this read never recorded.
current.mockReturnValue('/hook/reported.jsonl');
await getLastResponse(sessionId, true);
const clearedId = 'b0c1d2e3-0000-4000-8000-000000000002';
session.claudeSessionId = clearedId;
writeTranscript(clearedId, [userEntry('After clear'), assistantEntry('Fresh.', '2026-07-21T00:00:02Z')]);
await getLastResponse(sessionId, true);
expect(start).not.toHaveBeenCalled();
});
it('leaves a watcher it started alone once a hook moved it', async () => {
const sessionId = harness.ctx._session.id;
const session = harness.ctx._session as typeof harness.ctx._session & {
claudeSessionId: string;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
session.claudeSessionId = sessionId;
session.adoptClaudeSessionId = vi.fn();
writeTranscript(sessionId, [userEntry('Hi'), assistantEntry('Hello.', '2026-07-21T00:00:01Z')]);
const start = harness.ctx.startTranscriptWatcher as ReturnType<typeof vi.fn>;
const current = harness.ctx.getTranscriptPath as ReturnType<typeof vi.fn>;
// The read starts the watcher on transcript A.
current.mockReturnValue(null);
await getLastResponse(sessionId, true);
expect(start).toHaveBeenCalledTimes(1);
// A hook then moves it to B, and a /clear leaves the conversation in C.
current.mockReturnValue('/hook/moved.jsonl');
const clearedId = 'b0c1d2e3-0000-4000-8000-000000000003';
session.claudeSessionId = clearedId;
writeTranscript(clearedId, [userEntry('After clear'), assistantEntry('Fresh.', '2026-07-21T00:00:02Z')]);
await getLastResponse(sessionId, true);
expect(start).toHaveBeenCalledTimes(1);
// The read forgot its record, so a later read leaves the hook's watcher alone too.
await getLastResponse(sessionId, true);
expect(start).toHaveBeenCalledTimes(1);
// Even once the watcher is back on the path the read first recorded, and the conversation
// moved on to a new file: a read that still held its record would move the watcher there.
current.mockReturnValue(String(start.mock.calls[0][1]));
const laterId = 'b0c1d2e3-0000-4000-8000-000000000004';
session.claudeSessionId = laterId;
writeTranscript(laterId, [userEntry('Later'), assistantEntry('Later still.', '2026-07-21T00:00:03Z')]);
await getLastResponse(sessionId, true);
expect(start).toHaveBeenCalledTimes(1);
});
it('starts no transcript watcher for a session removed while the read was in flight', async () => {
const sessionId = harness.ctx._session.id;
const session = harness.ctx._session as typeof harness.ctx._session & {
claudeSessionId: string;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
session.claudeSessionId = sessionId;
session.adoptClaudeSessionId = vi.fn();
writeTranscript(sessionId, [userEntry('Hi'), assistantEntry('Hello.', '2026-07-21T00:00:01Z')]);
const start = harness.ctx.startTranscriptWatcher as ReturnType<typeof vi.fn>;
// A delete or detach between the route's lookup and the transcript scan leaves the
// session out of the server's map; nothing would ever stop a watcher started for it.
harness.ctx.sessions.delete(sessionId);
const result = await harness.ctx.lastResponseFor!(session as never, 'full');
expect(start).not.toHaveBeenCalled();
expect((result as { messages?: unknown[] }).messages?.length).toBeGreaterThan(0);
});
it('remembers where a transcript was found, and scans again once the file moved', async () => {
const sessionId = harness.ctx._session.id;
const session = harness.ctx._session as typeof harness.ctx._session & {
claudeSessionId: string;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
session.claudeSessionId = sessionId;
session.adoptClaudeSessionId = vi.fn();
writeTranscript(sessionId, [userEntry('Hi'), assistantEntry('Hello.', '2026-07-21T00:00:01Z')]);
const projectsDir = join(testHome, '.claude', 'projects');
const readdir = vi.spyOn(fsPromises, 'readdir');
const projectScans = () => readdir.mock.calls.filter((call) => String(call[0]) === projectsDir).length;
try {
await getLastResponse(sessionId, true);
expect(projectScans()).toBe(1);
const second = await getLastResponse(sessionId, true);
expect(projectScans()).toBe(1);
expect(second.body.data.text).toBe('Hello.');
// The file moves to another project folder: the remembered path fails, the scan finds it.
const movedDir = join(projectsDir, '-elsewhere');
mkdirSync(movedDir, { recursive: true });
renameSync(join(projectsDir, '-workspace', `${sessionId}.jsonl`), join(movedDir, `${sessionId}.jsonl`));
const third = await getLastResponse(sessionId, true);
expect(projectScans()).toBe(2);
expect(third.body.data.text).toBe('Hello.');
} finally {
readdir.mockRestore();
}
});
it("marks Codeman's keep-warm turns so the chat view can leave them out", async () => {
const sessionId = harness.ctx._session.id;
const session = harness.ctx._session as typeof harness.ctx._session & {
claudeSessionId: string;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
session.claudeSessionId = sessionId;
session.adoptClaudeSessionId = vi.fn();
writeTranscript(sessionId, [
userEntry('Fix the bug'),
assistantEntry('Fixed.', '2026-07-21T00:00:01Z'),
userEntry(KEEP_WARM_NUDGE),
assistantEntry('ok', '2026-07-21T00:00:02Z'),
userEntry('Thanks'),
assistantEntry('You are welcome.', '2026-07-21T00:00:03Z'),
]);
const { body } = await getLastResponse(sessionId, true);
expect(
body.data.messages.map((message: { role: string; text: string; keepAlive?: boolean }) => [
message.role,
message.text,
message.keepAlive === true,
])
).toEqual([
['user', 'Fix the bug', false],
['assistant', 'Fixed.', false],
['user', KEEP_WARM_NUDGE, true],
['assistant', 'ok', true],
['user', 'Thanks', false],
['assistant', 'You are welcome.', false],
]);
});
it('keeps a prompt the user queued during a keep-warm turn, and the answer to it', async () => {
const sessionId = harness.ctx._session.id;
const session = harness.ctx._session as typeof harness.ctx._session & {
claudeSessionId: string;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
session.claudeSessionId = sessionId;
session.adoptClaudeSessionId = vi.fn();
writeTranscript(sessionId, [
userEntry(KEEP_WARM_NUDGE),
queuedEntry('Also run the tests', '2026-07-21T00:00:01Z'),
assistantEntry('ok. Tests pass.', '2026-07-21T00:00:02Z'),
]);
const { body } = await getLastResponse(sessionId, true);
expect(
body.data.messages.map((message: { text: string; keepAlive?: boolean }) => [
message.text,
message.keepAlive === true,
])
).toEqual([
[KEEP_WARM_NUDGE, true],
['Also run the tests', false],
['ok. Tests pass.', false],
]);
});
it('opens a keep-warm turn of its own after a turn that ended without assistant text', async () => {
const sessionId = harness.ctx._session.id;
const session = harness.ctx._session as typeof harness.ctx._session & {
claudeSessionId: string;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
session.claudeSessionId = sessionId;
session.adoptClaudeSessionId = vi.fn();
writeTranscript(sessionId, [
userEntry('Fix the bug'),
{ type: 'assistant', message: { content: [{ type: 'tool_use', id: 'tool-1' }] } },
userEntry(KEEP_WARM_NUDGE),
assistantEntry('ok', '2026-07-21T00:00:02Z'),
]);
const { body } = await getLastResponse(sessionId, true);
const messages = body.data.messages as Array<{ role: string; text: string; turn: number; keepAlive?: boolean }>;
const prompt = messages.find((message) => message.text === 'Fix the bug');
const reply = messages.find((message) => message.text === 'ok');
expect(prompt?.keepAlive).toBeUndefined();
expect(reply?.keepAlive).toBe(true);
expect(reply?.turn).not.toBe(prompt?.turn);
});
/**
* A prompt typed while Claude is working is absorbed mid-turn and recorded
* ONLY as an attachment row — 160 of the 347 user cards across a real
@@ -727,7 +984,7 @@ describe('GET /api/sessions/:id/last-response (relocated Claude config folder, #
expect(pane.adoptClaudeSessionId).toHaveBeenCalledWith('after-clear');
});
it("keeps a Docker session off its override, which names a folder inside the container", async () => {
it('keeps a Docker session off its override, which names a folder inside the container', async () => {
const home = join(testHome, '.claude');
writeTranscript(home, 'conversation-a', 'what the host folder holds');
writeTranscript(relocated, 'conversation-a', 'a host folder that only shares the path');
+5 -2
View File
@@ -807,6 +807,9 @@ describe('session-routes', () => {
['todo.md', 'text/markdown', Buffer.from('# héllo\n- [ ] one\n'), /-todo\.md$/],
['data.csv', 'application/octet-stream', Buffer.from('a,b\n1,2\n'), /-data\.csv$/],
['archive.zip', 'application/zip', zip, /-archive\.zip$/],
// An AI-written spec or report exported as HTML is context, like a .md.
['spec.html', 'text/html', Buffer.from('<!doctype html><h1>Spéc</h1>\n'), /-spec\.html$/],
['report.HTM', 'application/octet-stream', Buffer.from('<p>report</p>\n'), /-report\.htm$/],
] as const) {
const res = await upload(name, mime, bytes);
expect(res.statusCode, name).toBe(200);
@@ -830,12 +833,12 @@ describe('session-routes', () => {
await rm(workDir, { recursive: true });
});
it('refuses a script or an HTML page by name, with a message that says so', async () => {
it('refuses a script by name, with a message that says so', async () => {
const workDir = await mkdtemp(join(tmpdir(), 'codeman-doc-'));
harness.ctx._session.workingDir = workDir;
for (const [name, mime] of [
['run.sh', 'text/x-shellscript'],
['page.html', 'text/html'],
['app.js', 'text/javascript'],
['app.py', 'text/x-python'],
] as const) {
const res = await upload(name, mime, Buffer.from('#!/bin/sh\necho hi\n'));
+126
View File
@@ -13,6 +13,7 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
import { registerStatusTelemetryRoutes } from '../../src/web/routes/status-telemetry-routes.js';
import { registerHookEventRoutes } from '../../src/web/routes/hook-event-routes.js';
import { SessionPromptCache, SessionStatusTelemetry } from '../../src/web/sse-events.js';
import { Session } from '../../src/session.js';
@@ -81,6 +82,131 @@ describe('POST /api/status-telemetry', () => {
});
});
describe('the conversation the pane runs', () => {
// As measured on Claude Code 2.1.332: the statusline runs about a second after a `/clear`,
// with the new conversation's id and transcript path, before any hook reports them.
const cleared = {
session_id: 'conv-2',
transcript_path: '/home/u/.claude/projects/-w/conv-2.jsonl',
};
it('follows the new conversation the statusline reports after /clear', async () => {
const res = await post({ sessionId: SID, data: cleared });
expect(res.statusCode).toBe(200);
expect(h.ctx._session.claudeSessionId).toBe('conv-2');
expect(h.ctx._session.claudeSessionIdIsFirstHand).toBe(true);
expect(h.ctx.startTranscriptWatcher).toHaveBeenCalledWith(SID, cleared.transcript_path);
expect(h.ctx.persistSessionState).toHaveBeenCalledTimes(1);
// The next render reports the same conversation: nothing is persisted again.
await post({ sessionId: SID, data: cleared });
expect(h.ctx.persistSessionState).toHaveBeenCalledTimes(1);
});
/**
* The exporter backgrounds its POST when it wraps the user's own statusline, so a report sent
* before the `/clear` can land after the one sent after it. That old report must not move the
* session back to the conversation the `/clear` ended.
*/
it('ignores a delayed report that names an earlier conversation', async () => {
const report = (id: string) => ({
sessionId: SID,
data: { session_id: id, transcript_path: `/home/u/.claude/projects/-w/${id}.jsonl` },
});
await post(report('conv-1'));
await post(report('conv-2'));
await post(report('conv-1')); // the delayed old POST
const session = h.ctx._session;
expect(session.claudeSessionId).toBe('conv-2');
expect(session.claudeSessionChain[session.claudeSessionChain.length - 1]).toBe('conv-2');
expect(h.ctx.startTranscriptWatcher).toHaveBeenLastCalledWith(SID, report('conv-2').data.transcript_path);
});
/**
* With workspace hooks off no hook ever follows a `/resume`, so a statusline report that names
* an earlier conversation must move the session back once the last move is old enough that no
* delayed POST from before it can still arrive.
*/
it('follows a /resume back to an earlier conversation once the last move is more than 10 s old', async () => {
const report = (id: string) => ({
sessionId: SID,
data: { session_id: id, transcript_path: `/home/u/.claude/projects/-w/${id}.jsonl` },
});
// Only the clock is faked: Fastify's inject still needs real timers.
vi.useFakeTimers({ toFake: ['Date'] });
try {
vi.setSystemTime(new Date('2026-11-26T10:00:00Z'));
await post(report('conv-1'));
await post(report('conv-2'));
vi.setSystemTime(new Date('2026-11-26T10:00:11Z'));
await post(report('conv-1')); // the /resume back
} finally {
vi.useRealTimers();
}
const session = h.ctx._session;
expect(session.claudeSessionId).toBe('conv-1');
expect(session.claudeSessionChain[session.claudeSessionChain.length - 1]).toBe('conv-1');
expect(h.ctx.startTranscriptWatcher).toHaveBeenLastCalledWith(SID, report('conv-1').data.transcript_path);
});
/**
* A report naming the session's current conversation is never refused, so after a server
* restart the statusline still starts the transcript watcher for it.
*/
it('starts the transcript watcher for a report that names the current conversation', async () => {
await post({ sessionId: SID, data: cleared });
h.ctx.startTranscriptWatcher.mockClear();
await post({ sessionId: SID, data: cleared });
expect(h.ctx.startTranscriptWatcher).toHaveBeenCalledWith(SID, cleared.transcript_path);
});
/**
* The run summary records a `prompt_submitted` only for a `/clear` successor's first prompt.
* The statusline adopts the successor before that prompt's hook, so the hook must still learn
* that the conversation moved.
*/
it("records the /clear successor's first prompt in the run summary after the statusline moved it", async () => {
const both = await createRouteTestHarness(
(app, ctx) => {
registerStatusTelemetryRoutes(app, ctx);
registerHookEventRoutes(app, ctx);
},
{ sessionId: SID }
);
const tracker = { recordHookEvent: vi.fn() };
both.ctx.runSummaryTrackers.set(SID, tracker as never);
const prompt = () =>
both.app.inject({
method: 'POST',
url: '/api/hook-event',
payload: { event: 'prompt_submitted', sessionId: SID, data: { session_id: 'conv-2' } },
});
await both.app.inject({
method: 'POST',
url: '/api/status-telemetry',
payload: { sessionId: SID, data: cleared },
});
await prompt();
expect(tracker.recordHookEvent).toHaveBeenCalledTimes(1);
expect(tracker.recordHookEvent).toHaveBeenCalledWith('prompt_submitted', expect.any(Object));
await prompt(); // the next prompt in the same conversation
expect(tracker.recordHookEvent).toHaveBeenCalledTimes(1);
});
it('refuses a transcript path with shell syntax in it', async () => {
await post({ sessionId: SID, data: { ...cleared, transcript_path: '/tmp/$(id).jsonl' } });
expect(h.ctx.startTranscriptWatcher).not.toHaveBeenCalled();
});
it('takes no report from a CLI without a statusline exporter', async () => {
h.ctx._session.mode = 'shell';
await post({ sessionId: SID, data: cleared });
expect(h.ctx._session.claudeSessionId).not.toBe('conv-2');
expect(h.ctx.startTranscriptWatcher).not.toHaveBeenCalled();
});
});
it('does not broadcast for an unknown session; returns an EMPTY footer, never a brand word', async () => {
const res = await post({ sessionId: 'does-not-exist', data: REAL });
expect(res.statusCode).toBe(200);
+61 -1
View File
@@ -16,9 +16,12 @@
* feature), so the "stays attachable" cases matter just as much: over-blocking
* breaks the publish skill and the review-card loop.
*/
import { homedir } from 'node:os';
import { mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { homedir, tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import { isSensitivePath } from '../src/web/sensitive-path.js';
import { initTrustedProxySecret, resetTrustedProxySecretForTests } from '../src/config/trusted-proxy.js';
const HOME = '/home/dev';
const dotenvPaths: Array<[string, string]> = [
@@ -80,6 +83,7 @@ describe('isSensitivePath', () => {
['codeman hook secret', `${HOME}/.codeman/hook-secret`],
['codeman user table', `${HOME}/.codeman/users.json`],
['codeman hook secret on a named instance', `${HOME}/.codeman-beta/hook-secret`],
['codeman trusted-proxy secret (documented name)', `${HOME}/.codeman/proxy-secret`],
// state.json persists SessionState.envOverrides, and the env allowlist
// admits key-shaped names (GEMINI_API_KEY, CLAUDE_CODE_*), so it can hold
// a live credential. Named once .json became previewable from outside the
@@ -236,4 +240,60 @@ describe('isSensitivePath', () => {
expect(isSensitivePath(path)).toBe(false);
});
});
describe('the configured trusted-proxy secret file', () => {
it('blocks CODEMAN_TRUSTED_PROXY_SECRET_FILE whatever its name, and only while configured', () => {
const prev = process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE;
const file = '/srv/secrets/codeman-sso.key';
try {
delete process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE;
resetTrustedProxySecretForTests();
expect(isSensitivePath(file)).toBe(false);
process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE = file;
expect(isSensitivePath(file)).toBe(true);
expect(isSensitivePath('/srv/secrets/other.txt')).toBe(false);
// Once the secret is read, the variable is gone from process.env (so sessions don't
// inherit it); the path stays blocked through the trusted-proxy module.
initTrustedProxySecret();
expect(process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE).toBeUndefined();
expect(isSensitivePath(file)).toBe(true);
expect(isSensitivePath('/srv/secrets/other.txt')).toBe(false);
} finally {
resetTrustedProxySecretForTests();
if (prev === undefined) delete process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE;
else process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE = prev;
}
});
it.skipIf(process.platform === 'win32')(
'blocks the file under its real path when the setting names a symlink, and the other way round',
() => {
const prev = process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE;
const dir = realpathSync(mkdtempSync(join(tmpdir(), 'tp-secret-link-')));
const real = join(dir, 'real.key');
const link = join(dir, 'link.key');
writeFileSync(real, 'x', { mode: 0o600 });
symlinkSync(real, link);
try {
// The setting names the symlink; a caller resolves the served path to the target.
process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE = link;
resetTrustedProxySecretForTests();
expect(isSensitivePath(real)).toBe(true);
initTrustedProxySecret(); // resolved once here, then answered from the cache
expect(isSensitivePath(real)).toBe(true);
expect(isSensitivePath(join(dir, 'other.key'))).toBe(false);
// The setting names the target; the symlink resolves to it.
process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE = real;
resetTrustedProxySecretForTests();
initTrustedProxySecret();
expect(isSensitivePath(realpathSync(link))).toBe(true);
} finally {
resetTrustedProxySecretForTests();
if (prev === undefined) delete process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE;
else process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE = prev;
rmSync(dir, { recursive: true, force: true });
}
}
);
});
});
+2
View File
@@ -118,6 +118,8 @@ describe('WebServer index.html <title> templating (#82)', () => {
.replace(/<script>window\.__codemanTranscriptPageKeys=\[.*?\];<\/script>\n/, '')
// And the keyboard-hold mode list, built the same way.
.replace(/<script>window\.__codemanKeyboardHoldModes=\[.*?\];<\/script>\n/, '')
// And the chat view mode list, built the same way.
.replace(/<script>window\.__codemanChatViewModes=\[.*?\];<\/script>\n/, '')
// And the wheel-forwarding rules: an object keyed by run mode, always injected.
.replace(/<script>window\.__codemanWheelForward=\{.*?\};<\/script>\n/, '');
const beforeTitle = rawTemplate.split('<title>Codeman</title>')[0];
+115 -4
View File
@@ -19,11 +19,13 @@ import { describe, expect, it, vi } from 'vitest';
type Link = { text: string; activate: (ev: unknown, text: string) => void; hover: () => void; leave: () => void };
type Provider = { provideLinks: (line: number, cb: (links: Link[] | undefined) => void) => void };
function loadHarness() {
function loadHarness(fetchResponse = vi.fn()) {
const CodemanApp = function CodemanApp(this: unknown) {};
const windowRef: Record<string, unknown> = {};
const context = vm.createContext({
window: windowRef,
AbortSignal,
fetch: fetchResponse,
document: {
body: { classList: { contains: () => false } },
activeElement: null,
@@ -48,20 +50,25 @@ function loadHarness() {
}
/** A one-screen xterm stand-in holding `lines`, recording every provider registered on it. */
function fakeTerminal(lines: string[]) {
function fakeTerminal(lines: string[], cols = 80) {
const providers: Provider[] = [];
return {
cols: 80,
cols,
providers,
registerLinkProvider: (p: Provider) => providers.push(p),
buffer: {
active: {
length: lines.length,
viewportY: 0,
getLine: (row: number) =>
row >= 0 && row < lines.length
? {
isWrapped: false,
translateToString: (trim?: boolean) => (trim === false ? lines[row].padEnd(80) : lines[row]),
getCell: (col: number) => ({ getChars: () => lines[row][col] ?? ' ', getWidth: () => 1 }),
translateToString: (trim?: boolean, start = 0, end = cols) => {
const text = lines[row].padEnd(cols).slice(start, end);
return trim ? text.trimEnd() : text;
},
}
: undefined,
},
@@ -146,3 +153,107 @@ describe('registerFilePathLinkProvider with a target (a second pane)', () => {
expect(app.openFilePreview).toHaveBeenCalledWith('/tmp/a.pdf', 'second');
});
});
describe('native Codex sidebar files', () => {
const left = 'wrote /tmp/keep.png'.padEnd(42);
const tab = ' Brief…26943.docx × +';
const picker = ' › · Word draft.docx Project root';
function setupSidebar() {
const app = makeApp();
app._supportsCodexResponseFiles = () => true;
app._codexFilePreviewsEnabled = () => true;
const terminal = fakeTerminal([
left + '│' + tab,
' '.repeat(42) + '│ Open in sidebar',
' '.repeat(42) + '│ Files 1',
' '.repeat(42) + '│' + picker,
' '.repeat(42) + '│ body /tmp/normal.png',
]);
app.terminal = terminal;
app._clientPointToCell = (col: number, row: number) => ({ col, row });
return { app, terminal };
}
it('finds a shortened tab and a picker entry without claiming the close button or directory suffix', () => {
const { app, terminal } = setupSidebar();
expect(app._codexTerminalLinkLabel(terminal, 47, 1)).toMatchObject({ label: 'Brief…26943.docx', sidebar: true });
expect(app._codexTerminalLinkLabel(terminal, 44 + tab.indexOf('×'), 1)).toBeNull();
expect(app._codexTerminalLinkLabel(terminal, 52, 4)).toMatchObject({ label: 'Word draft.docx', sidebar: true });
expect(app._codexTerminalLinkLabel(terminal, 44 + picker.indexOf('Project'), 4)).toBeNull();
});
it('suppresses generic sidebar suffixes and preserves ordinary paths beside and below them', () => {
const { app } = setupSidebar();
const provider = app.registerFilePathLinkProvider();
expect(linksOn(provider, 1).map(({ text }) => text)).toEqual(['/tmp/keep.png']);
expect(linksOn(provider, 4)).toEqual([]);
expect(linksOn(provider, 5).map(({ text }) => text)).toEqual(['/tmp/normal.png']);
app._supportsCodexResponseFiles = () => false;
expect(linksOn(provider, 4).map(({ text }) => text)).toContain('draft.docx');
});
it('leaves sidebar rows to Codex while the Codex files setting is off', () => {
const { app, terminal } = setupSidebar();
app._codexFilePreviewsEnabled = () => false;
// No sidebar label is taken, so the click is forwarded to Codex as before.
expect(app._codexTerminalLinkLabel(terminal, 47, 1)).toBeNull();
expect(app._codexTerminalLinkLabel(terminal, 52, 4)).toBeNull();
// And the row keeps the ordinary linkifier's links, exactly as on master.
const provider = app.registerFilePathLinkProvider();
expect(linksOn(provider, 4).map(({ text }) => text)).toContain('draft.docx');
});
it('caches the parsed conversation per session until its next turn', async () => {
const fetchResponse = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: { messages: [] } }) });
const app = loadHarness(fetchResponse);
const session = { status: 'idle', lastSubmitAt: 1 };
app.sessions = new Map([['pane', session]]);
await app._codexResponseMessages('pane');
await app._codexResponseMessages('pane');
expect(fetchResponse).toHaveBeenCalledTimes(1);
session.lastSubmitAt = 2; // a new turn
await app._codexResponseMessages('pane');
expect(fetchResponse).toHaveBeenCalledTimes(2);
session.status = 'busy'; // a growing rollout is never served from the cache
await app._codexResponseMessages('pane');
await app._codexResponseMessages('pane');
expect(fetchResponse).toHaveBeenCalledTimes(4);
});
});
describe('Codex response click fallback', () => {
const clicked = { label: 'Word draft.docx', row: 1, start: 42, end: 57, sidebar: true };
const point = { clientX: 40, clientY: 10 };
it.each(['failed load', 'no match', 'superseded click', 'moved cell', 'matched file'])(
'handles %s',
async (outcome) => {
const fetchResponse = vi.fn();
const app = loadHarness(fetchResponse);
const forward = vi.fn();
const terminal = fakeTerminal([]);
const match = vi.fn(() => (outcome === 'no match' ? null : '/work/Word draft.docx'));
app._findCodexResponseFile = match;
app._codexTerminalLinkLabel = () => (outcome === 'moved cell' ? { ...clicked, row: 2 } : clicked);
app._openResponseFile = vi.fn();
if (outcome === 'failed load') fetchResponse.mockRejectedValue(new Error('offline'));
else fetchResponse.mockResolvedValue({ ok: true, json: async () => ({ data: { messages: [] } }) });
await app._openCodexTerminalResponseFile(
terminal,
'pane',
point,
clicked,
() => outcome !== 'superseded click',
forward
);
expect(forward).toHaveBeenCalledTimes(Number(outcome === 'failed load' || outcome === 'no match'));
if (outcome === 'matched file') {
expect(app._openResponseFile).toHaveBeenCalledWith('/work/Word draft.docx', 'pane');
} else {
expect(app._openResponseFile).not.toHaveBeenCalled();
}
if (outcome === 'superseded click') expect(match).not.toHaveBeenCalled();
}
);
});
+47
View File
@@ -493,6 +493,53 @@ describe('terminal touch tap mouse guard', () => {
expect(sent).toEqual([{ id: 'sess-1', data: '\x1b[<0;21;6M\x1b[<0;21;6m' }]);
});
it('desktop click: resolves a Codex label from underlined cells before forwarding mouse input', () => {
const { app } = loadTerminalUiHarness();
const session = { mode: 'codex', cliMouseTracking: true };
app.activeSessionId = 'sess-1';
app.sessions = new Map([['sess-1', session]]);
app.terminal = createTerminalGrid(['• Word brief', '', '› '], 2);
const getLine = app.terminal.buffer.active.getLine;
app.terminal.buffer.active.getLine = (row: number) => {
const line = getLine(row);
if (row !== 0) return line;
return {
...line,
translateToString: (_trim: boolean, start: number, end: number) => '• Word brief'.slice(start, end),
getCell: (column: number) => ({ getWidth: () => 1, isUnderline: () => column >= 2 && column < 12 }),
};
};
app._supportsCodexResponseFiles = () => true;
app._codexFilePreviewsEnabled = () => true;
app._openCodexTerminalResponseFile = vi.fn().mockResolvedValue(undefined);
app._sendSyntheticSgrTap = vi.fn();
app._handleDesktopTerminalClick({
isTrusted: true,
button: 0,
detail: 1,
clientX: 40,
clientY: 10,
target: { closest: () => ({}) },
});
expect(app._openCodexTerminalResponseFile).toHaveBeenCalledWith(
app.terminal,
'sess-1',
{ clientX: 40, clientY: 10 },
{ label: 'Word brief', row: 1, start: 2, end: 12 },
expect.any(Function),
expect.any(Function)
);
expect(app._sendSyntheticSgrTap).not.toHaveBeenCalled();
// A double-click selects the word: its second click returns before it can supersede
// this one, so the selection it leaves is what makes the pending lookup stale.
const stillCurrent = app._openCodexTerminalResponseFile.mock.calls[0][4];
expect(stillCurrent()).toBe(true);
app.terminal.hasSelection = () => true;
expect(stillCurrent()).toBe(false);
});
it('desktop click: skips clicks that already have a meaning elsewhere', () => {
const { app } = loadTerminalUiHarness();
const sent: string[] = [];
+14
View File
@@ -199,6 +199,20 @@ describe('parking the main terminal', () => {
app.closeTileGrid({ reselect: false });
expect(app.selectSession).not.toHaveBeenCalled();
});
it('opening and closing re-sync the chat view, so it hides for the tiles and comes back after', () => {
const app = makeApp();
// What the grid reported when the chat view was told, one entry per call.
const owned: boolean[] = [];
app._chatViewSync = vi.fn(() => owned.push(app._tilesOwnTerminal()));
app.openTileGrid(IDS);
expect(owned).toContain(true);
owned.length = 0;
app.closeTileGrid({ reselect: false });
expect(owned).toContain(false);
});
});
/** An app with the grid open on IDS (focus s-a), or closed, for the paired guard checks. */
+5 -4
View File
@@ -19,7 +19,7 @@ function loadToolbar(sessionId: string | null = 'session-1', localEcho = true, k
const dom = new JSDOM(
'<!DOCTYPE html><html><body><span class="btn-attach-mobile-wrap">' +
'<button type="button" id="attachBtnMobile"></button>' +
'<input type="file" id="attachFileInput" accept="image/*,video/*,.pdf,.docx,.pptx,.xlsx,.zip,.txt,.md,.csv,.tsv,.json,.log,.yaml,.yml,.xml" multiple>' +
'<input type="file" id="attachFileInput" accept="image/*,video/*,.pdf,.docx,.pptx,.xlsx,.zip,.txt,.md,.csv,.tsv,.json,.log,.yaml,.yml,.xml,.html,.htm" multiple>' +
'</span><div id="terminalContainer"></div></body></html>'
);
const { window } = dom;
@@ -361,8 +361,8 @@ describe('phone toolbar Attach button', () => {
};
const photo = new window.File(['p'], 'photo.jpg', { type: 'image/jpeg' });
const script = new window.File(['#!/bin/sh'], 'run.sh', { type: 'text/x-shellscript' });
const page = new window.File(['<p>'], 'page.html', { type: 'text/html' });
drop([photo, script, page]);
const program = new window.File(['print(1)'], 'app.py', { type: 'text/x-python' });
drop([photo, script, program]);
expect(app._uploadAndInsertImages).toHaveBeenCalledWith([photo]);
expect(app.showToast).toHaveBeenCalledWith('2 files skipped: unsupported type', 'info');
app.showToast.mockClear();
@@ -397,7 +397,8 @@ describe('phone toolbar Attach button', () => {
expect(kind('todo.md', 'text/plain')).toBe('document');
expect(kind('data.csv', 'application/octet-stream')).toBe('document');
expect(kind('run.sh', 'text/x-shellscript')).toBeNull();
expect(kind('page.html', 'text/html')).toBeNull();
expect(kind('spec.html', 'text/html')).toBe('document');
expect(kind('report.HTM', '')).toBe('document');
expect(kind('noext', '')).toBeNull();
});
+88
View File
@@ -0,0 +1,88 @@
/**
* @fileoverview The server path from a transcript watcher's `transcript:update` event to the
* throttled `transcript:update` SSE broadcast, which the chat view's live updates depend on.
*
* Pinned: the first update broadcasts at once and a second one inside the interval broadcasts
* once at its end (750 ms), stopTranscriptWatcher drops a pending trailing broadcast, and no
* watcher starts for a session that cleanup is removing.
*
* Strategy: construct WebServer on port 0 in test mode (nothing listens until start()) and call
* its private watcher methods directly.
*
* Port: N/A (no server start)
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import type { EventEmitter } from 'node:events';
import { WebServer } from '../src/web/server.js';
import { SseEvent } from '../src/web/sse-events.js';
interface ServerInternals {
broadcast: (event: string, data: unknown) => void;
startTranscriptWatcher: (sessionId: string, transcriptPath: string) => void;
stopTranscriptWatcher: (sessionId: string) => void;
transcriptWatchers: Map<string, EventEmitter>;
cleaningUp: Set<string>;
}
describe('transcript:update broadcast', () => {
const SID = 'transcript-update-session';
let server: ServerInternals;
let broadcast: ReturnType<typeof vi.spyOn>;
let transcriptPath: string;
const updates = () => broadcast.mock.calls.filter(([event]) => event === SseEvent.TranscriptUpdate);
beforeEach(() => {
server = new WebServer(0, false, true) as unknown as ServerInternals;
broadcast = vi.spyOn(server, 'broadcast').mockImplementation(() => {});
transcriptPath = join(mkdtempSync(join(tmpdir(), 'codeman-transcript-update-')), 'conv.jsonl');
writeFileSync(transcriptPath, '');
});
afterEach(() => {
server.stopTranscriptWatcher(SID);
vi.useRealTimers();
});
it('broadcasts the first update at once and a second one at the end of the interval', () => {
server.startTranscriptWatcher(SID, transcriptPath);
const watcher = server.transcriptWatchers.get(SID);
expect(watcher).toBeDefined();
vi.useFakeTimers();
watcher!.emit('transcript:update');
watcher!.emit('transcript:update');
expect(updates()).toHaveLength(1);
expect(updates()[0][1]).toMatchObject({ sessionId: SID });
vi.advanceTimersByTime(749);
expect(updates()).toHaveLength(1);
vi.advanceTimersByTime(1);
expect(updates()).toHaveLength(2);
expect(updates()[1][1]).toMatchObject({ sessionId: SID });
});
it('drops a pending trailing broadcast when the watcher stops', () => {
server.startTranscriptWatcher(SID, transcriptPath);
const watcher = server.transcriptWatchers.get(SID)!;
vi.useFakeTimers();
watcher.emit('transcript:update');
watcher.emit('transcript:update');
server.stopTranscriptWatcher(SID);
vi.advanceTimersByTime(1000);
expect(updates()).toHaveLength(1);
expect(server.transcriptWatchers.has(SID)).toBe(false);
});
it('starts no watcher for a session that cleanup is removing', () => {
server.cleaningUp.add(SID);
server.startTranscriptWatcher(SID, transcriptPath);
expect(server.transcriptWatchers.has(SID)).toBe(false);
server.cleaningUp.delete(SID);
});
});
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff. Show more