Compare commits

..
Author SHA1 Message Date
Codeman maintainer 6db166f3f8 chore: version packages 2026-11-27 08:19:14 +01:00
Codeman maintainer b3e781696a test(web): #815's cleanup test knows the input settle #839 added
Both land in this release. #839 makes _cleanupPreviousSession() settle the
main pane's native input first, and #815's test drives that method on a
stub app that did not have it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 07:40:03 +01:00
Codeman maintainer 854f316809 chore: the release changeset names #815
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 07:37:39 +01:00
Codeman maintainer 00552ac04a docs: the maintainer bot also triages issues
The sentence had been sitting uncommitted in the shared checkout since
1.51.0.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 07:36:44 +01:00
Codeman maintainer 4936e07ca2 Merge #815: fix(web): manual Reload history action for the tmux repaint gap above live output (#814)
# Conflicts:
#	src/web/CLAUDE.md
2026-11-27 07:36:29 +01:00
Codeman maintainer 51852dbdbc chore: the release changeset names #840 and #853
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 06:13:56 +01:00
Codeman maintainer fcccdd07c5 fix(tui): the review items of #853 that go on top
The one-row nudge before a forced resize at an unchanged size runs only
for a tmux-backed session. On a direct PTY the process is the agent
itself, which got two height changes where master sent none. The
unrelated table reformatting in docs/tui.md is dropped.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 06:13:29 +01:00
Codeman maintainer f2c03e6bf3 Merge #853: fix(tui): the attached terminal takes the window size back after a browser resized it 2026-11-27 06:11:12 +01:00
Codeman maintainer d5fe0adfe7 test(tmux): the review item of #840 that goes on top
The live-pane close case moves into test/kill-pid-guard.test.ts, whose
harness answers ps from a fixed table. In tmux-manager.test.ts the mock
keeps the real execFile, so the walk read this machine's process table.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 06:10:21 +01:00
Codeman maintainer a4201b34a8 Merge #840: fix(tmux): see an exited agent on tmux 3.8, which blanks a dead pane's pid 2026-11-27 06:08:26 +01:00
Kamil KaliszandClaude Opus 5.5 70ee1312d4 fix(tui): Redraw wins, leaks are told by process, detach unsets the whole hook array
Review follow-up on the follow-typing attach.

- Redraw (and every forced resize at an unchanged size) handed the window
  back to the terminal: an unchanged pty sends tmux no SIGWINCH, so the
  terminal stayed the latest client and the after-resize-window hook undid
  the resize-window. Session.resize() now nudges the pty one row first
  (FORCED_RESIZE_NUDGE_MS), then applies the size, so tmux counts the tab
  as the client used last; the second move bumps the guarded geometry
  revision too. Under manual with no attach the agent sees no change.
- With the nudge, client-active[91] alone covers every case, so the
  after-resize-window hook is gone. It kept latest through every browser
  resize and cost the agent three height changes per resize; now the first
  resize after the terminal was used costs two and later ones one. The
  cost is stated next to the hook.
- The leak sweep matched owners by tty, and Linux hands the next terminal
  the pty that just closed, so the common leak was never swept. The arm
  now records the TUI's pid (@codeman-tui-follow-pid), and the sweep keeps
  only sessions this process armed (a Set filled before the first write)
  or whose pid is another live process. One list-sessions call reads every
  owner. It also runs before each attach dresses its sessions, so
  `codeman tui <n>` gets it and a leaked hook cannot undo presizeWindow().
- `set-hook -u` on our index left an empty session-level array, which
  hides the user's global hook on that event. Disarm unsets the whole
  event when ours is its only entry, and arm refuses while the user has a
  global client-active hook.
- Arm and disarm are one tmux call to read and one to write (`;` lists).
- Docs: the "forced resize when a browser opens a session" wording was
  wrong (selectSession sends no force; only Redraw, a closing pop-out and
  the split pane do), fixed in tui-client.ts, docs/tui.md and the
  invariants, whose paragraph now stands on its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 10:46:57 +01:00
Kamil KaliszandClaude Opus 5.5 9309500d40 fix(tmux): a pane pid of 0 falls back to the recorded pid on close
Review follow-up (owner's merge-time items, applied here).

- killSession() used `pane.pid ?? session.pid`, which kept tmux's 0 for
  an empty active pane (`split-window ''`: `1|0|` up to tmux 3.6, `0|0|`
  on 3.7) beside a running agent, so the close signalled nothing where
  master signals the agent's tree. `||` restores that; isSignalablePid()
  still refuses 0 or 1.
- kill-pid-guard.test.ts answered the old pid-only read, which the
  three-field parser read as no pid, so no case gave killSession() tmux's
  own 0. Its mock now answers the kill read, with cases for `1|0|`,
  `0|0|` and `0||` against a recorded agent pid and a recorded 0.
- Tests pin the whole kill read format, and the reconcile rule that a
  pane without a pid never overwrites a live pane's pid. Dropping
  `#{pane_dead_time}`, using `??` or `pane.pid` alone, or a plain
  `active.set(...)` each fail now.
- parsePaneKillRead() cases for `1|0|`, `0|0|` and `1|-1|`.
- Comments and docs: the blank pid with a late dead flag is tmux 3.8;
  on 3.4 only the seconds to collect the status were measured. A pid
  below 2 is no pid. The recorded pid is unreaped in the closing window
  only when it is the pane's start pid (`respawn-pane` breaks that).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 10:20:57 +01:00
Kamil KaliszandClaude Opus 5.5 95918b80b4 Merge master into fix/dead-pane-blank-pid
Resolves the killSession() conflict with babb55e4 (never signal pid 0
or 1). The dead-pane read decides first; a pid that is not signalable
(isSignalablePid) then also means nothing is signalled and only
`tmux kill-session` runs. killPaneProcessTree() sends every signal
through signalProcess().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 21:16:11 +01:00
Codeman maintainer 64c8d1c8a5 chore: the release changeset names the Mac app's server tabs
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 17:43:21 +01:00
Codeman maintainer b957eb8dea Merge #816: feat(desktop): server tabs, several Codeman servers open in one window 2026-11-25 17:43:21 +01:00
Codeman maintainer 6824fe666c chore: the release changeset names the four bugfixes and becomes a minor
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 17:43:05 +01:00
Codeman maintainer 5672e47a2d Merge #817: fix(desktop): pasting an image with Cmd+V works in the Mac app 2026-11-25 17:15:16 +01:00
Codeman maintainer 03916d75a1 Merge #819: fix(mobile): the phone toolbar sits on the keyboard, and the prompt's last line is no longer under it 2026-11-25 17:15:16 +01:00
Codeman maintainer 38c98529c4 Merge #857: fix(web): a dialog opened with the mouse hands the keyboard back to the terminal 2026-11-25 17:15:15 +01:00
Codeman maintainer 063476ec55 Merge #851: fix(tabs): keep the working spinner on a ledger cell 2026-11-25 17:15:15 +01:00
Codeman maintainer 7a3bbce7d5 chore: the changeset for the next release
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 16:11:57 +01:00
Codeman maintainer eb40f4aaa5 Merge #839: fix(web): synchronize iOS keyboard edits (#830) (@HadrienKerlero) 2026-11-25 16:11:57 +01:00
Codeman maintainer dfd661f9d1 docs(auth): the two wording nits of #838's review
An empty Authorization header is treated like a missing one, and the docs
say so. The comment on why hook-secret failures keep their own bucket no
longer claims a shared one would 429 a request without credentials.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 16:11:57 +01:00
Codeman maintainer fc41bb5b13 fix(files): the review items of #848 that go on top
A restore no longer pages through a whole large folder for an expanded
folder that is gone: directories are listed before files across pages, so
a loaded file ends the search, and the expansion is forgotten. An expanded
folder that waits for its turn in the restore says it is loading, and a
search-result folder opened while the tree was loading runs the restore
afterwards. The error line keeps its parts in separate elements so the
zh-CN entries apply, one local match reads in the singular, and the search
box labels the phone keyboard's Enter key.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 16:11:57 +01:00
Codeman maintainer 76c5f1a99b fix(installer): the review items of #847 that go on top
The manual multi-user start line is printed only where no service runs:
next to a working service it would start a second server on the same data
dir and tmux socket. The Environment= reader removes quotes wherever they
sit in a word, as systemd does, so a hand-written CODEMAN_MULTIUSER="1" or
CODEMAN_PASSWORD="my pass" survives a re-run.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 16:11:57 +01:00
Codeman maintainer f109bdc23a docs(wiki): the review items of #845 that go on top
The drop-in is the right place because the installer and
`codeman service install` rewrite the unit file and drop
CODEMAN_ALLOWED_HOSTS, not because it sits outside the checkout. The unit
of a named instance is named.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 16:11:57 +01:00
Codeman maintainer d466e5c3bf Merge #848: feat(files): load file-browser directories on demand (@DodgyBadger) 2026-11-25 16:11:57 +01:00
Codeman maintainer 1d889468df Merge #847: fix(installer): explain how to enable multi-user mode (@bearyjd) 2026-11-25 16:11:56 +01:00
Codeman maintainer 0be4c154cc Merge #845: Document persistent reverse-proxy hostnames for systemd (@bearyjd) 2026-11-25 16:11:56 +01:00
Codeman maintainer b7bb332338 Merge #838: fix(auth): stop counting credential-less requests as failed logins (@kkalisz) 2026-11-25 16:11:56 +01:00
Codeman maintainer babb55e4d9 fix(tmux): closing a session never signals pid 0 or 1
tmux answers 0 for the pid of a pane without a process (`split-window ''`).
The pane list read at server start recorded that 0 on the session, and the
next close of the tab walked the children of pid 0, which is the whole
machine: every process of the account was signalled, all sessions, tmux
itself and the systemd user manager included.

killSession() now decides once whether there is a process to signal
(isSignalablePid(), an integer above 1) and otherwise leaves the close to
`tmux kill-session`. The descendant walk of the kill path returns nothing
for such a root, and signalProcess(), the only place in tmux-manager.ts
that sends a signal, refuses it for the process group form as well.

proc-walk-bounds used pid 1 as the root of its fixture tree, which the kill
path now refuses on purpose, so the fixture is rooted at a real pid.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:03:54 +01:00
Kamil KaliszandClaude Opus 5.5 891f3a19e9 test(tmux): let the live pane die on its signal, so Linux CI never reads /proc
The live-pane close test mocked process.kill to always succeed, so the
pane never exited and the kill path's wait polled isProcessRunning().
On Linux that reads /proc/<pid>/stat, which this file mocks to return
undefined, and the test threw "Cannot read properties of undefined
(reading 'lastIndexOf')". macOS skips that read, so it passed locally.

The mock now models a pane that exits on its first real signal, after
which kill(pid, 0) throws ESRCH. Reproduced the CI error locally by
forcing the Linux branch; it passes with this change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:19:18 +01:00
Kamil KaliszandClaude Opus 5.5 ccf502b7a8 fix(tmux): keep a closing pane, and trust a dead flag only with an exit sign
Review follow-up on the tmux 3.8 dead-pane fix.

- parsePaneRows() skipped a row with a blank pid and pane_dead 0. tmux
  blanks the pid when the pty closes, and pane_dead turns 1 only once
  the exit status is collected (seconds for some exits on tmux 3.4), so
  a restart in that window dropped the session. Only a row with neither
  a pid nor a dead flag is skipped now.
- Before tmux 3.7 pane_dead means only that the pty is closed. The kill
  read now also reads #{pane_dead_time}, and counts a pane as dead only
  with a blank pid or a set exit time, so a program that closed its tty
  and ignores SIGHUP is still killed on tmux 3.3a to 3.6.
- Tests pin the last two pane format fields and add a live-pane
  counterpart to the dead-pane kill test.
- Changeset notes that finished sessions piled up on 3.8 are relaunched
  once at the first start after the update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:59:40 +01:00
Codeman maintainer 79f85415d8 fix(web): a dialog opened with the mouse hands the keyboard back to the terminal
After App Settings or Session Options was opened with a mouse click and
closed, nothing typed reached the terminal until it was clicked again.
FocusTrap saved document.activeElement when the dialog opened, and by then
the press had 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.

FocusTrap.focusToReturn() is what a dialog saves now. A pointerdown listener
records the typing field that had focus when a mouse press began (pointerdown
comes before mousedown, whose default action moves focus), and that field is
the answer when focus sits on the pressed control or on <body> as the dialog
opens. Any key forgets the press, so a control reached with the keyboard gets
focus back as before. Only a typing field is remembered, for one press (a
press on a menu item inherits it from the press that opened the menu) and
only for a mouse, so touch is unchanged. Asking spends the press, so nothing
pressed inside the opening dialog can hand the keyboard to a field behind it.

The command palette and the Session Manager save the same answer.

Measured in Chromium against a running server: App Settings and Session
Options opened by mouse ended on the clicked gear before and in the terminal
after, also with the press clearing focus as WebKit on macOS does, with the
tile grid and the split open (the keyboard returns to the pane it was in),
and through a tile's menu. Not run in WebKit on macOS itself.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 10:23:52 +01:00
Kamil KaliszandClaude Opus 5.5 9753ca9d70 fix(tui): undo a half-done follow arm
armFollowTyping() set the owner option, then a hook. On tmux before 3.3
there is no client-active hook, so the first set-hook failed and the arm
answered false with the owner still set; restore() disarms only what
armed, so it stayed on the session. A failed arm now drops the owner and
any of our hooks it already set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 18:42:21 +01:00
Kamil KaliszandClaude Opus 5.5 dbf545ce8f fix(tui): keep the window following the client used last, forced resizes included
A browser that opens a session sends a forced resize at its current size.
Its pty does not change, so tmux keeps the TUI's client as the latest one
and `client-active` never fires again, while Codeman's `resize-window`
still pins the window to `manual` at the browser's size. Typing in the
terminal then did nothing, which is the bug this branch fixes.

An `after-resize-window[91]` hook now puts `latest` back after Codeman's
resize, so tmux keeps deciding by the client used last; `client-active[91]`
stays for Codeman's own attach (`setManualWindowSize()`), which sets
`manual` without a resize.

The owner's tty moves into the session option `@codeman-tui-follow`, and
both hook commands are constants that read it, so no tty is interpolated
into a hook and hooks whose owner is gone do nothing. restore() and the
startup sweep drop the owner first, then our hooks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 18:39:54 +01:00
Kamil KaliszandClaude Opus 5.5 d387cf8cdb fix(tui): sweep follow-typing hooks a killed TUI left behind
A terminal that dies while attached (closed window, dropped SSH) never
reaches restore(), so its client-active[91] hooks stayed on the sessions.
TUI startup now removes ours whose tty has no live tmux client, next to
the leaked-banner sweep. The TUI's own tty is never swept: the sweep is
fire-and-forget, and an early Enter can arm that hook before the attach
client exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 18:30:27 +01:00
Kamil KaliszandClaude Opus 5.5 ba61cfe4e6 fix(tui): take the window size back when the attached terminal is used
`codeman tui` sets `window-size latest` for an attach, but a browser tab
that opens or resizes the same session mid-attach makes Codeman run
`resize-window`, which puts the window back on `manual` at the browser's
size. The terminal then showed a phone-sized pane, and typing or pasting
changed nothing until a detach and a fresh attach.

The attach now sets a per-session `client-active[91]` hook on every
session it dresses. It runs `set-window-option window-size latest` only
for the TUI's own client (`#{client_tty}`), so typing, pasting or
resizing the terminal hands the window back to it, the way plain tmux
follows whoever used it last. `restore()` removes the hooks before the
window sizes are put back, and only while they still name this tty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 18:28:06 +01:00
Kamil KaliszandClaude Opus 5.5 d7c141e25f docs(tmux): note second-granular dead time and orphaned-session cleanup
Review follow-ups on #840: `#{pane_dead_time}` is stamped in whole seconds,
so two same-status exits in one second read as one; and the changeset tells
users how to remove a dead codeman-* session orphaned before this fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 17:10:37 +01:00
Kamil KaliszandClaude Opus 5.5 67aa28ac4f test(tmux): close a dead-pane session end to end without signalling its pid
The kill rule was pinned only through parsePaneKillRead(). Drive
killSession() with tmux commands enabled and exec answering like tmux
3.8 (a dead pane, pid blank), and assert nothing signals the recorded
pid while kill-session still runs. Against bee4948e it fails: pid 4242
is signalled 201 times. Group the three no-pid tests in their own
describe instead of the launch-cwd one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 15:41:39 +01:00
Kamil KaliszandClaude Opus 5.5 df494b21ce fix(tmux): never signal the recorded pid of a dead pane on close
killSession() read `#{pane_pid}` and fell back to the recorded pid when
tmux printed none, which tmux 3.8 does for every dead pane. That pid
belongs to the program that exited; the OS may have reused it, and the
kill path walked its process tree and SIGKILLed it. It now reads
`#{pane_dead}` with the pid (parsePaneKillRead) and, for a dead pane,
only runs kill-session. Survivors of an exited program were already out
of reach (reparented, and the group kill only ran for a live leader),
so nothing a live pane gets is lost. Strategies 1 and 2 move into
killPaneProcessTree() unchanged.

Docs: the architecture-invariants paragraph says a kept dead pane is
respawned by the restore at the next server start (measured on tmux
3.8; tmux 3.7 and older always did this), and describes the kill rule.
CLAUDE.md's paneExit rule gains the no-pid warning. The
PaneExitObservation comment no longer claims tmux before 3.4 lacks
`#{pane_dead_time}`, which was never measured.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 13:22:42 +01:00
Codeman maintainer 79f444a2fc fix(tabs): keep the working spinner on a ledger cell
The ledger layout hid every .tab-status to swap the dot for its coloured
bar. The bar is green for idle and working alike, and the spinner is the
dot's own .tab-status.busy::after ring, so a working session showed no
mark at all. A busy cell now keeps the dot and its ring, idle cells stay
bar-only, and an exited agent's cell still hides it like the classic strip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 09:46:23 +01:00
Hadrien Kerlero 58a5ef51bc docs(changeset): drop internal recovery bookkeeping from the release note (#814)
- The deferred dropped-output recovery's retry attempt is internal; the release note no longer mentions it.
2026-11-23 18:37:12 +01:00
DodgyBadger 349d21f75e feat(files): load directories on demand 2026-11-23 16:34:03 +00:00
Hadrien Kerlero c52137a2ec docs(web): RIS leaves the reading-row marker alive (#814)
- In xterm 6 only ESC[3J (and a trim) disposes the marker; RIS swaps in a new buffer and leaves it on its old line, which is the same index as the fallback. The flushPendingWrites comment and the invariants paragraph now say so.
2026-11-23 17:06:04 +01:00
Hadrien Kerlero e44d586f93 fix(web): keep the reader's row when a flush clears scrollback (#814)
- flushPendingWrites falls back to the absolute viewport index when the write disposed the marker, which ESC[3J or RIS also do (the narrow and middle strips keep 3J), instead of sending the reader to row 0.
- The live-output mark block moves below the write's try/catch, so the catch only covers the write.
- Test: one flush of ESC[H ESC[2J ESC[3J plus a reprint keeps the reader on line 100, with and without markers.
2026-11-23 15:22:07 +01:00
Hadrien Kerlero a92d512459 test(web): match the Reload history button by its exact name (#814)
- The reload-only bar's × is now labelled "Dismiss Reload history", which Playwright's default substring name match also selected; the five Reload history locators in history-gap-repair.browser.test.ts pass exact: true.
2026-11-23 13:02:47 +01:00
Hadrien Kerlero 82071d47bd fix(web): skip Reload history for Docker and adopted panes, label the × for what the bar carries (#814)
- _historyReloadActionEligible() leaves out Docker and adopted sessions, whose nested tmux client keeps the local pane in the alternate screen so ?full=1 returns one screen the downgrade guard refuses; remote sessions stay eligible.
- The bar's × is labelled "Dismiss Reload history" when the bar carries no truncation notice, with a zh-CN entry.
2026-11-23 12:07:13 +01:00
bearyjd 3f7d08e97e fix(installer): honor effective multi-user assignments 2026-11-22 20:40:01 -05:00
bearyjd c22bbd70ac fix(installer): preserve multi-user service configuration 2026-11-22 20:34:11 -05:00
bearyjd 7d6e7fd411 fix(installer): explain how to enable multi-user mode 2026-11-22 23:59:09 +00:00
Hadrien Kerlero 4848886330 fix(web): sample the live-output generation before selectSession fetches (#814)
- selectSession now samples _liveOutputGen before its fresh fetch, as the refresh and manual-pull paths do, so output that arrives during the download keeps the session marked for Reload history.
- Test: live output during the fresh fetch keeps the mark after a mux-full-history replay.
2026-11-23 00:31:49 +01:00
Hadrien Kerlero 7794f74282 fix(web): announce only the truncation notice from the history bar (#814)
- _renderHistoryTruncationBanner sets aria-live to polite for the truncation notice and off for a reload-only bar, which re-renders on nearly every scroll-up in a busy tab; its button stays reachable with Tab.
- docs: comma in the Reload eligibility list, and the live-region rule in the invariants paragraph.
2026-11-22 23:49:19 +01:00
Hadrien Kerlero 6f5b3aca23 fix(web): keep Reload history and history pulls aside while a drop-recovery refresh fetches (#814)
- _historyReloadActionEligible() and _maybeRefetchFullHistory stand aside while _terminalRefreshOwner holds the active session, so Reload, Load full history and the top-of-buffer pull no longer start a second capture whose download-time queue the refresh's own load would replace.
- _onSessionNeedsRefresh re-syncs the action when it takes the owner and again in its finally once it releases it.
- Tests: a refresh-in-flight visibility row, and a tap during a held refresh that fetches nothing and gets the action back afterwards.
2026-11-22 18:24:47 +01:00
bearyjd 99977ca022 docs: persist reverse proxy hostnames for systemd service 2026-11-22 10:33:05 -05:00
Hadrien Kerlero e7f90cb3ec fix(web): keep Load full history on Loading… while it stands in for Reload (#814)
- A content-anchored Load full history pull sets _historyReloadActionLoadingFor and clears it on settle, as Reload history does.
- The button renders from that loading state, so the re-render the in-flight pull triggers keeps it disabled on Loading….
- The top-anchor case keeps no loading state, so the bar still hides on a scroll back to live output.
2026-11-22 04:40:40 +01:00
Hadrien Kerlero a692f9f193 fix(web): decide the history notice per replay move and drop unused anchor fields (#814)
- Content-anchored replay travel reveals the notice on an upward move that reaches row 0 and retires it on a downward move back at live output, as a live scroll does.
- _captureViewportAnchor returns only viewportY, rowsFromBottom and context; tests read anchor.context.
2026-11-22 02:44:24 +01:00
Hadrien Kerlero 1f9b17e29a fix(web): keep drop recovery bounded and the notice in step with replay travel (#814)
- _onSessionNeedsRefresh clears the Reload mark only after a completed mux replay.
- A later drop during an open load keeps the deferred recovery's higher attempt.
- Replay travel that reaches row 0 reveals the partial-history notice; at live output it retires it.
- The onScroll coalescing test drives the scheduler instead of evaluating a source line.
2026-11-22 02:44:24 +01:00
Hadrien Kerlero 193f220f5e fix(web): hold the reader past a 2,000-row gap and drop stale drop recoveries (#814)
- _restoreViewportAnchor searches expected - 4000 + rows .. expected + rows
  (same 4,001 candidates / 4,064 reads): filled rows only move the reader
  up, so gaps up to 4000 - rows land exactly, also at the scrollback cap.
- _resetAllAppState and _cleanupPreviousSession clear
  _pendingDroppedOutputRecovery next to the recovery timer, so a reconnect
  load does not resume a stale recovery and run a second full capture.
- Tests: capped 2,500- and 3,900-row gaps; both real cleanup methods drop
  the pending recovery. Docs: the window and the beyond-window fallback.
2026-11-22 02:44:24 +01:00
Hadrien Kerlero 6311e59412 fix(web): keep the reader's line when Load full history stands in for Reload (#814)
- The notice's Load full history button pulls with anchor 'content' when
  Reload history is eligible (read at click time, since the bar only
  re-renders on eligibility transitions) and keeps 'top' otherwise.
- Tests: the single load control asserts the content anchor; an
  ineligible session keeps the top anchor.
2026-11-22 02:44:24 +01:00
Hadrien Kerlero b3698756a2 fix(web): retire Reload history on the drop-recovery shrink fallback (#814)
- _onSessionNeedsRefresh adds the session to _historyReloadDismissed when
  the full capture would shrink the buffer and it falls back to ?tail=,
  past the ownership guard, so a no-history pane is not re-captured by
  the next tap.
- Changeset: scope the note to agent sessions (seen with OMP).
- CLAUDE.md: one warning sentence on the Reload history rules.
- terminal-resilience test reads each whole method instead of a
  4,000-character window.
2026-11-22 02:44:24 +01:00
Hadrien Kerlero bc00ad4335 fix(web): clear the Reload mark after a drop-recovery capture (#814)
- _onSessionNeedsRefresh samples the live-output generation before its
  fetch and, after replaying a mux-full-history capture, clears
  _liveOutputSinceFullPull and _historyReloadDismissed while it still owns
  the active session and the generation is unchanged; the ?tail= fallback
  never clears them.
- test/terminal-viewport-marker.test.ts: gated test driving the real
  flushPendingWrites over @xterm/headless at a full scrollback; the reading
  row holds with the marker and drifts without it.
- Docs: the anchor sentence matches minimumScore, and the refresh rule is
  in the Repair while reading paragraph.
2026-11-22 02:44:24 +01:00
Hadrien Kerlero 444f375ac7 fix(web): retire Reload history after a non-capture answer (#814)
- A content-anchored reload answered by anything but mux-full-history (an
  empty response, or the byte-history fallback for a blank or failed pane
  capture) adds the session to _historyReloadDismissed until the next mux
  replay; only a mux replay clears the mark, so each tap repeated a forced,
  unbounded capture. An error envelope leaves it available.
- Only the request still current (active session and select generation)
  may dismiss: a slow answer from before an A -> B -> A switch must not
  retire the action a newer capture already cleared.
2026-11-22 02:44:24 +01:00
Hadrien Kerlero 5f0366c060 fix(web): keep Reload history off while the incoming tab loads (#814)
- _historyReloadActionEligible() also requires no terminal load state:
  selectSession sets it before switching activeSessionId, so the sync
  right after the switch no longer offers Reload for the loading tab.
- _clearTerminalLoadState() re-syncs the action, so a marked tab offers
  Reload once its load ends.
- Changeset: note the reading-position fix for live flushes at the
  scrollback cap.
2026-11-22 02:44:23 +01:00
Hadrien Kerlero b4d729a054 fix(web): offer Reload history after a burst in a session opened empty (#814)
- _historyReloadActionEligible() no longer reads _paneHistoryLines: it is
  recorded at the last load, so a session first opened empty kept 0 after
  the burst that opens the gap, and the action never appeared (found by the
  live #814 recipe).
- A pane with no tmux history is still retired by the downgrade refusal,
  which dismisses the action until the next mux-full-history replay.
2026-11-22 02:44:23 +01:00
Hadrien Kerlero 9ef47aca6c fix(web): retire refused Reload history and hold the reading row (#814)
- Reload history requires pane history and no buffer load in flight; a
  downgrade-refused pull hides it until the next mux-full-history replay,
  and a stale tap re-checks eligibility before fetching.
- x during Loading... hides the bar at once; the pull continues.
- The content anchor scores up to 64 visible rows, so repeated TUI borders
  cannot outvote the row being read; ambiguous matches keep the viewport.
- Live flushes track the reading row with an xterm marker across
  scrollback trimming at the cap.
- Docs: Settings-Reference row, Dashboard notice text, ~1 s capture cost,
  byte-history replays rely on the top-of-buffer pull.
2026-11-22 02:44:23 +01:00
Hadrien Kerlero fd6b392b4d fix(web): make the early history repair a manual Reload history action (#814)
- Scrolling pulls tmux history only at the top of the buffer again (#205);
  the automatic pull on any upward scroll is removed.
- Reload history lives in the existing #historyTruncationBar on desktop and
  touch, shown for a marked non-shell session scrolled away from live output.
  It never duplicates Load full history; one × dismisses what the bar carried.
- New per-device setting historyReloadAction (Terminal & Input > Scrolling &
  rendering), default on, kept out of SettingsUpdateSchema.
- Eligibility sync is transition-only and onScroll is coalesced per frame.
- Remove the floating #historyReloadBtn and its z-index 20 layer.
- Deferred dropped-output recovery resumes at its saved attempt.
- zh-CN entries for the new strings; docs and changeset updated.
2026-11-22 02:44:23 +01:00
Hadrien Kerlero b890ef3302 fix(web): repair the history gap while reading, queue download-time output, add a phone reload control (#814)
Review follow-up on #815, and the phone case from #814: the gap opens
below a reader who stays scrolled up while output arrives, and the
bottom-only trigger never fired there.

- Open the buffer load before the capture fetch so output arriving during
  the download is queued and replayed, not wiped by the reset. Every
  non-replay exit flushes the queue. A drop at the 128 KiB cap during an
  open load is deferred and resumed when the load ends instead of
  spending its retries against it.
- Clear the live-output mark only when the response is
  source 'mux-full-history', on the scroll and tab-switch paths.
- Repair on any upward scroll in a marked non-shell session, not only
  from the bottom. A content anchor (3-row signature, searched at most
  2000 rows either side) keeps the row being read in place; no match
  falls back to distance from the bottom.
- Tie replay travel to its session so a tab switch does not swallow
  moves on the new tab.
- Reveal the partial-history notice when the initiating gesture
  reached the top, even if the anchor moved the viewport off row 0.
- Touch-only Reload history button (#historyReloadBtn), styled in
  styles.css so wide touch viewports get it too. Non-touch pages skip
  its work entirely.
- Docs, JSDoc and a changeset. Unit tests, and a Playwright browser test
  with trusted touch events and real xterm.

Fixes #814
2026-11-22 02:43:56 +01:00
Hadrien Kerlero fd31315582 fix(web): keep fetch-time output dirty and clamp replay travel per move (#814)
Review follow-up. The early re-pull sampled the live-output generation after
its fetch, but nothing gates live output while the capture downloads, so
output newer than the capture was overwritten and the session marked clean.
Sample before the fetch.

Travel made during the replay was one signed sum clamped once, so scrolling
to the bottom and back up cancelled out. Record moves in order and clamp
after each, as live scrolling does.
2026-11-22 02:43:30 +01:00
Hadrien Kerlero e91c62885a fix(web): recover the tmux repaint gap above the live screen on the first scroll-up (#814)
A tmux repaint burst overwrites rows that never reach xterm scrollback,
leaving a hole just above the live screen. The #205 re-pull only fired at
viewportY 0, so the user had to scroll past the hole first.

Mark a non-shell session dirty on each live write; the first upward scroll
from the bottom of a dirty session runs the existing full-history re-pull
anchored to the bottom, keeping the viewport's distance from live output and
replaying travel made during the replay. Cooldown, downgrade guard and the
top-of-buffer path are unchanged.
2026-11-22 02:43:30 +01:00
Hadrien Kerlero 2d818e39bf docs: describe caret generation and the parsed-write wait (#830)
caret() also returns generation; the parsed-buffer marker waits for a parsed write only when it changes.
Say the wait is a heuristic, not a delivery acknowledgement.
2026-11-21 23:05:53 +01:00
Hadrien Kerlero cda5d96451 fix(web): exact iOS caret, review fixes and round-eight items (#830)
Toolbar Enter spends one-shot Ctrl; Backspace finds the last grapheme with Segments.containing(); accessory Shift+Tab keeps the draft like a typed one.
Pass the captured session to Compose uploads, voice compose and held CJK drafts; clear Ctrl on deletion-only native edits; path picker clears predictions.
Clear xterm dead-key state on native commits; restore a borrowed clipboard field before classifying a key; overlay removeChar spans the pending/flushed boundary.
Place the trackpad caret from the overlay layout (getInputAnchor, committedText) or validated xterm cells, hiding when unproven; no end-minus-width arithmetic.
Grapheme-aware replay Backspace; docs, README rows, changeset and comment updates.
2026-11-21 21:16:13 +01:00
Hadrien Kerlero 414dd51eb2 fix(web): send a typed combining mark as a plain append (#830)
Both editBetween() functions return a pure append as-is before the grapheme split, so a mark typed onto the last letter is not a DEL plus the retyped cluster (zsh would double the base letter).
Drop a redundant setFlushed() in the Tab-completion fallback; detectBufferText() already stores it.
2026-11-21 16:09:24 +01:00
Hadrien Kerlero e4ac7728ba fix(web): count Android recovery deletions in graphemes, release the overlay change (#830)
The keyCode-229 recovery diff counts grapheme clusters, matching the overlay and the iOS owner, so one Backspace on a multi-code-point emoji is one DEL.
List xterm-zerolag-input in the changeset; document getInputEndAnchor(), onLayout() and the grapheme unit of removeChar().
2026-11-21 07:18:51 +01:00
Hadrien Kerlero 71c7d01d02 fix(web): delete one grapheme per iOS Backspace, keep the recovery fallback (#830)
Count native edits and overlay deletions in grapheme clusters (Intl.Segmenter, code-point fallback), so one Backspace on a multi-code-point emoji sends one DEL.
Toolbar Enter with echo off tells the codex predictor about the CR, clearing its predictions as typed Enter does.
Fall back to the keyCode-229 recovery when the iOS owner refuses to start, in the main pane and tiles.
2026-11-21 04:13:40 +01:00
Hadrien Kerlero 05fc2f990b fix(web): scroll to the prompt on toolbar Enter, retire app.sendInput (#830)
submitFromToolbar() puts the CR on the FIFO, bypassing xterm scrollOnUserInput; scroll the focused pane before sending.
Remove app.sendInput(), which has no production caller; update @dependency headers and test stubs.
Retarget the codex predictive-echo recorders to _enqueueReliableInput.
Correct the docs and the _sendInputAsync JSDoc for the session FIFO; drop stale _pendingInput stubs.
2026-11-21 01:34:27 +01:00
Kamil KaliszandClaude Opus 5.5 5ff018772e test(auth): multi-user still challenges a header-less request during lockout
The single-user suite pinned this; the multi-user one only showed that
header-less requests are not counted. Fill the per-IP bucket with
malformed headers, then expect 401 + challenge for no header and 429
for another malformed one. Fails on master.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:09:25 +01:00
Kamil KaliszandClaude Opus 5.5 cc2b7d9c25 docs(auth): list the no-header step after the Basic check; changeset
The pipeline list said it "runs in this order" but put the no-header
challenge before the HTTP Basic check, while single-user auth.ts checks
the correct password first. Swap steps 3 and 4. Note in the README and
the Security / Remote-Access wiki pages that a request with no
credentials is never counted, and add the patch changeset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:08:26 +01:00
Hadrien Kerlero ddb5a647ba fix(web): bind Send on Enter to the captured session, keep the voice draft (#830)
Held-mode Ctrl, Backspace and restored drafts send to the session their text was typed for; a Ctrl-only field releases it.
Voice compose Send settles the iOS owner without flushing the unsent local-echo draft.
Cover Send on Enter across focus moves, the toolbar Enter in the CJK field and the same-session reload.
Describe Pane B iOS input ownership; drop a stub for a removed helper.
2026-11-20 21:11:33 +01:00
Kamil KaliszandClaude Opus 5.5 ad08cb957d test(auth): malformed headers still fill the bucket; document the challenge
Review on #838. The unchanged half had no test: send the cap's worth of
`Authorization: Bearer x` and expect the next request to be 429, in
single-user and multi-user mode. Both fail if the header-less skip is
widened to malformed headers.

docs/security-architecture.md gets a pipeline step for the header-less
challenge (not counted, even during a lockout), and the Rate limit rows in
CLAUDE.md and docs/architecture-invariants.md say so, so a later change
cannot bring the counting back unnoticed. auth.ts uses challengeBasicAuth()
at the two spots that still inlined it, with a blank comment line before
the new paragraph.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 20:36:03 +01:00
Hadrien Kerlero eb22f10fd4 fix(web): scroll to the prompt on iOS native input (#830)
The native owner bypasses xterm triggerDataEvent, so scrollOnUserInput never ran; scroll before sending.
Derive the local-echo overlay switch from the echo policy instead of a second mode check.
Link docs/ios-native-input.md and describe Pane B input ownership on iOS.
2026-11-20 20:13:31 +01:00
Hadrien Kerlero db5ab5a701 fix(web): address #839 review for the iOS keyboard fix (#830)
Keep the unsent draft out of slash-command keys; settle the iOS owner without flushing local echo.
Restore the overlay last-prompt fallback and the #520 Shift/Ctrl+Enter gate guard.
Pin the xterm privates the iOS owner needs; retarget browser/mobile harnesses to the session FIFO edge.
Document the session FIFO invariants and link #830 for the device sequences.
2026-11-20 20:13:31 +01:00
Hadrien Kerlero c4b382b727 fix(web): synchronize iOS keyboard edits (#830)
Keep one native-input owner per iOS terminal and reconcile keyboard edits without duplicate producers.
Preserve session-bound input ordering, local-echo Unicode deletion, and visual caret geometry.
Cover device event sequences and lifecycle handoffs; remove obsolete helpers and source-text-only regression tests.

Fixes #830
2026-11-20 20:13:30 +01:00
Codeman maintainer 5548c17c4a chore: version packages
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:46:20 +01:00
Codeman maintainer 1d33220493 chore: the changeset for the next release
One changeset for everything since 1.51.0: the eleven PRs merged on this
branch, #803's MLX row and #812 already on master, the dead-code cleanup and
the fixes applied while landing. It replaces the eight PR changesets. Patch
until the owner says otherwise.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:10:15 +01:00
Codeman maintainer baf9d6a6a4 chore(web): two constants got their own comments back
Removing THROTTLE_DELAY_MS and STATS_POLLING_INTERVAL_MS in 6fb8b277 left
each neighbour carrying the deleted line's comment, so the toast maximum read
as a throttle delay and the terminal sync wait as stats polling.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:07:43 +01:00
Codeman maintainer d00a8d6cbf test(discord): the review items of #832 that go on top
A test pins the symlink and non-file branch of the reply store (a planted
link or a folder at the metadata path is never replaced, and replies are
still accepted), the @fileoverview names the file, its bounds, where the
bridge claims and the four rules a reader has to keep, and a comment left
from the #793 journal approach says store file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:06:03 +01:00
Codeman maintainer a9ed3f55c3 Merge #832: a replayed Discord reply is typed once, and a store failure never costs a reply
Each allowed Discord reply is claimed by its message id in a small private store (discord-reply-dedupe.json, 0600) before the rate-limit and exited-agent checks; when the store fails the bridge falls back to memory and still types the reply.
2026-11-20 04:05:22 +01:00
Codeman maintainer acd90efe73 fix(webview): the review items of #825
The owner of a managed dsh tab is compared with the server's starter only in
multi-user mode: a record created there keeps its owner, while a single-user
start records none, so that tab would never get its cookie again (new route
test). CLAUDE.md and the invariants doc name the cookie rules. The third item,
Codeman's session cookie filtered on the WebSocket leg whether or not the dsh
cookie is injected, came in with the merge itself, where it met #827.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:04:58 +01:00
Codeman maintainer 9d0f29fb22 fix(header): the two review items of #824
The format check passes again (Prettier breaks the createCpuUsageMeter call
one argument per line), and the load-average fallback answers 0 instead of
dividing by a core count of 0 on the platform it exists for, where cpus()
is empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:03:46 +01:00
Codeman maintainer 6a5b818f65 chore(docker): the two review items of #822
A comment says why the wait after the kill keeps its 2>/dev/null (bash 3.2
prints a Terminated job line there, bash 5.2 does not, so CI would not
notice its removal), and the two probe tests use the file's own imports.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:03:18 +01:00
Codeman maintainer 507116f019 docs(tmux): name the tmux releases a one-binding list-keys answer is blank on (#821)
The blank list-keys -T answer is not a development-build quirk: tmux commit
09bd686327 sent a one-binding listing to a status message instead of stdout,
and it shipped in 3.7, 3.7a, 3.7b and 3.7c until 7ec94fda08 fixed it for 3.8.
The comments, the tests and the invariants doc now say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:02:36 +01:00
Codeman maintainer 8202e07286 fix(watchers): the two review items of #818
The fs.watch failure tests skip on macOS, where chokidar 3 never calls
fs.watch for these watchers (fsevents, or polling without it), so the stub
never fired and the waits timed out. TeamWatcher.stop() clears its outage
set, so a stop() and start() on the same instance warns again about a
watcher that still fails; a new test pins it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:02:07 +01:00
Codeman maintainer 6222444e82 Merge #820: Send on Enter for the pinned CJK input field
A per-device mode for the pinned CJK field on phones: a typed answer stays in the field while the terminal scrolls and goes out only on Enter.
2026-11-20 04:00:05 +01:00
Codeman maintainer 1207c316c0 Merge #834: codeman tui attaches by session name
codeman tui <name> attaches by an exact session name as well as by list number.
2026-11-20 04:00:05 +01:00
Codeman maintainer 923db64a10 Merge #831: the wheel is forwarded for any CLI whose registry entry asks for it
The wheel gate reads each CLI's wheelForward rule from the registry (window.__codemanWheelForward) instead of a list of ids, so a custom full-screen CLI in clis.json can opt in.
2026-11-20 04:00:05 +01:00
Codeman maintainer 756d8d875e Merge #818: a chokidar watcher whose fs.watch fails is closed instead of retrying forever
A persistent:false watcher closes on its first error (closeWatcherOnError), so a failing fs.watch costs one warning instead of an endless climb to /, and TeamWatcher re-creates a stopped watcher from its 30 s poll.
2026-11-20 04:00:05 +01:00
Codeman maintainer f25e94141f Merge #825: proxied dashboards render in a web tab (dsh token, relative base, dynamic imports)
The DeepSeek Harness web tab trades the dsh web launch token for its session cookie, a relative <base href> resolves against the document's own directory, and root-absolute import("/...") inside scripts is rewritten onto the proxy prefix.

# Conflicts:
#	src/web/routes/webview-routes.ts
#	test/routes/webview-routes.test.ts
2026-11-20 04:00:05 +01:00
Codeman maintainer c31e4fc716 Merge #824: the header CPU reading shows CPU use, not the load average per core
Busy time across all cores, sampled over a window of at least a second (#823).
2026-11-20 03:59:10 +01:00
Codeman maintainer 99a69a87cf Merge #822: Start-Codeman.sh gives each port probe about a second
A dropped 127.0.0.1 connect (seen on WSL) no longer stalls the first run on the kernel's connect timeout.
2026-11-20 03:59:10 +01:00
Codeman maintainer 5df5628518 Merge #821: a key table reduced to one binding is read from the full listing
tmux 3.7 to 3.7c print a one-binding list-keys -T answer as a status message instead of stdout; Codeman now falls back to the full list-keys listing.
2026-11-20 03:59:10 +01:00
Codeman maintainer 4344ce8c11 Merge #827: a trusted web tab's WebSocket leg no longer forwards Codeman's session cookie
The WebSocket upgrade filters codeman_session out of the Cookie header the same way the HTTP leg already did.
2026-11-20 03:59:10 +01:00
Codeman maintainer b732cec36d Merge #826: a password-protected Codeman can be installed as an app
The manifest link fetches manifest.json with the session cookie (crossorigin=use-credentials), so the browser no longer gets a 401 for it.
2026-11-20 03:59:10 +01:00
Kamil KaliszandClaude Opus 5.5 bee4948e1a fix(tmux): see an exited agent on tmux 3.8, which blanks a dead pane's pid
tmux 3.8 prints #{pane_pid} blank once a pane's program has exited.
parsePaneRows() skipped any row without a numeric pid, so the watcher
never saw an exited agent: the session stayed idle with no paneExit and
the clean-exit sweep (#446) never closed it. reconcileSessions() read the
same rows, so at server start such a session's record was dropped while
its tmux session stayed on the socket.

Keep a dead row with no pid (a live one is still a bad read), tell one
exit from the next by #{pane_dead_time} next to the pid, and keep a
tracked session with a dead pane alive with its last known pid. An
untracked one is still not rediscovered: a made-up pid would reach
killSession()'s process-tree walk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:11:30 +01:00
JD c7b6e1cb4e fix(watchers): re-arm a stopped TeamWatcher watcher from the poll
chokidar 3 reports a one-off ENOENT race (a new file gone between its
stat and its watch) through the same TypeError as a lasting EMFILE, so a
watcher that stayed closed ended live team and task updates until a
restart. Each poll tick now re-creates a stopped watcher, as
WorkflowRunWatcher already does, and an outage warns once rather than
once per attempt. Also imports getErrorMessage from the types barrel.
2026-11-19 02:52:40 -05:00
JD b5a356dadf docs(cli-registry): say a version-gated wheel rule needs gates to forward
A version-gated rule reads the session's cliVersion, which the server
probes only for an entry that declares capabilities.gates, so a custom
entry with version-gated and no gates never forwards. Also brings the
claude and copilot comments in line with the code that now reads them.
2026-11-19 02:39:47 -05:00
Kamil KaliszandClaude Opus 5.5 363de086fc fix(auth): stop counting credential-less requests as failed logins
After a server restart every cookie session is gone (they live in memory).
An open tab's background requests then carry only the dead cookie and no
Authorization header. Each one was counted as a failed login: ten filled
the single-user per-IP bucket within seconds, and the 429 that followed
carries no WWW-Authenticate challenge, so the browser never showed its
login dialog again and reloading could not recover for 15 minutes. Behind
a tunnel all clients share 127.0.0.1, so every device was locked out.
Multi-user mode had the same shape against its per-IP pre-gate, which
refuses even a correct password once full.

A request with no Authorization header is not a guess and runs no
password check, so it is now challenged with a plain 401 and not counted,
in both modes and even while the IP is limited. Wrong and malformed
credentials are counted and limited exactly as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 17:33:53 +01:00
Kamil KaliszandClaude Opus 5.5 d7b195a783 fix(tui): the not-found hint no longer says --list shows the names
The --list column is rowLabel() cut to 48 characters: an unnamed session
shows its folder, a long name ends in an ellipsis, and neither resolves as
a name. Point at attaching by number instead. Review on #834.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 11:21:22 +01:00
Kamil KaliszandClaude Opus 5.5 d9ded95b95 docs(readme): attach by name in the zh-CN tui example
Review on #834.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:12:51 +01:00
Kamil KaliszandClaude Opus 5.5 8b809da466 docs(tui): keep docs/tui.md hand-formatted, show attach by name
Review on #834: drop the Prettier reflow of docs/tui.md and keep only the
new example line and paragraph, put "two" back in the fast-paths
sentence, list <n|name> in the tui-app.ts fileoverview, and add a
codeman tui <name> line to the README and the Remote Access wiki page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 08:56:04 +01:00
Saqeb Akhter ce899f59cc docs(discord): document reply replay guard in agent guide (#218) 2026-11-18 11:07:32 +04:00
Saqeb Akhter 44459a12dd fix(discord): claim refused replies before rate limiting (#218) 2026-11-18 11:04:02 +04:00
Kamil KaliszandClaude Opus 5.5 974b85493c test(cli): the tui operand is now [session]
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 23:52:17 +01:00
Kamil KaliszandClaude Opus 5.5 a36b875363 feat(tui): attach by session name, codeman tui <name>
codeman tui <session> takes a list number or a session name. Digits only
stay a number; anything else matches the session name exactly
(case-sensitive, never a prefix, folder or prompt). Names are not unique,
so two live matches refuse and print their numbers; a name only a RECENT
row carries says the session has finished. The target is resolved before
the TTY check, so scripts get these answers without a terminal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 23:23:56 +01:00
Saqeb Akhter 7343274d5f fix(discord): heal invalid reply metadata after upstream review (#218, #258) 2026-11-18 00:38:59 +04:00
Saqeb Akhter ba4a1c16e2 fix(discord): tolerate reply dedupe storage failures (#218, #258) 2026-11-17 23:25:43 +04:00
Kamil KaliszandClaude Opus 5.5 c639b38c1a fix(mobile): case sheet lift on a partial pan, live placeholder language
- The phone case sheet (#mobileCasePickerModal) is inside .app, so once
  .app follows a pan it takes the same insideLift as the bars. The layout
  gap on top lifted it twice (186px above the keyboard at offsetTop 100).
  Comment, architecture-invariants and a test case updated.
- setHoldUntilEnter() writes the placeholder before the unchanged-mode
  early return, only when the text differs, so a live language switch
  shows up without touching the rest of the field.
- Settings-Reference: Shift+Enter needs a hardware keyboard.
- styles.css: the #cjkInput cap is a backstop now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:08:26 +01:00
Kamil KaliszandClaude Opus 5.5 e85bb83353 fix(mobile): pinned field on phones: swipes, focus scroll, viewport pan, iOS lift
Found on a real Android phone (Chrome) and iPhone (Safari) with Send on Enter:

- A swipe that started on the live screen closed the keyboard: the content
  touchstart blurred the focused input before the gesture was known to be a
  tap or a scroll. It now skips the visible #cjkInput
  (_contentTouchStartBlurs()); a real tap still closes it (inert content, a
  link, a long press).
- Focusing the field scrolled the terminal off screen: KeyboardHandler's
  focusin scrollIntoView({ block: 'center' }) centred the fixed field in its
  ancestors. isInputElement() skips #cjkInput like xterm's inputs.
- Android pans the visual viewport to reveal the field (offsetTop 285 in a
  458/744 viewport), leaving only the terminal's last line visible. On phones
  .app now follows visualViewport.offsetTop while the keyboard is up, and the
  fixed bars inside .app are lifted from .app's bottom, so a partial pan does
  not lift them twice. Non-phone branches and resetLayout() clear the shift.
- On iOS the first keyboard open reported innerHeight as the visual height
  (323 vs 640), zeroing the bars' lift; the layout height is now the larger of
  innerHeight and documentElement.clientHeight.

Tests in test/keyboard-handler-pinned-field.test.ts and
test/terminal-touch-tap.test.ts; docs in architecture-invariants and
src/web/CLAUDE.md; changeset sentence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:45:20 +01:00
JD 3ef4900e60 fix(web): forward the wheel for any CLI whose registry entry asks for it
The browser's wheel gate named copilot, pi, claude and codex by id, so a custom clis.json entry that launches pi could not get the forwarding #771 gave stock pi: after every tab switch or reload its wheel scrolled an empty local buffer. Copying pi's altScreen value into such an entry made it worse, since the mouse DECSETs were then stripped while nothing forwarded the wheel.

The server now publishes every CLI's wheelForward rule as window.__codemanWheelForward, disabled entries included because disabling a CLI leaves its sessions running, and _shouldForwardWheelToApp reads that map instead of an id list. Stock CLIs keep their behaviour, and a minVersion that is not MAJOR.MINOR.PATCH refuses forwarding instead of comparing as passing.
2026-11-17 00:43:09 -05:00
Kamil KaliszandClaude Opus 5.5 3c5b7e2199 fix(mobile): Send on Enter placeholder i18n, one-line field on desktop
- input-cjk.js translates its placeholder with CodemanI18n.t(), like the
  prompt composer, since i18n.js skips <textarea> subtrees; the zh-CN
  entries now show.
- The field only grows on touch devices, where it is position: fixed.
  On a desktop it sits under the terminal, so growing would shrink the
  terminal box and resize the PTY on every line; it stays one line and
  scrolls there.
- Input And Voice: a line break needs a hardware keyboard (no Shift+Enter
  on a phone keyboard, and the extended bar's newline key goes to the CLI).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 06:42:37 +01:00
Kamil KaliszandClaude Opus 5.5 57fdb52f7c fix(mobile): turning Send on Enter off drops the held draft
setHoldUntilEnter going from on to off clears the stashed drafts and
resets the field, so live mode's next flush sends only the new key, not
a held multi-line draft. The invariants doc and the _handleCjkInput
comment name _sendCjkPrompt as the path a held answer takes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 02:37:01 +01:00
Kamil KaliszandClaude Opus 5.5 387cb830f4 fix(mobile): the clear-line key discards a Send on Enter draft
clear({ discard: true }) skips the owner stash, drops any older stash of
the owner and keeps the owner; clearTerminalInput() (the keyboard bar's
clear-line key) uses it, so a cleared draft does not come back on a
same-tab reload or a switch back. @fileoverview gains a Send on Enter
section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 00:37:16 +01:00
Kamil KaliszandClaude Opus 5.5 673a656538 fix(mobile): Send on Enter keeps drafts on every path, Ctrl stays in a held field
- CjkInput remembers which session the field's text belongs to (set by
  restoreDraft) and clear() stashes a held draft under it, so the paths
  that drop the active session before the next cleanup (goHome,
  _replaceTileGrid, _onTileAdoptedElsewhere) keep the answer.
  discardDraft() drops the owner of a removed session.
- Tile focus no longer stashes again for a tile closed from this tab.
- With a draft in the field, Ctrl shortcuts (undo, select all, copy) are
  the field's; they reach the CLI only while it is empty, like Backspace
  and the arrows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 22:25:02 +01:00
Kamil KaliszandClaude Opus 5.5 b5ad7afebe fix(mobile): Send on Enter fourth review fixes
- selectSession restores the CJK draft after _activateFileBrowserSession,
  which test/file-browser-search.test.ts pins right after the
  activeSessionId assignment.
- A lone digit while the session has a pending permission_prompt or
  elicitation_dialog goes out without the delayed Enter: the dialog acts
  on the digit, and the Enter would confirm whatever comes next. Same
  rule as the Approvals Inbox and the Discord bridge.
- Changeset mentions the toolbar Enter sending the CJK field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 21:53:27 +01:00
Kamil KaliszandClaude Opus 5.5 80d719df5f fix(mobile): keep the Send on Enter draft when going Home
goHome() nulled activeSessionId without stashing the field, so picking the
session again cleared the draft. Stash it first.

Docs: src/web/CLAUDE.md lists cjkInputHoldUntilEnter among the per-device
keys the strict schema does not declare, and notes the sendEnterKey()
exception for the visible CJK field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:38:20 +01:00
Kamil KaliszandClaude Opus 5.5 64ee504247 fix(mobile): Send on Enter second review fixes
- Never send a held answer as text + CR in one write: Codex folds an Enter
  in the same burst into a paste. A single character is typed, then CR
  ~120 ms later to the session captured at Enter; anything longer goes
  through _sendComposedPrompt. Drops HELD_DIRECT_MAX. No session keeps the
  text in the field.
- Cap #cjkInput at 68px on every device, not only touch.
- _autoGrow adds the border height and skips a hidden field.
- setHoldUntilEnter returns early when the mode is unchanged.
- Per-session held drafts: stashed on switch and tile focus, restored on
  return, dropped when the session is removed.
- Toolbar Enter presses Enter in the visible CJK field (commits an active
  composition first).
- Blank-only field sends a bare Enter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 17:39:22 +01:00
Kamil KaliszandClaude Opus 5.5 95fb147e9c fix(mobile): Send on Enter review fixes
- A long single line (over 64 characters) or several lines now go through
  the composer's _sendComposedPrompt: one bracketed paste, then Enter as a
  separate delayed write to the session captured at Enter. Claude Code took
  a long `<text>\r` burst as a paste and left it unsent, and the old delayed
  Enter followed a tab switch. A refused prompt keeps the text in the field.
- Deleting held text no longer sends Backspace to the PTY. It goes out only
  when the field was already empty (the phantom itself deleted), so
  select-all + delete is covered too.
- With the one-shot Ctrl armed, the next single typed character skips the
  hold and reaches _handleCjkInput, which turns it into the control byte;
  any other change spends the modifier, as in live mode.
- A reload of the session already shown (tapping its tab, the geometry
  retry) keeps a held draft.
- With the keyboard down the field stays one line tall, so it no longer
  covers the terminal's last rows.
- zh-CN strings for both field placeholders, and a test pinning
  cjkInputHoldUntilEnter as per-device.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 14:18:18 +01:00
Kamil KaliszandClaude Opus 5.5 14dccd462f fix(pwa): fetch the manifest with credentials so password installs can be installed
Browsers fetch the web app manifest without cookies unless the link sets
crossorigin="use-credentials". With a password set, manifest.json needs
the codeman_session cookie, so it answered 401 and Chrome refused to
install Codeman as an app.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 11:51:27 +01:00
ArizeSky 677e393fc3 fix(webview): stop forwarding the session cookie on the websocket leg
The WebSocket leg sent the browser's whole Cookie header to a trusted dashboard, including Codeman's own codeman_session, which the dashboard could then replay against the API. Filter it through filterCookieHeader like the HTTP leg, and omit the header when nothing remains.
2026-11-16 16:46:10 +08:00
ArizeSky 2a3496b7b3 fix(webview): keep the browser's cookies on the websocket leg
The HTTP leg puts the server-held dsh credential in front of the browser's own
cookies; the upgrade leg replaced them with it. A managed dsh tab is trusted, so
its other cookies must survive there too. Filter the request the way the HTTP
leg does and merge the credential in front.

Order is the point: a `Cookie` header can name the same cookie twice, and the
first value is the one parsers keep, so appending the credential let a stale
browser copy of the same dsh cookie shadow the one the running process minted -
the tab would come back to the 401 this path exists to prevent. Both legs now
lead with it, and a route-level test asserts the bytes the upstream sees on the
upgrade, not only on the HTTP request.
2026-11-16 16:30:25 +08:00
ArizeSky 44a10cff39 fix(deepseek): skip a tokenless banner line while scanning
The scanner now takes the first `dsh web:` line that parses as an http(s)
URL AND carries a token, as the boot contract describes, instead of
settling on an earlier plain URL and reporting no launch URL. The
tokenless line is still what identifies an older, ungated dsh in the wait
loop.
2026-11-16 16:14:45 +08:00
ArizeSky 06100a5506 fix(webview): rewrite dynamic imports only inside script bodies
The root-absolute import("/...") rewrite ran over the whole document, so
visible text such as <pre>import("/x")</pre> was rewritten too. Run the
specifier rewrite per <script> body and leave markup text untouched.
2026-11-16 16:12:53 +08:00
ArizeSky cc413afdd1 fix(webview): resolve a relative base against the document directory
rebaseRelativeBase resolved a relative <base> against the proxy root, so
a document served from a subdirectory of its dashboard (for example
/webview/<cap>/app/page.html with <base href="./">) pointed at
/webview/<cap>/ and loaded its assets one level too high. Pass the
request's wildcard path into rewriteHtml and resolve the base against
the document URL, which keeps the proxy root for the landing page.
2026-11-16 16:11:58 +08:00
ArizeSky 238853f96a fix(webview): keep dashboard cookies alongside the injected one
The managed DeepSeek tab is trusted, so the browser's own cookies for the
dashboard are forwarded. The injected dsh credential replaced that header
instead of joining it, dropping any other cookie dsh had set. Append the
pair to the filtered browser cookies and leave the rest untouched.
2026-11-16 16:10:51 +08:00
ArizeSky 7f729ee87b fix(deepseek): only exchange a banner for the spawned loopback port
The launch URL comes from the child's output but fetching it is a request
made by the Codeman server, so a banner naming another host or another
local service could aim it. Require 127.0.0.1 and the port just spawned
before the exchange runs, and mark the server as unusable for reuse if
the check fails.
2026-11-16 16:10:10 +08:00
ArizeSky b1bcd1e3af fix(deepseek): restart a server whose token exchange failed
Reuse returned the running server whenever it answered HTTP and matched
the authority, including one whose launch token could not be exchanged
for a cookie. That server answered 401 forever, so the restart the
warning asks for could never happen. Track the failed exchange and skip
reuse, which makes the next start request stop and respawn it.
2026-11-16 16:09:16 +08:00
ArizeSky 4ce9abde7d fix(deepseek): scan every dsh web line for the launch URL
The banner parser and the boot wait each took the FIRST `dsh web:` match,
so a diagnostic such as `dsh web: loading profiles` printed before the
banner made parsing return null on every poll and boot gave up after four
seconds. Scan every line and take the first payload that parses as an
http(s) URL, and only scan complete lines in the wait loop so a banner
split across two output chunks is waited for instead of being parsed
truncated.
2026-11-16 16:08:19 +08:00
ArizeSky 6e3d6ebad9 test(webview): cover the managed dsh cookie at the route level
Drive the real proxy route against loopback listeners and assert the
Cookie header dsh would receive: the minted port gets it, another port,
an unmanaged tab and a multi-user owner without the grant get none, and
a granted multi-user owner still gets it.
2026-11-16 16:06:34 +08:00
ArizeSky 28ed4016bd fix(webview): require the owner's privilege grant for the dsh cookie
`managed` is accepted from the client on POST/PATCH /api/webviews and
GET /api/deepseek/web publishes the live port, so a saved managed record
pointing at that port was enough to receive the dsh-auth cookie. Gate it
on the same privileged-commands grant POST /api/deepseek/web requires,
fail closed for an ownerless record in multi-user mode, and record the
user whose request started the process so the supervisor only hands its
cookie to that identity. A request from another owner restarts the server
rather than reusing a cookie that is not theirs.
2026-11-16 16:05:22 +08:00
ArizeSky 0ea97d62ec chore(webview): name a root-absolute request that escapes the proxy
When a web tab's boot module (or any asset it builds at runtime) escapes the
`/webview/<cap>/` prefix, the request reaches Codeman's 404 with nothing to relay
to: the frame's document URL is masked, so its `Referer` carries no capability
and the existing fallback declines. The tab then shows a blank page or a spinner
that never resolves, and the log says nothing — the failure mode that made the
DeepSeek Harness tab un-diagnosable twice.

Classify that shape conservatively on the 404 path (asset-shaped
`Sec-Fetch-Dest`, same-origin `Referer` at the masked landing path, not `/api`,
not one of Codeman's own files) and log the path once per five minutes. Nothing
is relayed or rewritten: this only turns a silent blank tab into one grep.

Also document the boundary in `docs/web-tabs.md` — the root-absolute URLs the
proxy never sees (runtime-built `import()`, imports inside external `.js`, static
imports in inline scripts, service-worker registration, `url()` in external
stylesheets) — so the next occurrence starts from the list instead of from zero.
2026-11-16 10:09:37 +08:00
ArizeSky 0b3087918f fix(deepseek): make the Harness web tab render, not just authenticate
`dsh web` gates its own index behind a per-process launch token it prints on
boot, and only that URL mints the `dsh-auth-*` cookie every later request needs.
The managed tab stores the clean URL, so nothing on the browser side could
present the token: the iframe rendered dsh's 401 text, a blank tab.

Read the token out of the captured boot output, trade it for the cookie once at
startup (`redirect: 'manual'`, since the 303 is what carries Set-Cookie), and
let the proxy present it on both the HTTP and WebSocket legs. Scoped to the
exact loopback authority the cookie was minted for; a token-less banner (an
older dsh) keeps the previous behaviour untouched. The banner is scanned on its
own 256 KB budget rather than the 16 KB error-tail buffer: a chatty profile can
fill that cap before the banner prints.

Authentication alone was not enough. dsh ships `<base href="./">`, which a
browser resolves against the DOCUMENT url — and the proxy's runtime shim
rewrites that url to strip the `/webview/<cap>/` prefix. The base therefore
landed on Codeman's root: every module script 404'd and the page painted its
inline `#151517` background with nothing on it (the black screen that replaced
the white one). `rewriteHtml` now resolves a relative base against the proxy
prefix before the mask can run, leaving a cross-origin base exactly as written.

Verified against dsh 0.2.1-rc.5 and a live Codeman build: bare GET 401, captured
cookie 200, proxied `/api` WebSocket 101, and a headless-Chrome load of the
proxied tab boots the full Harness UI with no console errors.
2026-11-16 09:47:23 +08:00
Ludo FourrageandClaude Opus 5.5 9304f98efb fix(header): the CPU reading shows CPU use, not the load average per core
The header's CPU figure was the 1-minute load average divided by the core
count, capped at 100. Load counts runnable tasks, not busy time, so a host
with bursty processes, or a VM whose vCPU threads count as runnable, read
100% while most cores were idle. It is now busy time across all cores
since the previous reading, from os.cpus(), with a one-second minimum
window on the monotonic clock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 14:56:33 -08:00
Aamer Akhter 0e913eedf2 fix(docker): bound Start-Codeman.sh's port probe to about a second
port_in_use() connected with bash's /dev/tcp and waited for the answer.
A listening port answers at once and a closed one is normally refused
at once, but on WSL a connect to a closed 127.0.0.1 port is dropped
and only fails at the kernel's connect timeout, minutes later
(measured: still waiting after 10 s; ::1 is refused at once). The
first-run port search tries up to 100 ports from 3000 and the start
path checks the chosen port again, so a first run on WSL stalled.

Each connect now runs in a background subshell that port_answers()
waits on for at most 20 x 50 ms, then kills; no answer in time reads
as free. Bash 3.2 clean: no `timeout` (macOS ships none), no `wait -n`.

Test: a python3 listener with a full accept queue (Linux drops further
SYNs, the same no-answer a WSL closed port gives) must be given up on
within 3 s; a listening port and a closed one still answer at once.
With the old unbounded connect the first test fails at its 10 s cap.
2026-11-15 15:09:20 -05:00
Aamer Akhter c497869ee5 fix(tmux): read a one-binding key table from the full listing
A tmux built from master (`tmux -V`: next-3.7) prints nothing, exit 0,
for `list-keys -T <table>` when the table holds exactly one binding.
tmux 3.4 prints the line. One binding is the shape
restrictTmuxPrefixTable leaves behind (`<prefix> send-prefix`), so on
that tmux the reduced table read as needing a reset and every session
create reset it again. `codeman tui` read its prefix table the same
way, so readPrefixBinding called a bound key free and readDetachKey
found no detach key.

A blank answer is now read from the full `list-keys` listing, keeping
only that table's lines. The parsers already match on `-T <table>`.

Tests: recorded-command cases for the blank answer (reduced table kept,
stray binding still reset) and TuiClient cases for both reads. The
real-tmux helper reads tables through the same fallback, and the
escaped `C-\` check accepts the unescaped form the full listing prints.
2026-11-15 15:06:07 -05:00
Kamil KaliszandClaude Opus 5.5 b8a4466643 docs(mobile): zh-CN strings and Input And Voice section for Send on Enter
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 18:42:59 +01:00
Kamil KaliszandClaude Opus 5.5 e0e2f689cf feat(mobile): Send on Enter for the pinned CJK input field
A per-device setting next to CJK Input keeps typed text in the pinned
field until Enter instead of streaming it to the PTY, so a phone user can
scroll the terminal and edit an answer before sending (Termux-style).
One line goes as text + CR, several lines as one bracketed paste with a
delayed Enter, like the prompt composer. Shift+Enter is a newline,
Escape clears, Backspace on an empty field still reaches the PTY, and
autocorrect is on in this mode. The field grows with its text and the
keyboard layout reserves its real height.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 18:38:25 +01:00
Codeman maintainer e4a85fabcd fix(mobile): the phone toolbar sits on the keyboard, and the prompt's last line is no longer under it
With the on-screen keyboard up, the toolbar and the keyboard accessory bar
kept a bottom offset of --safe-area-bottom (34px on a Face ID iPhone, since
the page sets viewport-fit=cover), although the keyboard covers the
home-indicator strip that inset reserves. That left an empty band between
the toolbar and the keyboard, and put the bars 34px above the room main's
keyboard padding reserves for them (84px, the two bars only), so the bottom
of the terminal box, the last line of the prompt being typed, was painted
under the accessory bar.

With the keyboard up the bars now stack from 0 (toolbar), 40px (accessory
bar) and 84px (CJK textarea), on iOS Safari and in the home-screen app alike.
Nothing changes with the keyboard down, on a tablet or on desktop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 14:00:34 +01:00
JD 10e443a309 fix(watchers): stop a chokidar watcher whose fs.watch fails instead of retrying forever
chokidar 3 with `persistent: false` has no guard for an `fs.watch` that throws (EMFILE once the inotify instance limit is used up, ENOSPC once the watch limit is). It emits the error, then a TypeError, then retries on the parent directory, and ends up re-adding `/` forever. TeamWatcher only logged its `'error'` events, so one failed watch became an endless stream of stack traces. WorkflowRunWatcher already closed its watcher on error, but `close()` removes every listener, so the TypeError from the same pass became an unhandled rejection, one per 10 s poll, and the server exits after five of those in a minute.

`closeWatcherOnError()` closes the watcher on its first error, keeps a no-op listener on it, and turns its `add()` into a no-op, since a callback chokidar still has in flight can otherwise re-add a path and reopen it. TeamWatcher logs one line per watcher and relies on its 30 s poll; WorkflowRunWatcher still drops the watcher and re-arms it on the next poll.
2026-11-14 15:14:35 -05:00
Codeman maintainer ab9c574ca4 fix(desktop): pasting an image with Cmd+V works in the Mac app
Cmd+V with a copied picture in a session's terminal did nothing in the Mac
app, while the same server worked in a browser.

Codeman's Cmd+V handler (_handleImagePaste, src/web/public/image-input.js)
focuses a hidden contenteditable trap and calls
document.execCommand('paste') before the key's own paste lands there.
Chromium refuses that call at once. From a WKWebView, WebKit answers it with
its DOM paste access menu ("Paste", opened at the last mouse-down) and holds
the page on a synchronous request until the menu is picked or the clipboard
changes. The key's own paste, the one that carries the image, was stuck
behind it.

Measured on macOS 27.2 (WebKit 22625) with a throwaway WKWebView probe:
- a menu Paste hands the page the image as a File for PNG data, a
  TIFF+PNG screenshot and a file copied in Finder, so WebKit itself is fine;
- Cmd+V through the same trap hung until the next clipboard change;
- with execCommand('paste') answered false, six Cmd+V presses in a row
  (image data, screenshot, Finder file, text, two repeats) each delivered
  exactly one paste event to the trap.

The fix lives in the app's HOST_SHIM, which every server page already gets:
it wraps Document.prototype.execCommand so 'paste' returns false the way
Chromium answers it, and every other command reaches WebKit unchanged. The
web page keeps its execCommand call: src/web/CLAUDE.md keeps it for mobile
engines that need it, and doing it in the app also covers servers on older
Codeman versions.

test/desktop-host-shim-paste.test.ts runs the shim's real text, cut out of
assets.rs, in a vm with a stub Document. shim_keeps_its_contract pins the
override too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 19:23:59 +01:00
160 changed files with 19852 additions and 1457 deletions

No files matched your search

-5
View File
@@ -1,5 +0,0 @@
---
"aicodeman": patch
---
**Mac app: server tabs.** The Mac app now keeps several Codeman servers open in one window, one tab each in the title bar, and switches between them with a click or ⌘1 to ⌘8. Every tab shows whether its server needs you, is waiting, is working or is offline, and ⌘0 shows all servers at once with the ones that need you first. ⌘T opens another server, a tab can be renamed, coloured and dragged, ⇧⌘T reopens a closed one, and your tabs come back at the next launch. On macOS 14 and later every server keeps its own login and cookies; before macOS 14 a second tab on the same machine is refused. Behaviour change: only the server you used last keeps its per-device settings (font size, skin); every other server starts those fresh once.
+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.51.0",
"version": "1.52.0",
"author": {
"name": "Ark0N",
"url": "https://github.com/Ark0N"
+72
View File
@@ -1,5 +1,77 @@
# aicodeman
## 1.52.0
### Minor Changes
- 7a3bbce: ### Thanks
- @HadrienKerlero for two big ones: the iPhone keyboard fix (#839, nine review rounds) and the Reload history action (#815, eighteen rounds), and for the reports that started both (#830, #814).
- @DodgyBadger for the Files panel that loads one folder at a time (#848), built on the design from #759.
- @kkalisz for three fixes: the login lockout after a restart (#838), exited agents on tmux 3.8 (#840, five review rounds), and the terminal dashboard's window size (#853).
- @bearyjd for the installer's multi-user guidance (#847) and the wiki section on keeping reverse-proxy hostnames across restarts (#845), a first contribution.
**Closing a tab can no longer signal every process of your account.** tmux reports pid 0 for a pane that has no process, such as an empty split beside the agent. A server restart could record that 0 for the tab, and closing the tab while that pane was the active one then signalled the children of pid 0, which is every process of the account: all sessions, tmux and the systemd user manager. A kill now never takes pid 0 or 1. Such a tab is closed by tmux alone and nothing else is signalled.
**The Files panel loads one folder at a time (#848).** Opening the panel reads only the top folder, and a folder is read when you open it, 500 entries a page with Load more. Large workspaces no longer stop at a scan limit, and Refresh keeps the folders you had open. Behaviour change: typing in the search box filters the folders already loaded, and Enter searches the whole workspace.
**iPhone keyboard suggestions, dictation and hold-delete work in the terminal (#839, fixes #830).** Tapping a suggestion used to send only its first letter, and holding delete never went word by word. Suggestions, text replacement, dictation and held delete now reach the agent as one ordered edit, in the main terminal, the split pane and every tile. A delayed Enter or paste stays with the session it was typed for when you switch tabs, and backspace deletes a whole emoji.
**Mac app: server tabs (#816).** The Mac app keeps several Codeman servers open in one window, one tab each in the title bar, and switches between them with a click or ⌘1 to ⌘8. Every tab shows whether its server needs you, is waiting, is working or is offline, and ⌘0 shows all servers at once with the ones that need you first. ⌘T opens another server, a tab can be renamed, coloured and dragged, ⇧⌘T reopens a closed one, and your tabs come back at the next launch. On macOS 14 and later every server keeps its own login and cookies; before macOS 14 a second tab on the same machine is refused. Behaviour change: only the server you used last keeps its per-device settings (font size, skin); every other server starts those fresh once.
**Fixes.**
- **An open tab after a restart no longer locks everyone out (#838).** A request with no `Authorization` header always gets the login prompt and is no longer counted as a failed login. Before, an open tab's background requests filled the per-IP limit within seconds of a restart, and everyone behind the same tunnel address was locked out for 15 minutes. Wrong passwords and malformed headers are counted as before.
- **Missing lines above the live screen can be fetched again (#815, fixes #814).** In some agent sessions (seen with OMP) a few lines were missing right above the live output until you scrolled to the very top. The history banner now has a Reload history action, on desktop and on phones, that fetches the whole history again and keeps the text you are reading in place. It can be switched off per device in Settings > Terminal & Input > Scrolling & rendering. Also, while you are scrolled up, new output no longer moves the text you are reading once the scrollback is full.
- **An agent that exited is seen again on tmux 3.8 (#840).** tmux 3.8 prints no process number for a finished pane, so a session whose agent had exited stayed on the board as idle, and a restart of Codeman dropped its record while its tmux session stayed behind. Such a session is now seen as exited and closed, as on older tmux. Finished sessions that piled up on tmux 3.8 are relaunched once, at the first start after this update. A dead `codeman-*` tmux session that was orphaned before this fix is not found again: remove it with `tmux -L codeman kill-session -t codeman-<id>`.
- **`codeman tui` takes its window size back (#853).** While a terminal is attached, the window follows whichever client was used last, as plain tmux does. Before, a browser tab that opened or resized the same session pinned the window to the tab's size until you detached and attached again. Now typing, pasting or resizing the terminal fills it again, and typing in the tab, or its Redraw, gives the tab the size. Needs tmux 3.3 or newer.
- **Closing a dialog you opened with the mouse puts the keyboard back in the terminal (#857).** After App Settings or Session Options was opened with a click and closed again, nothing you typed reached the terminal until you clicked it. A dialog now returns the keyboard to the field you were typing in when you clicked, which with the tile grid or the split open is the pane you were in. The Session Manager and the command palette follow the same rule, and a dialog opened with the keyboard still returns to the control it was opened from.
- **The Ledger tab layout shows the working spinner again (#851).** The ledger hid the status dot and the spinner with it, so a busy session looked like an idle one. A working cell now keeps the ring.
- **The phone toolbar sits directly on the keyboard (#819).** With the keyboard open on an iPhone, an empty band sat between the toolbar and the keyboard, and the last line of the prompt you were typing was hidden under the bar above it. Both are gone.
- **Mac app: pasting an image works (#817).** ⌘V with a copied picture did nothing in the Mac app, while the same server worked in a browser. Screenshots, images copied from an app, files copied in Finder and plain text now paste with one ⌘V, also from servers on older Codeman versions.
- **The installer explains multi-user mode and keeps it across re-runs (#847).** The done screen says how to create the first admin and switch multi-user sign-in on for a systemd unit or a LaunchAgent, and a re-run keeps an existing `CODEMAN_MULTIUSER` setting.
- **A hand-written quoted value in the systemd unit survives an installer re-run.** `Environment=CODEMAN_PASSWORD="my pass"` used to be dropped when the installer rewrote the unit, which left a server bound to the LAN without its password. It is now read the way systemd reads it.
**Fixes applied while landing.** The installer prints the manual multi-user start line only where no service runs, since next to a running service it would start a second server on the same data (#847). The Files panel no longer pages through a whole large folder looking for an open folder that was deleted, shows a folder that is still waiting to load as loading instead of empty, and its error line and single-match count read correctly in Chinese and English (#848). The resize nudge that lets a browser's Redraw win back the window runs only for sessions that have tmux behind them (#853), and the test for closing a live pane no longer reads the machine's real process list (#840).
**Docs and tests.** The Remote Access wiki page shows how to keep `CODEMAN_ALLOWED_HOSTS` across restarts with a systemd drop-in (#845), and the kill guard, the installer's unit reader and the Files panel restore have tests that fail without them.
## 1.51.1
### Patch Changes
- 1d33220: ### Thanks
- @kkalisz for Send on Enter in the phone's input field (#820), `codeman tui <name>` (#834), and a password-protected Codeman that installs as an app (#826).
- @ArizeSky for web tabs that render the DeepSeek Harness web UI and Vite dashboards (#825), and for closing a session-cookie leak on the web tab's WebSocket leg (#827).
- @JDProfresh for tracking a 174 GiB log flood down to a chokidar retry loop and fixing it (#818), and for wheel forwarding that any CLI entry can ask for (#831).
- @aakhter for the tmux 3.7 key-table fix (#821) and for Start-Codeman.sh on WSL (#822).
- @ludovicfourrage for the report and the fix that makes the header's CPU reading real CPU use (#823, #824).
- @johoja12 for Discord replies that are typed once, however often the gateway replays them (#832).
- @shenlvkang-collab for the report in #701 that led to answers on a relocated Claude config folder (#812).
**Phone: Send on Enter for the input field (#820).** A new per-device setting next to CJK Input, Input Field: Send on Enter. With both on, the field above the keyboard works like a chat box: your text stays there while you scroll the terminal to reread a question, Enter sends it, Shift+Enter adds a line and Esc clears it. The phone keyboard layout is sturdier for everyone too: a swipe on the live screen no longer closes the field's keyboard, and on iOS the bars sit on the keyboard the first time it opens.
**The terminal dashboard attaches by session name (#834).** `codeman tui <name>` attaches to a live session by its exact name as well as by its list number, so getting back into the same session over SSH no longer depends on where it sits in the list.
**Web tabs render the DeepSeek Harness web UI and Vite dashboards (#825).** The DeepSeek Harness web tab opened on a blank 401 page since `dsh web` started asking for a one-time launch token. Codeman now trades that token for dsh's session cookie and presents it only to that tab. Dashboards that ship a relative `<base href>` (what Vite and SvelteKit builds emit) and ones that load modules with `import("/...")` render through the web tab proxy too.
**Local model: Muse Glimmer 30B as its MLX build (#803).** On a Mac with 48 GB or more, Run a model on this Mac offers the MLX build of Muse Glimmer 30B. On an M5 Pro with 48 GB it wrote twice as many tokens a second as the GGUF build on the same request, and finished an OpenCode turn the GGUF build never answered. Macs with 32 or 36 GB keep the GGUF row as it was.
**Fixes.**
- **A failing file watcher no longer floods the log (#818).** When Linux ran out of inotify instances, a watcher whose `fs.watch` failed retried on each parent folder up to `/` and then forever, writing about 112,000 log lines a second until the disk filled. It now logs one warning and keeps working by polling, and the agent-teams watcher switches its live watcher back on once watching works again.
- **A password-protected Codeman installs as an app (#826).** The browser fetched the app manifest without the login cookie and got a 401, so Chrome's Install app refused. The manifest request now carries the cookie.
- **A trusted web tab's WebSocket no longer sends Codeman's session cookie to the dashboard (#827).** The HTTP leg already stripped it.
- **Answers come back for a session on its own Claude config folder (#701, #812).** A session started with `CLAUDE_CONFIG_DIR` (a second Claude account) showed "No response yet" in the response viewer, and `codeman agent read` and the Discord bridge's last message came back empty. They now read the transcript from that session's own folder.
- **tmux 3.7 to 3.7c: the prefix table and `codeman tui` keys read right (#821).** Those releases print nothing for a key table with exactly one binding, so Codeman reset its already reduced prefix table on every new session and `codeman tui` took a bound key for a free one.
- **`docker/Start-Codeman.sh` no longer hangs on WSL (#822).** Each free-port check gives up after about a second instead of waiting out the kernel's connect timeout.
- **The header CPU reading is CPU use (#823, #824).** It showed the load average per core, which read 100% on a host whose cores were mostly idle. Behaviour change: on such a host the figure is now much lower.
- **Discord: a replayed reply is typed once (#832).** A gateway replay, also after a restart, could type the same reply into a session twice. If the small store that prevents it fails, the reply is still typed.
- **A custom full-screen CLI can get the mouse wheel (#831).** The wheel went only to a fixed list of CLIs. It now follows each entry's `wheelForward` rule, so a `clis.json` entry can ask for it; stock CLIs behave as before.
**Fixes applied while landing.** The web tab proxy filters Codeman's session cookie off the WebSocket leg whether or not the dsh cookie is added, and a dsh tab created in multi-user mode still gets its cookie after a switch back to single-user mode (#825, #827). The CPU fallback no longer divides by a core count of 0 (#824). A watcher that a restart finds still failing warns again, and the watcher tests skip on macOS, where chokidar never calls `fs.watch` (#818). The Discord reply store has a test for a planted symlink at its path (#832).
**Docs and tests.** The docs name the tmux releases with the blank key-table answer, the DeepSeek web cookie rules and how a custom full-screen CLI asks for the wheel.
About 8,900 lines of code nothing reached are gone, among them the Ralph plan wizard that no button opened any more and the Agent Teams terminal windows; no route, setting or SSE event was removed. `npm run check:frontend-dead` lists frontend code nothing references.
## 1.51.0
### Minor Changes
+16 -14
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.51.0 (must match `package.json`)
**Version**: 1.52.0 (must match `package.json`)
## Project Overview
@@ -64,7 +64,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
**Requirements**: Node.js 22+, Claude CLI, tmux
**Git**: Main branch is `master`. Terminal session dashboard: `codeman tui` (`--list` to list, `codeman tui <n>` to attach).
**Git**: Main branch is `master`. Terminal session dashboard: `codeman tui` (`--list` to list, `codeman tui <n>` or `codeman tui <name>` to attach).
## Additional Commands
@@ -134,7 +134,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
**Agent CLI (`codeman agent …`, `src/cli-agent.ts`)**: the command-line client for the wait primitives and the session verbs, for agents the skill does not reach (pi, shell, no `jq`; `seedAgentSessionPreamble` covers every local session whose CLI takes the skill, `capabilities.agentSkillDir`; every pane still exports `CODEMAN_MUX`/`CODEMAN_SESSION_ID`/`CODEMAN_API_URL`). It is an HTTP CLIENT: inspection and guarded stage/submit use the ownership-checked `agent-session-routes.ts` module (experimental, behind `agentCoordinationEnabled`, SYNCED, default OFF: all three routes answer `403 FORBIDDEN` naming it while off, and the CLI shows that verbatim); the other verbs reuse existing routes, with no second transport (the plan's "Socket API" non-goal stands), every call carries `X-Codeman-Parent-Session`, only `spawn`'s quick-start carries `X-Codeman-Agent-Origin` (pinned in test/cli-agent.test.ts), while `spawn` without a case (cwd or `--working-dir`) is `POST /api/v1/sessions` plus `/interactive` or `/shell` without that header, so no agent-case marker, and refuses (exit 4, before any request) an empty `--working-dir` and a bare spawn from a HOME cwd, since it always sends an explicit `workingDir` and the server's no-`workingDir` hooks skip cannot apply (test/cli-agent-project-spawn.test.ts), auth (`src/codeman-credentials.ts`, shared with `codeman attach` and the TUI) from `CODEMAN_PASSWORD` or the data dir's `.env` (the same reader `codeman attach` uses — `readCodemanEnvFile`). Verbs return exit codes (`0` ok / `1` error / `2` timeout / `3` exited / `4` refused) instead of calling `process.exit`, so `test/cli-agent.test.ts` drives every verb against a recording fake transport plus the real `httpRequest` against a local server. ⚠️ Three guards live in code, not prose, and the tests pin them: refuse without `CODEMAN_MUX=1`+`CODEMAN_API_URL` (never guess a URL); `send` transmits printable text + `\r` only (`inputRefusal`: any byte < 0x20 or DEL refuses BEFORE the transport — opencode's `Ctrl+C` is `app_exit`), ESC exists solely as `interrupt` with no `\r`; `rm` fails closed (`deleteRefusal`: empty id, self shorter than 8, prefix match in EITHER direction, re-checked on the resolved id). ⚠️ The routes accept FULL ids only — an 8-char prefix is a 404 (measured live) — while `ls` prints prefixes, so `resolveSessionId` maps a short id through `GET /api/v1/sessions` and refuses an ambiguous one. It also refuses any id under 8 characters (exit 4, on every verb, before any request), the same floor as the server's `PARENT_SESSION_ID_MIN_PREFIX`, so `rm 9` can never pick an arbitrary session. ⚠️ A 400 for `--until stop` on a hook-less mode is passed through verbatim, never papered over: the marker path is the answer there. `spawn` on a readiness timeout exits 2 and LEAVES the session for inspection (the skill's `spawn_worker` deletes it; the CLI's caller is often a human); its stdout is the id ALONE (prose on stderr) so `SID=$(…)` works. ⚠️ Two server answers that look like success and are not: `delivered:false` without `duplicate` (the bytes went into a dead pane — the field exists so a client says "restart" instead of "wait longer") and `wait.ended:true, signal:null` (the worker died during a `stop`/`idle` wait: the registry satisfies only waiters that listed `exit`, then cancels the rest) — both exit 3, checked BEFORE the happy paths in `waitExitCode`. → README "`codeman agent`", `docs/api-reference.md`
**Discord bridge (`src/discord-bridge.ts`, `src/web/routes/discord-routes.ts`, `src/cli-notify.ts`)**: opt-in two-way Discord (a bot, not the one-way webhook), one thread per tab. Split like `webhook-notify.ts`: pure helpers, a 0600 store (`discord.json` holds the bot token, is never returned by these routes and is on the sensitive-path list; `discord-bridge.json` maps sessionId to thread id), then IO (`DiscordApi` REST with injected fetch, `DiscordGateway` inbound WebSocket with injected socket, `DiscordBridge` rules). Outbound hangs off `WebServer.sendPushNotifications` beside the webhook (so it works with zero push subscriptions) and tab events off `WebServer.broadcast` (`bridgeSessionEvent`); a finished turn (Claude's idle and stop hooks, DeepSeek's stop; the other CLIs raise no turn end, so theirs arrive with an error, a blocked respawn, a crash loop or `codeman notify`) or an error posts the CLI's WHOLE last message as markdown, read from its transcript through the response viewer's reader (`WebServer.lastResponseFor`, set by the session routes: the CLI's own transcript, or the pane segmented into turns for the CLIs that keep none; never for a shell), split over posts of at most 1900 characters and not posted twice (keyed on the text plus its turn, recorded only after the first post succeeds), while a dialog and every CLI without a transcript post the RENDERED tmux screen (`screenTail`, with the composer row and the status lines under it cut), never the raw stream, which a full-screen UI repaints in place; `staleThreads` (default `keep`) archives or deletes threads the bot owns that no tab maps to, after boot and then daily, never one under an hour old, never with an empty map and at most 25 per run. Inbound replies are typed through `session.writeViaMux`. ⚠️ Guards that live in code and tests pin: only `allowedUserIds`, in `guildId`, inside a thread the bridge created, are acted on, everything else is dropped unread; a reply is one printable line plus Enter (a lone digit while a permission or question is pending goes as the key alone, since the dialog acts on it), capped and rate limited, and `discord-notify` is a per-session token bucket (6 a minute, 429 `RATE_LIMITED`; `fileProblem` probes the folder with the bounded probe first); posts send `allowed_mentions` limited to the allowlisted ids; received files go only from Discord's own HTTPS hosts (max 5 x 8 MB, names reduced to `[A-Za-z0-9._-]`) into `<tab folder>/.codeman-discord/`, and a sent file's REAL path must lie inside the tab's folder (`fileProblem`, symlinks followed); a Discord failure never reaches a session; the alert tail is a function the bridge calls only once it will post (no tmux exec per event while off); a delete reaches the bridge from the cleanup path with `killMux` true, never from `session:deleted`, which a detach also fires; `.codeman-discord/` is probed with the bounded probe, refused if a symlink, and ignores itself with a `.gitignore` of `*`; a config restore of `discord.json` reloads the running bridge (`afterRestore`). The startup hint ("how to reach the user") rides the CLI registry as the engine value `appendSystemPrompt` (Claude's `--append-system-prompt`, undefined unless the bridge and `startupHint` are on, so every other launch is byte-identical) No other CLI is told. `codeman notify "<message>" [--urgent] [--file <path>]` wraps `POST /api/sessions/:id/discord-notify`, which accepts a unique 8-character id prefix (a Docker case exports it cut). → `docs/discord-bridge.md`, `docs/wiki/Discord-Bridge.md`, `docs/api-reference.md`
**Discord bridge (`src/discord-bridge.ts`, `src/web/routes/discord-routes.ts`, `src/cli-notify.ts`)**: opt-in two-way Discord (a bot, not the one-way webhook), one thread per tab. Split like `webhook-notify.ts`: pure helpers, a 0600 store (`discord.json` holds the bot token, is never returned by these routes and is on the sensitive-path list; `discord-bridge.json` maps sessionId to thread id), then IO (`DiscordApi` REST with injected fetch, `DiscordGateway` inbound WebSocket with injected socket, `DiscordBridge` rules). Outbound hangs off `WebServer.sendPushNotifications` beside the webhook (so it works with zero push subscriptions) and tab events off `WebServer.broadcast` (`bridgeSessionEvent`); a finished turn (Claude's idle and stop hooks, DeepSeek's stop; the other CLIs raise no turn end, so theirs arrive with an error, a blocked respawn, a crash loop or `codeman notify`) or an error posts the CLI's WHOLE last message as markdown, read from its transcript through the response viewer's reader (`WebServer.lastResponseFor`, set by the session routes: the CLI's own transcript, or the pane segmented into turns for the CLIs that keep none; never for a shell), split over posts of at most 1900 characters and not posted twice (keyed on the text plus its turn, recorded only after the first post succeeds), while a dialog and every CLI without a transcript post the RENDERED tmux screen (`screenTail`, with the composer row and the status lines under it cut), never the raw stream, which a full-screen UI repaints in place; `staleThreads` (default `keep`) archives or deletes threads the bot owns that no tab maps to, after boot and then daily, never one under an hour old, never with an empty map and at most 25 per run. Inbound replies are typed through `session.writeViaMux`. An allowed reply is claimed by message ID before rate-limit or exited-agent checks, attachments or typing; a store failure never costs a reply. A file that could not be read is never overwritten. ⚠️ Guards that live in code and tests pin: only `allowedUserIds`, in `guildId`, inside a thread the bridge created, are acted on, everything else is dropped unread; a reply is one printable line plus Enter (a lone digit while a permission or question is pending goes as the key alone, since the dialog acts on it), capped and rate limited, and `discord-notify` is a per-session token bucket (6 a minute, 429 `RATE_LIMITED`; `fileProblem` probes the folder with the bounded probe first); posts send `allowed_mentions` limited to the allowlisted ids; received files go only from Discord's own HTTPS hosts (max 5 x 8 MB, names reduced to `[A-Za-z0-9._-]`) into `<tab folder>/.codeman-discord/`, and a sent file's REAL path must lie inside the tab's folder (`fileProblem`, symlinks followed); a Discord failure never reaches a session; the alert tail is a function the bridge calls only once it will post (no tmux exec per event while off); a delete reaches the bridge from the cleanup path with `killMux` true, never from `session:deleted`, which a detach also fires; `.codeman-discord/` is probed with the bounded probe, refused if a symlink, and ignores itself with a `.gitignore` of `*`; a config restore of `discord.json` reloads the running bridge (`afterRestore`). The startup hint ("how to reach the user") rides the CLI registry as the engine value `appendSystemPrompt` (Claude's `--append-system-prompt`, undefined unless the bridge and `startupHint` are on, so every other launch is byte-identical) No other CLI is told. `codeman notify "<message>" [--urgent] [--file <path>]` wraps `POST /api/sessions/:id/discord-notify`, which accepts a unique 8-character id prefix (a Docker case exports it cut). → `docs/discord-bridge.md`, `docs/wiki/Discord-Bridge.md`, `docs/api-reference.md`
**MCP server (`codeman mcp`, `src/mcp-server.ts`)**: a Model Context Protocol server on stdio for any MCP client, a CLIENT of the HTTP API like `codeman agent` (reuses its `httpRequest`, `inputRefusal`, `buildSendBody`; the MCP server adds no routes). Seven tools: `list_sessions`, `start_session`, `send_prompt`, `wait_for_session`, `read_output`, `interrupt_session`, `delete_session`. ⚠️ Dual-era: answers the legacy `initialize` handshake (2024-11-05 to 2025-11-25) AND the 2026-07-28 revision (per-request `_meta` with `protocolVersion` + `clientCapabilities`, `server/discover`, `resultType: "complete"` on every modern result); a modern `tools/list`/`server/discover` MUST carry `ttlMs` + `cacheScope` (Claude Code 2.1.296 drops every tool without them: measured). ⚠️ stdout is protocol only; logs go to stderr. ⚠️ The URL comes from `--url`/`CODEMAN_API_URL`, never a guess, and unconfigured it still lists tools (registries introspect) while every call answers how to configure it. ⚠️ Prompt/interrupt/delete only sessions the PROCESS started (in-memory allowlist, so a restart fails closed) or, inside a pane, the calling session's own children, unless `--allow-any-session`; never its own session. ⚠️ `read_output` returns text ONLY, no `structuredContent` (a client that prefers it showed the model metadata instead of the output: measured). Waits default 45 s (Codex's MCP tool timeout is 60 s). Registry manifest `config/mcp-registry/server.json` (`mcpName` in package.json, version kept by `scripts/sync-plugin.mjs`). Tests: `test/mcp-server.test.ts`.
@@ -152,13 +152,15 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
⚠️ **A quiet pane is not always a pane that wants you.** A CLI can declare an optional `capabilities.workDetect.watchingLine` (a monitor, background shell or cloud hand-off it is still running); the idle probe reads it into `Session.watching` and `notePrompt()` opens that idle item ALREADY acknowledged, so no surface alerts. Only `idle` is eligible, and the label is pane-derived and prompt-injectable, so a pattern must anchor on chrome only that CLI draws. → [architecture-invariants#the-watching-signal-a-quiet-pane-that-is-not-waiting-for-you](docs/architecture-invariants.md#the-watching-signal-a-quiet-pane-that-is-not-waiting-for-you). Tests: `test/session-watching.test.ts`, `test/watching-no-alert.test.ts`.
**An exited agent in a live pane** (`paneExit`, #446): panes use `remain-on-exit on`, so `/exit` leaves a pane, session and pid that look alive; `TmuxManager.startPaneExitWatcher()` publishes `SessionState.paneExit` via `session:updated`. ⚠️ Never set `status: 'error'` or null the `pid` for it; the field is TRI-STATE (absent = UNKNOWN, never alive, scoped by `Session.paneExitApplies`); an absent `#{pane_dead_status}` is not 0; a path that starts a command in a pane must clear the record AND persist. A clean exit is CLOSED via `cleanupSession()` (`pane-exit-sweep.ts`): only an explicit numeric status 0 with no signal, confirmed by 2 reads, with no start/attach in flight (`paneLifecycleInFlight`) and not within 10 s of one (a startup error keeps its row); a crashed agent keeps its row. → [architecture-invariants#an-exited-agent-in-a-live-pane-paneexit](docs/architecture-invariants.md#an-exited-agent-in-a-live-pane-paneexit)
**An exited agent in a live pane** (`paneExit`, #446): panes use `remain-on-exit on`, so `/exit` leaves a pane, session and pid that look alive; `TmuxManager.startPaneExitWatcher()` publishes `SessionState.paneExit` via `session:updated`. ⚠️ Never set `status: 'error'` or null the `pid` for it; the field is TRI-STATE (absent = UNKNOWN, never alive, scoped by `Session.paneExitApplies`); an absent `#{pane_dead_status}` is not 0; a dead pane may have NO pid (tmux 3.8 prints `#{pane_pid}` blank), so never skip a no-pid row whose `#{pane_dead}` tmux answered, and never signal the recorded pid of a dead pane in `killSession()` (dead = flag 1 plus a blank pid or a `#{pane_dead_time}`; a pid below 2 is no pid, since an empty pane prints 0 before tmux 3.8); a path that starts a command in a pane must clear the record AND persist. A clean exit is CLOSED via `cleanupSession()` (`pane-exit-sweep.ts`): only an explicit numeric status 0 with no signal, confirmed by 2 reads, with no start/attach in flight (`paneLifecycleInFlight`) and not within 10 s of one (a startup error keeps its row); a crashed agent keeps its row. → [architecture-invariants#an-exited-agent-in-a-live-pane-paneexit](docs/architecture-invariants.md#an-exited-agent-in-a-live-pane-paneexit)
**Dead-pane respawn resume pin** (`_buildRespawnPaneOptionsWithResumePin()`, session.ts): recovering a dead pane, like a custom-model `restartCli()`, must pin the conversation or claude refuses the reused `--session-id`. The pin takes the first transcript-backed candidate (chain tail, launch seed, own id), never `_claudeSessionId`, adds nothing when none is backed, and is never applied to remote or docker sessions. → [architecture-invariants#dead-pane-respawn-the-resume-pin](docs/architecture-invariants.md#dead-pane-respawn-the-resume-pin)
**Workspace-trust dialog auto-accept** (`session-trust-dialog.ts`, pure): Claude Code's per-directory trust dialog is always answered yes, or the session is stuck. ⚠️ Match the compacted SCREEN (`compactScreenText()`, all whitespace removed), never the stream (tmux sends words joined by cursor-forwards, not spaces). ⚠️ Never answer with a blind `\r` (newer versions highlight "No, exit" first): `trustDialogNextKey()` returns ONE key per re-read frame (arrow, then Enter only once `❯` is on the trust option), and the LAST marked option wins. ⚠️ All three guards must hold: startup window `TRUST_DIALOG_WINDOW_MS` (90s), two-marker match (`isTrustDialogScreen`), attempt cap `TRUST_DIALOG_MAX_ATTEMPTS` (6). ⚠️ Read `capturePaneText()`; only a direct-PTY session falls back to a SHORT buffer tail. ⚠️ The scan must schedule its own next read (`_trustDialogTimer`, cleared in `_clearAllTimers()`), not rely on PTY output, and a throttled read is DEFERRED onto that timer, never dropped (the dialog's paint is often the pane's last output); a stopped session never scans. → [architecture-invariants#workspace-trust-dialog-auto-accept](docs/architecture-invariants.md#workspace-trust-dialog-auto-accept)
**Process-tree walks are bounded** (`proc-tree.ts`, pure): `collectDescendants(pid, byParent)` is the ONE descendant traversal, fed by one cached `ps -eo pid=,ppid=` snapshot (`refreshProcSnapshot()` in tmux-manager.ts: async, in-flight-shared, and ANY error discards the result rather than caching a truncated `ps`). ⚠️ Never walk a process tree with per-node `pgrep` or unbounded recursion (the unbounded version took a machine down): the walk must terminate on cycles, cap depth (`PROC_WALK_MAX_DEPTH`) and node count (`PROC_WALK_MAX_NODES`), and never spawn anything. ⚠️ Keep it in its own module so the test exercises the shipped code, and report truncation through `onTruncated` naming both caps, never silently. → [architecture-invariants#process-tree-walks-are-bounded](docs/architecture-invariants.md#process-tree-walks-are-bounded)
**Process-tree walks are bounded** (`proc-tree.ts`, pure): `collectDescendants(pid, byParent)` is the ONE descendant traversal, fed by one cached `ps -eo pid=,ppid=` snapshot (`refreshProcSnapshot()` in tmux-manager.ts: async, in-flight-shared, and ANY error discards the result rather than caching a truncated `ps`). ⚠️ Never walk a process tree with per-node `pgrep` or unbounded recursion (the unbounded version took a machine down): the walk must terminate on cycles, cap depth (`PROC_WALK_MAX_DEPTH`) and node count (`PROC_WALK_MAX_NODES`), and never spawn anything. ⚠️ Keep it in its own module so the test exercises the shipped code, and report truncation through `onTruncated` naming both caps, never silently. ⚠️ **A kill never takes pid 0 or 1** (`isSignalablePid()`): the children of pid 0 are the whole machine, and tmux really answers 0 for an empty pane (`split-window ''`), which the pane list at server start records as `session.pid`; a close then signalled every process of the account. `killSession` signals only through `signalProcess()`, walks nothing for such a pid and leaves the close to `tmux kill-session`. Never call `process.kill` in tmux-manager.ts with a signal anywhere else, and never drive a real `killSession` from a script: stub `process.kill` in vitest (`test/kill-pid-guard.test.ts`). → [architecture-invariants#process-tree-walks-are-bounded](docs/architecture-invariants.md#process-tree-walks-are-bounded)
**A `persistent: false` chokidar watcher stops on its first error**: ⚠️ its `'error'` handler goes through `closeWatcherOnError()` (`utils/close-watcher-on-error.ts`), never a bare log or `close()`. chokidar 3 retries a failed `fs.watch` (EMFILE once the inotify instances are used up, ENOSPC once the watches are) on the parent directory up to `/` forever, logging every pass (one server wrote 174 GiB of log that way); a bare `close()` turns the follow-up TypeError into an unhandled rejection, and a callback already in flight can reopen it through `add()`. The watcher's own poll must cover what it watched and create it again on a later tick (`TeamWatcher`, `WorkflowRunWatcher`): chokidar 3 reports a one-off ENOENT race (a new file gone between its `stat` and `watch`) through the same TypeError, so a watcher that stayed closed would end live updates until a restart. Tests: `test/watcher-fs-watch-failure.test.ts`.
**Auto-resume on usage limit** (opt-in per session, top of the Respawn tab): when Claude halts on a subscription limit, `usage-limit-patterns.ts` (pure, unit-tested) parses the reset time and `SessionAutoOps` arms a timer for reset+2min, then sends Esc + `continue`. ⚠️ Respawn cycles are blocked while paused (`isLimitPaused` guard in `onIdleDetected`), which is what prevents `/clear` from wiping the paused conversation. Claude-mode only. → [architecture-invariants#auto-resume-on-usage-limit](docs/architecture-invariants.md#auto-resume-on-usage-limit)
@@ -188,7 +190,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
**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)
**DeepSeek web UI** (`POST`/`GET`/`DELETE /api/deepseek/web`, `deepseek-web-server.ts`): the Run menu's "DeepSeek web UI..." entry supervises ONE background `dsh web` child process, deliberately **NOT a shell session**. ⚠️ Every piece is load-bearing: exactly one server (a second click REUSES it), restarted when the browser authority changes (`--trusted-host`, last asker wins), killed on shutdown via `stopDeepSeekWeb()` (the detached child would otherwise outlive Codeman and hold its port), and failures returned to the caller. ⚠️ Never hardcode the port: search from 3080 across 40, detect free ports by BINDING, then wait for the server to really answer. ⚠️ Both `POST` and `DELETE` must stay behind `canUsernameRunPrivilegedCommands` (booting a profile runs its plugin code; the server is shared). → [architecture-invariants#deepseek-web-ui](docs/architecture-invariants.md#deepseek-web-ui)
**DeepSeek web UI** (`POST`/`GET`/`DELETE /api/deepseek/web`, `deepseek-web-server.ts`): the Run menu's "DeepSeek web UI..." entry supervises ONE background `dsh web` child process, deliberately **NOT a shell session**. ⚠️ Every piece is load-bearing: exactly one server (a second click REUSES it, but only for the same starter and while its cookie works), restarted when the browser authority changes (`--trusted-host`, last asker wins), killed on shutdown via `stopDeepSeekWeb()` (the detached child would otherwise outlive Codeman and hold its port), and failures returned to the caller. ⚠️ Never hardcode the port: search from 3080 across 40, detect free ports by BINDING, then wait for the server to really answer. ⚠️ Both `POST` and `DELETE` must stay behind `canUsernameRunPrivilegedCommands` (booting a profile runs its plugin code; the server is shared). ⚠️ The launch token is traded for dsh's session cookie once at startup, and the web-tab proxy presents it on both legs only to the `managed: 'deepseek-web'` tab on the `127.0.0.1` port it was minted for (in multi-user mode, only to a granted owner who started it). → [architecture-invariants#deepseek-web-ui](docs/architecture-invariants.md#deepseek-web-ui)
**Case rename** (`POST /api/cases/:name/rename`, `src/case-rename.ts`; `docs/wiki/Core-Concepts.md#case`): a case under the cases dir is its folder name and always moves; a linked case renames its alias and moves its real folder only with `renameFolder`; remote and Docker cases are refused. ⚠️ A folder that sessions have open is the hazard: live sessions at or under it make the route answer `409 requiresStop` with their names, and only `stopSessions: true` ends them (via `ctx.cleanupSession`: closed like a tab close, uploads included, nothing is restarted); the free-target pre-check runs before that and refuses a dangling symlink too (`lstat`, as `moveCaseFolder` does), so no session is ended for a move that cannot happen. `withCaseLock` holds the old and new paths for the whole operation (`isCasePathLocked`; the `Session` constructor throws for a working directory inside a held path, so nothing is constructed mid-move). ⚠️ A create awaits the owner's layout lock and a settings read between `new Session` and the server's map, where the rename looks for open sessions, so the constructor also records the session (`noteCaseSessionStarting`) until `registerSessionWithLayout()` or `stop()` settles it (30 s TTL for one that never registers), and a folder move refuses `409` with `renameCode: "BUSY"` while one is recorded at or under the folder (`isCaseSessionStarting`, checked in the same tick that takes the lock); an alias-only rename is not refused. A create whose path was validated before the move but whose `Session` is constructed after it is not covered (the plain check-then-use race of any create path), `moveCaseFolder` refuses an existing target itself (POSIX `rename` would silently replace an EMPTY directory) and retries `EBUSY`/`EPERM`/`EACCES` before answering `423 LOCKED`. If the registries (`linked-cases.json`, `caseOrder`, `lastUsedCase`, `lastPickedCase`, `caseSettings`) fail after the move, `settings.json` and the folder are put back (a failed move-back says the folder is now at the new path), and an error after `stopSessions` carries `stoppedSessions`. Claude Code keys history by path (`claudeProjectDirName`: every non-alphanumeric becomes `-`), so `<claude config>/projects/<old>` is renamed too, or merged entry by entry, never overwriting, into one already at the new key (case delete never removes history, so an earlier case of the new name leaves one); other CLIs' history, Docker bind mounts, `git worktree` links, cron jobs' `workingDir`, Claude history of subfolder sessions and Claude Code's per-project entry in `~/.claude.json` (local-scope `mcpServers`, `allowedTools`, trust; writing another CLI's config is the opt-in MCP sync's job) are NOT migrated. The history scanner prefers the decoded project key over a transcript's `cwd` that no longer exists, so Resume follows a rename. Only an admin's rename touches the server-wide `settings.json` (`caseOrder`, `lastUsedCase`, `lastPickedCase`, `caseSettings`); the owner's default session group is carried across with `TabLayoutService`. `settings.json` is written before `linked-cases.json`, so a failed or refused registry write puts `settings.json` back and leaves the registry as it was. ⚠️ Every write to `linked-cases.json` (link, unlink, rename, and a create or clone into a custom folder) goes through `mutateLinkedCases()` (`src/web/linked-cases-writer.ts`: serialized, temp file + rename, and a file that does not parse is refused, never read as `{}`; the one direct writer is config-backup restore, `restoreConfigBackup()`, which must work on such a file), and a check that must still hold when the entry is written (the name is free; for a rename, the old entry still names the folder) runs INSIDE its callback: two clones that claimed one name used to both pass a re-read made outside it and both answer success. Pinned by `test/linked-cases-writer.test.ts`, and for a rename by `test/routes/case-rename-routes.test.ts`.
@@ -204,7 +206,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
**Auto-named sessions** (`autoNameSessions`, SYNCED, default OFF): a placeholder tab (`w3-myapp`) takes its first real prompt as a title in the `<prefix>: <title>` form, so the case identity and `w<n>` counter survive. Ownership is `SessionState.nameSource` (`placeholder` | `auto` | `manual`; the `name` setter / `PUT /api/sessions/:id/name` makes it `manual`, never touched again). ⚠️ `applyAutoName()` flips to `auto` even if the string is unchanged, so only the FIRST titled prompt names the tab. ⚠️ Only user input counts: `SessionWriteOptions.fromUser` is set by the browser WS path, `POST /api/sessions/:id/input`, the experimental guarded stage (`stageGuardedInput()`, `POST /api/sessions/:id/stage`, typed on an agent's behalf like the input route) and a Discord reply (`DiscordBridge.onGatewayMessage`, through the bridge's `sendInput`) ONLY; any new user-input path must set it (and the send-key Shift+Enter path must call `trackUserInput()`). ⚠️ The pure tracker (`session-auto-name.ts`) sits on the raw keystroke stream with an explicit rule per key; add a rule for any new key class. ⚠️ `nameSource` also decides `--name`: by default only a `manual` name is pinned on the claude CLI (`Session.cliPinnedName`), since `--name` is also the `/resume` title and a pinned one stops Claude generating its own; the opt-in synced `pinCliSessionName` (default OFF, re-read at every spawn and respawn) pins every tab name, after which a Codeman rename holds only until the next turn; a rename appends a `custom-title` row to a LOCAL, non-docker transcript, and a same-name PUT is a no-op (never flips to `manual`). Tests: `test/session-auto-name.test.ts`. → [architecture-invariants#auto-named-sessions-first-prompt--tab-title](docs/architecture-invariants.md#auto-named-sessions-first-prompt--tab-title)
**Maintainer bot (external)**: the Telegram bot that reviews open PRs and triages discussion threads in Codeman sessions used to live at `scripts/pr-bot/`. It moved OUT of this repository on 2026-09-14, to `~/codeman-cases/prbot/` (its own private git repo, systemd unit `codeman-pr-bot`, guide + agent rules in its own `README.md` and `CLAUDE.md`). It is a CLIENT of Codeman's HTTP API like any other, so nothing here depends on it and it is not part of the server, the CLI or the npm package. ⚠️ It spawns real sessions named `prbot-<n>` / `dscbot-<n>` on the local Codeman and holds clones under `~/.codeman/pr-bot/`, so those session names and that data dir are taken; it also fetches PR heads into `refs/pr-bot/*` of this checkout and must never check out, reset or clean it. The CHANGELOG entries for 1.25.0 and earlier still describe it, which is history rather than drift.
**Maintainer bot (external)**: the Telegram bot that reviews open PRs and triages discussion threads and issues in Codeman sessions used to live at `scripts/pr-bot/`. It moved OUT of this repository on 2026-09-14, to `~/codeman-cases/prbot/` (its own private git repo, systemd unit `codeman-pr-bot`, guide + agent rules in its own `README.md` and `CLAUDE.md`). It is a CLIENT of Codeman's HTTP API like any other, so nothing here depends on it and it is not part of the server, the CLI or the npm package. ⚠️ It spawns real sessions named `prbot-<n>` / `dscbot-<n>` / `issuebot-<n>` on the local Codeman and holds clones under `~/.codeman/pr-bot/`, so those session names and that data dir are taken; it also fetches PR heads into `refs/pr-bot/*` of this checkout and must never check out, reset or clean it. The CHANGELOG entries for 1.25.0 and earlier still describe it, which is history rather than drift.
**Unified session list**: `GET /api/sessions/unified` merges live sessions, persisted state, lifecycle-log history and transcript files into one deduped list (pure core `src/services/unified-session-service.ts`), backing the Cmd+K Session Manager, pinning and cross-device tab order (`PUT /api/session-order`, `src/session-order.ts`). ⚠️ Transcript history is THREE stores (`~/.claude/projects`, `~/.omp/agent/sessions`, `~/.codex/sessions`), folded via the `claudeSessionId → Codeman id` alias map (not Claude-only despite the name). ⚠️ `resumeId` is set by a SCANNER row only, never a live session; every surface that re-projects these rows (phone overview included) must carry it through, or a tap silently starts a second conversation. → [architecture-invariants#unified-session-list-and-session-manager](docs/architecture-invariants.md#unified-session-list-and-session-manager)
@@ -226,9 +228,9 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
**Circuit breakers**: the Ralph breaker prevents respawn thrashing (`CLOSED` → `HALF_OPEN` → `OPEN`; reset via `/api/sessions/:id/ralph-circuit-breaker/reset`). **Distinct: the PTY-exit breaker** (`session-pty-exit-breaker.ts`) trips after repeated rapid PTY exits and blocks auto-restarts. ⚠️ It resets ONLY via an explicit `{clearBreaker:true}` body on `POST /api/sessions/:id/interactive`; the frontend's auto-reattach in `selectSession()` sends no body and must never clear it. → [architecture-invariants#circuit-breakers-ralph-and-pty-exit](docs/architecture-invariants.md#circuit-breakers-ralph-and-pty-exit)
**Full-scrollback replay**: `GET /api/sessions/:id/terminal?full=1` returns the whole tmux scrollback ALONE (`source='mux-full-history'`), superseding the byte buffer. First load of each non-shell TUI session requests it (`_fullHistoryLoaded`); Shell selection, drop recovery, clear and a tile's load use `SHELL_LOAD_QUERY` (constants.js), a bounded window of tmux's RENDERED history (`?full=1&tail=1MiB&alt=recording&lines=10000`), never the raw byte recording, whose full-screen repaints replayed at another pane height push copies of their top row into scrollback; the route reports a client `lines=` bound below the history ceiling that left lines in tmux as `truncationReason: 'tail'`, and `alt=recording` falls back to the visible frame over the tailed byte recording when the pane is in the alternate screen (a nested tmux in a remote or Docker case keeps no tmux history; vim/less take it too while open). A Shell scroll-to-top pulls a bounded `?full=1&tail=` window (a window no longer than the browser's buffer is skipped before the downgrade guard, so it never marks the session exhausted); the unbounded pull stays behind **Load full history**. A Shell split-pane Pane B has its own copy of the bounded pull against its own xterm (`TerminalTile._pullHistory`, terminal-tile.js); keep the two in step. → [architecture-invariants#split-pane-sessions](docs/architecture-invariants.md#split-pane-sessions) ⚠️ The capture ends with a RELATIVE cursor move back to the pane's caret (never `CUP`), so no line-deleting transform may run over it; those skips key on `isFullCapture`, never on `?full=1` alone. ⚠️ A re-pull must never shrink the buffer (`_replayWouldShrinkBuffer()`). ⚠️ `captureCols`/`captureRows` are absent when no frame was positioned: test `Number.isFinite`, never truthiness. ⚠️ A frame dropped at the 128 KiB render cap MUST be recovered, and the recovery verifies itself: `_scheduleDroppedOutputRecovery` re-arms (bounded by `DROP_RECOVERY_MAX_ATTEMPTS`) while `_onSessionNeedsRefresh` reports no repaint, but never after a capture-fetch `'deadline'`. → [architecture-invariants#full-scrollback-replay](docs/architecture-invariants.md#full-scrollback-replay)
**Full-scrollback replay**: `GET /api/sessions/:id/terminal?full=1` returns the whole tmux scrollback ALONE (`source='mux-full-history'`), superseding the byte buffer. First load of each non-shell TUI session requests it (`_fullHistoryLoaded`); Shell selection, drop recovery, clear and a tile's load use `SHELL_LOAD_QUERY` (constants.js), a bounded window of tmux's RENDERED history (`?full=1&tail=1MiB&alt=recording&lines=10000`), never the raw byte recording, whose full-screen repaints replayed at another pane height push copies of their top row into scrollback; the route reports a client `lines=` bound below the history ceiling that left lines in tmux as `truncationReason: 'tail'`, and `alt=recording` falls back to the visible frame over the tailed byte recording when the pane is in the alternate screen (a nested tmux in a remote or Docker case keeps no tmux history; vim/less take it too while open). A Shell scroll-to-top pulls a bounded `?full=1&tail=` window (a window no longer than the browser's buffer is skipped before the downgrade guard, so it never marks the session exhausted); the unbounded pull stays behind **Load full history**. A Shell split-pane Pane B has its own copy of the bounded pull against its own xterm (`TerminalTile._pullHistory`, terminal-tile.js); keep the two in step. → [architecture-invariants#split-pane-sessions](docs/architecture-invariants.md#split-pane-sessions) ⚠️ The capture ends with a RELATIVE cursor move back to the pane's caret (never `CUP`), so no line-deleting transform may run over it; those skips key on `isFullCapture`, never on `?full=1` alone. ⚠️ A re-pull must never shrink the buffer (`_replayWouldShrinkBuffer()`). ⚠️ `captureCols`/`captureRows` are absent when no frame was positioned: test `Number.isFinite`, never truthiness. ⚠️ A frame dropped at the 128 KiB render cap MUST be recovered, and the recovery verifies itself: `_scheduleDroppedOutputRecovery` re-arms (bounded by `DROP_RECOVERY_MAX_ATTEMPTS`) while `_onSessionNeedsRefresh` reports no repaint, but never after a capture-fetch `'deadline'`. ⚠️ **Reload history** (#814, manual early repair; rules in the invariants paragraph "Repair while reading"): only a `mux-full-history` replay whose live-output generation is unchanged since before its fetch clears `_liveOutputSinceFullPull` and `_historyReloadDismissed`; a refused or non-mux answer to a manual reload retires the action until then; and the buffer load opens BEFORE the fetch, so download-time output queues behind the replay. → [architecture-invariants#full-scrollback-replay](docs/architecture-invariants.md#full-scrollback-replay)
**Terminal scrollback strip + wheel/touch forwarding**: codex/claude/gemini get the FULL strip (alt-screen, `3J`, mouse DECSETs); tmux-backed opencode, copilot and pi get the MIDDLE strip (alt-screen toggles + mouse DECSETs, `3J` kept); every other tmux-backed mode (shell/antigravity/grok/deepseek/omp) gets the NARROW strip (alt-screen toggles only). Table: `CliCapabilities.altScreen` JSDoc, pinned in test/claude-scrollback-strip.test.ts. ⚠️ Gated on `useMux`: direct-PTY sessions must keep the alt screen. Wheel and touch forward only with observed `cliMouseTracking`: **Claude ≥ 2.1.187, tracked Codex, tracked Copilot, or tracked Pi**. Codex 0.163.0 fullscreen was measured with `alternate_on=1`, `mouse_any_flag=1`: one SGR report moves one transcript row; see the fresh measurement in architecture-invariants. Inline/untracked Codex retains local history or the capability-gated paging fallback. Copilot has no version gate; a stale/false tracking flag falls back to PageUp/PageDown. Pi has no version gate either, and is fullscreen by default since 1.0.0: it enables tracking once at start, so the flag is what survives a tab switch or reload (xterm's own mode does not). ⚠️ Pi deliberately has no `transcriptPageKeys`: its `tuiMode: regular` binds those keys to the editor, so paging there moves a draft's caret. Touch alone has one more branch (`_shouldForwardTouchToApp`): in any mode, a drag also forwards as SGR wheel reports while xterm ITSELF tracks the mouse with SGR encoding (an app in the pane asked for it; a tracking mode other than `x10` and `coreMouseService.activeEncoding === 'SGR'`, so DEFAULT, X10 and SGR-pixel apps fail closed), because xterm encodes a wheel there but the touch listeners consume the drag. ⚠️ `getClaudeCliVersion()` must never cache a FAILED probe. ⚠️ Hand-report clicks only while the CLI has mouse tracking on: `_shouldReportMouseToCli()` gates all three report sites on `cliMouseTracking` (from `_recordStrippedMouseMode()`, session.ts), or a plain shell prints the reports as literal text. ⚠️ A `TerminalTile` (grid tile, split Pane B) forwards the wheel as SGR reports, pages it and reports clicks through these SAME gates with itself as the target (its terminal, its session, never `activeSessionId`), and scrolls Shift+wheel itself (xterm makes it a horizontal no-op); never copy the mode lists into terminal-tile.js. ⚠️ The hollow-buffer PageUp/PageDown fallback (`_maybePageCliTranscript`) stands down when the last capture reported tmux scrollback (`paneHistoryLines` > 0: a tail replayed after a server restart carries only the attach repaint), so the gesture scrolls locally and the scroll-to-top pull loads `full=1`; 0 and unknown keep paging. Read `_logScrollRouting()` before diagnosing a scroll report. → [architecture-invariants#terminal-scrollback-strip-flavors-and-wheeltouch-forwarding](docs/architecture-invariants.md#terminal-scrollback-strip-flavors-and-wheeltouch-forwarding)
**Terminal scrollback strip + wheel/touch forwarding**: codex/claude/gemini get the FULL strip (alt-screen, `3J`, mouse DECSETs); tmux-backed opencode, copilot and pi get the MIDDLE strip (alt-screen toggles + mouse DECSETs, `3J` kept); every other tmux-backed mode (shell/antigravity/grok/deepseek/omp) gets the NARROW strip (alt-screen toggles only). Table: `CliCapabilities.altScreen` JSDoc, pinned in test/claude-scrollback-strip.test.ts. ⚠️ Gated on `useMux`: direct-PTY sessions must keep the alt screen. Wheel and touch forward only with observed `cliMouseTracking`: **Claude ≥ 2.1.187, tracked Codex, tracked Copilot, or tracked Pi**. Which CLIs forward is the registry's `wheelForward`, published as `window.__codemanWheelForward` and never an id list in the gate, so a custom `clis.json` entry opts in with it plus `altScreen: 'strip-mux-and-mouse'` (`docs/cli-registry.md`). Codex 0.163.0 fullscreen was measured with `alternate_on=1`, `mouse_any_flag=1`: one SGR report moves one transcript row; see the fresh measurement in architecture-invariants. Inline/untracked Codex retains local history or the capability-gated paging fallback. Copilot has no version gate; a stale/false tracking flag falls back to PageUp/PageDown. Pi has no version gate either, and is fullscreen by default since 1.0.0: it enables tracking once at start, so the flag is what survives a tab switch or reload (xterm's own mode does not). ⚠️ Pi deliberately has no `transcriptPageKeys`: its `tuiMode: regular` binds those keys to the editor, so paging there moves a draft's caret. Touch alone has one more branch (`_shouldForwardTouchToApp`): in any mode, a drag also forwards as SGR wheel reports while xterm ITSELF tracks the mouse with SGR encoding (an app in the pane asked for it; a tracking mode other than `x10` and `coreMouseService.activeEncoding === 'SGR'`, so DEFAULT, X10 and SGR-pixel apps fail closed), because xterm encodes a wheel there but the touch listeners consume the drag. ⚠️ `getClaudeCliVersion()` must never cache a FAILED probe. ⚠️ Hand-report clicks only while the CLI has mouse tracking on: `_shouldReportMouseToCli()` gates all three report sites on `cliMouseTracking` (from `_recordStrippedMouseMode()`, session.ts), or a plain shell prints the reports as literal text. ⚠️ A `TerminalTile` (grid tile, split Pane B) forwards the wheel as SGR reports, pages it and reports clicks through these SAME gates with itself as the target (its terminal, its session, never `activeSessionId`), and scrolls Shift+wheel itself (xterm makes it a horizontal no-op); never copy the mode lists into terminal-tile.js. ⚠️ The hollow-buffer PageUp/PageDown fallback (`_maybePageCliTranscript`) stands down when the last capture reported tmux scrollback (`paneHistoryLines` > 0: a tail replayed after a server restart carries only the attach repaint), so the gesture scrolls locally and the scroll-to-top pull loads `full=1`; 0 and unknown keep paging. Read `_logScrollRouting()` before diagnosing a scroll report. → [architecture-invariants#terminal-scrollback-strip-flavors-and-wheeltouch-forwarding](docs/architecture-invariants.md#terminal-scrollback-strip-flavors-and-wheeltouch-forwarding)
**Detached start + service install**: `codeman web -d` relaunches the same entry script `detached:true` (setsid); `nohup` is not what makes it survive. ⚠️ Both `-d` and `service install` must REFUSE when a server is already up on this data dir (pidfile + `/api/status` probe), or a second instance attaches to the first one's live sessions. ⚠️ Never report success not observed: poll `/api/status` until the child answers or dies. `--stop` must verify the pid still looks like Codeman (`ps -o command=`) before signalling. Unit/label names live only in `config/service-names.ts`. `service install` bakes the installing shell's PATH into the unit and never writes `CODEMAN_PASSWORD` into it. → [architecture-invariants#detached-start-and-service-install](docs/architecture-invariants.md#detached-start-and-service-install)
**Self-update** (App Settings → System → Updates): in-app updater for git-clone installs under a supervisor (`systemd`, `launchd`, `launchd-daemon`, `docker-compose`, else `none`). The work runs in a DETACHED `scripts/self-update.sh` writing `update-status.json`, polled across the restart; pure helpers in `src/web/self-update.ts`. ⚠️ Compose: the restart kills the script, so nothing may be appended after the `restarting` marker; the repo must stay a host bind mount over `/opt/codeman` and the image must keep devDependencies + toolchain. ⚠️ `evaluateEnvironmentGate()` refuses releases that change `server.Dockerfile`/`docker-compose.yaml` or add `.env.example` keys, re-evaluated on `POST /api/system/update`; unknowns fail OPEN, but the exit-to-restart needs `--restart-by-exit 1` (`CODEMAN_RESTART_BY_EXIT=1` only in the Compose file). ⚠️ An install with no git checkout (`install.sh` on a machine without a working git leaves the marker `.install-source`) is kind `archive`: it cannot update in place, and both the check and the UI tell it to re-run the installer, never the npm line. ⚠️ Keep the agent CLIs in `server.Dockerfile` pinned. → [docs/docker-self-update.md](docs/docker-self-update.md), [architecture-invariants#self-update](docs/architecture-invariants.md#self-update)
@@ -249,7 +251,7 @@ The terminal provider scans `terminalLinkLine()`, which extends `terminalPathLin
**Files panel delete** (salvaged from #529; `DELETE /api/sessions/:id/files?path=`, the × on a file row of the Files panel, tree and search results): removes ONE regular file and is the **only file surface that deletes**. It takes the edit route's confinement and guards whole (ownership via `findSessionOrFail`, `validateLocalSessionFilePath` behind `withGuardedOutsideWorktree`, so an absolute path in a followed outside worktree obeys the same rules, sensitive/blocked/`.git` 403), and both spellings are checked, the realpath and the path as named. ⚠️ **A symbolic link is refused (400), never followed**: the confinement check returns the REALPATH, i.e. the link's target, so an `unlink` of it deleted `CLAUDE.md` for `AGENTS.md -> CLAUDE.md` and left the link dangling. The final component is `lstat`ed on the path AS NAMED, only a plain file goes on, the inode is compared again before `unlink`, and `unlink` never follows a final link. A dangling link fails realpath and reads as 404. ⚠️ Remote sessions are refused before any path check (a same-named local folder would take the delete), and so are adopted ones (the `/tmp` file-surface exception is not copied to a new surface); Docker workspaces are allowed like the edit route. The workspace (and the outside worktree root) is probed bounded first (#516, `422` on a dead mount). ⚠️ The button is bound from the row's escaped `data-path` in the `.file-tree-item` loops, NEVER an inline `onclick` (`encodeURIComponent` leaves `'` alone, so `x'-alert(1)-'.txt` ran script); it asks with `confirm()`, reloads through `_reloadFileBrowserKeepingQuery()` so a search re-runs, stays visible under `@media (hover: none)`, and is not drawn for remote or adopted sessions. Tests: `test/routes/file-delete-routes.test.ts`, `test/file-delete-ui.test.ts`. → [architecture-invariants#files-panel-delete](docs/architecture-invariants.md#files-panel-delete)
**Files panel search** (COD-236, the `q` param on `GET /api/sessions/:id/files`): `compileFileQuery()` (`utils/file-query.ts`, pure) compiles the query into a predicate the server-side walk prunes with; a query returns a FLAT match list and the walk recurses past non-matching directories. An empty, whitespace-only or overlong (`MAX_QUERY_LENGTH`, 256) query compiles to `null`, keeping the default tree response byte-identical. ⚠️ **Never compile a glob into a RegExp** (`*a*a*a…` backtracks and freezes the event loop for the whole server): `globMatch()` is a two-pointer wildcard walk. Tree and search share one walk shape: a per-directory round-robin (breadth-first, so fair per directory, not per subtree) over one 5,000-node budget, where a folder's own files count as one share beside the subfolders it just found (`walkTurnEnd()`). ⚠️ That budget caps what is LISTED, never what is read: a read keeps only what the listing can use (`readWalkFolder()`) and `MAX_WALK_ENTRIES_READ` (250,000) stops opening folders, or one GET reads the whole workspace into memory. ⚠️ A folder below the walk's root is probed (#516) before its `readdir`, and anything but `directory` is skipped unflagged. ⚠️ A directory has its node before it is read, so every cursor still queued or unread when the walk ends must get `incomplete: true` or it reads as an empty folder. → [architecture-invariants#files-panel-search](docs/architecture-invariants.md#files-panel-search)
**Files panel search** (COD-236, the `q` param on `GET /api/sessions/:id/files`): `compileFileQuery()` (`utils/file-query.ts`, pure) compiles the query into a predicate the server-side walk prunes with; a query returns a FLAT match list and the walk recurses past non-matching directories. An empty, whitespace-only or overlong (`MAX_QUERY_LENGTH`, 256) query compiles to `null`, keeping the default tree response byte-identical. ⚠️ **Never compile a glob into a RegExp** (`*a*a*a…` backtracks and freezes the event loop for the whole server): `globMatch()` is a two-pointer wildcard walk. Tree and search share one walk shape: a per-directory round-robin (breadth-first, so fair per directory, not per subtree) over one 5,000-node budget, where a folder's own files count as one share beside the subfolders it just found (`walkTurnEnd()`). ⚠️ That budget caps what is LISTED, never what is read: a read keeps only what the listing can use (`readWalkFolder()`) and `MAX_WALK_ENTRIES_READ` (250,000) stops opening folders, or one GET reads the whole workspace into memory. ⚠️ A folder below the walk's root is probed (#516) before its `readdir`, and anything but `directory` is skipped unflagged. ⚠️ A directory has its node before it is read, so every cursor still queued or unread when the walk ends must get `incomplete: true` or it reads as an empty folder. ⚠️ The PANEL itself no longer draws that tree for a local session: it browses with `lazy=1` (#759), ONE folder per request, 500 entries a page, with a `nextCursor` scoped to the session, root, folder and hidden preference. The folder is probed with `pastCap` before its `readdir`, refused segments are checked on both spellings (as named and resolved), and a directory row without `children` is NOT LOADED, never empty. A page lists directories before files and the order holds across pages; the panel's restore relies on it (a loaded file ends the search for a folder, `_revealFileBrowserDirectory()`). Typing filters loaded rows with no request; only Enter runs the workspace search. The legacy tree and `q` responses stay byte-identical for other callers and remote sessions. Tests: `test/routes/file-routes-lazy.test.ts`, `test/file-browser-lazy.test.ts`. → [architecture-invariants#files-panel-search](docs/architecture-invariants.md#files-panel-search)
**Files panel in a worktree** (#765, `src/live-worktree.ts`, `root=live` and `root=live-any` on `GET /api/sessions/:id/files`): Claude's EnterWorktree moves the process, and `paneCwd` follows it (tmux reads the process cwd, measured on 2.1.318, back out on ExitWorktree too), while `workingDir` stays the session's identity. `refreshLiveWorktree()` (server.ts) turns a changed `paneCwd` into `SessionState.liveWorktree` by reading the `.git` FILE (never spawning git), walking up and stopping at `workingDir`, a repository or submodule of its own, or anything unreadable. That is the lookup for a pane inside `workingDir`; a pane outside it goes to `findOutsideWorktree()`, described below. ⚠️ The security argument has two halves. For a worktree inside `workingDir` the lookup only answers a folder strictly below it, but that is a LEXICAL judgement made when the pane moves, and a symlink can replace the folder or a parent later without moving the pane, so `root=live` re-checks on every request (`canWalkLiveWorktree()`, file-routes.ts: walk the worktree only when it resolves strictly inside the resolved `workingDir`, else walk `workingDir`). The walk starts there, returned `path`s stay relative to `workingDir`, and the routes keep confining to `workingDir`, so never make an INSIDE `liveWorktree` a confinement root. ⚠️ Only that check uses resolved paths: the walk keeps the session's spelling, or a workspace reached through a symlink stops producing paths relative to `workingDir`. ⚠️ A plain subfolder is deliberately no answer, or a `cd` in a shell would re-root the panel. ⚠️ A listing reports `worktree` whichever folder it walked, even when the worktree has gone or the check refused it: `_followFileBrowserWorktree()` compares that with the session's state, and an absent report would reload forever. The one exception is a listing without `root=live-any`, which omits an outside worktree; while the session folder is pinned, the panel compares with the worktree it pinned away from (`pinnedWorktree`, panels-ui.js). ⚠️ **A worktree OUTSIDE `workingDir` (`git worktree add ../feature`, or an EnterWorktree placed beside the repo) IS a second root**, answered only through `findOutsideWorktree()` with `outside: true` and published on the wire as `SessionState.outsideWorktree`, never in `liveWorktree`, which stays inside-only: the session's own repository must vouch for it by FILE READS (`workingDir` must be the top of its repository or worktree, so a session in a subfolder follows nothing outside it; the candidate's `.git` FILE names `<common dir>/worktrees/<id>` and that entry's `gitdir` names the candidate back, or its `.git` FOLDER is the session's common dir itself, which is the main worktree for a session started in a linked one, and a symlinked `.git` is refused; never spawn git from the pane watcher). It is refused at `/`, home or above, around `workingDir` and at/inside/around a Docker case workspace (an unreadable Docker list follows nothing). It is refused while attachment workspace confinement is on. It is also refused at, inside or around an attachment blocked tree, and at a root that is itself a sensitive folder such as `~/.ssh` (a child probe, since the sensitive patterns describe file locations). These rules are judged when the pane moves like the Docker rule, and multi-user mode applies `folderAllowedForUser`. The routes also re-check confinement and the blocked trees on every request (`isOutsideWorktreeRootRefused()`), so turning confinement on or blocking the folder stops serving it at once. ⚠️ `validateLocalSessionFilePath()` also refuses any file there that `isSensitivePath()` blocklists, so a root such as a credential folder can never serve its keys. Walking it is opt-in: only `root=live-any` (which the panel sends) lists it, with ABSOLUTE `path`s, while `root=live` never walks an outside worktree: it walks `workingDir` with relative paths, and its listing omits `worktree` for an outside one. An absolute path inside it is confined to it, falling back to `workingDir` when the worktree root refuses it (`validateLocalSessionFilePath()`, route-helpers.ts), while a relative path still resolves against `workingDir` alone. ⚠️ It is recorded as a REAL path, and every request re-checks that the folder still resolves to exactly that path (`outsideWorktreeRootFor()`, `canWalkOutsideWorktree()`), or a symlink swapped in would re-root the routes anywhere. Tests: `test/live-worktree.test.ts`, `test/live-worktree-outside.test.ts`, `test/routes/file-routes-live-worktree.test.ts`, `test/routes/file-routes-outside-worktree.test.ts`, `test/file-browser-worktree.test.ts`, `test/file-browser-outside-worktree.test.ts`. → [architecture-invariants#files-panel-in-a-worktree](docs/architecture-invariants.md#files-panel-in-a-worktree)
@@ -301,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). 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 and hook-secret have separate buckets, so neither 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 |
@@ -334,7 +336,7 @@ One module per domain in `src/web/routes/` (plus a barrel; `ls src/web/routes/`
## State Files
All in `~/.codeman/`: `state.json` (sessions, settings, respawn, orchestrator, cron jobs/runs, owner tab layouts, case default groups), `mux-sessions.json` (tmux recovery), `settings.json` (user prefs), `push-keys.json` + `push-subscriptions.json`, `session-lifecycle.jsonl` (audit log), `update-status.json` (self-updater progress, polled across the service restart), `docker-env-applied.json` (Compose deployment only: sha256 of the Dockerfile + compose file the running container was built from, written by `Start-Codeman.sh`, read by the self-updater's environment gate), `docker-build-source.json` (Compose deployment only: the checkout's HEAD commit and `package-lock.json` hash the `codeman-node-modules`/`codeman-dist` volumes currently reflect, written by both `Start-Codeman.sh` and a successful in-place self-update, compared to detect and refresh a volume left stale by an externally-triggered rebuild), `linked-cases.json`, `webviews.json` (saved web-tab dashboard URLs), `remote-hosts.json` + `remote-cases.json`, `docker-hosts.json` + `docker-cases.json` + `docker-exports/`, `subagent-window-states.json` + `subagent-parents.json` (subagent window layout, GET/PUT `/api/subagent-window-states`/`-parents`), `hook-secret` (per-instance), `users.json` (multi-user, mode 0600) + `admin-audit.jsonl`, `intents.json` (Read My Mind intent profiles, mode 0600), `agent-inbox.json` (agent inbox snapshot, only while `agentInboxPersistEnabled` is on, mode 0600), `edit-history/<id>.json` (Edit history panel, one store per session, every diff an agent wrote, mode 0600), `webhook.json` (webhook notifications: enabled/service/scope plus the ntfy/Slack/Discord URL, a bearer secret, so mode 0600, kept out of `settings.json` and never returned by `/api/webhook`, which is admin-only in multi-user mode), `discord.json` (Discord bridge: bot token, a bearer secret, so mode 0600, never returned by `/api/discord`, admin-only in multi-user mode) + `discord-bridge.json` (sessionId to Discord thread id), `local-model.json` (local model install: state, step, model, port, pid, digest, the checked models of the library, the previous `customModelEndpointsEnabled` value; mode 0600, holds no path, not part of a config backup) + `local-model/` (the pinned runtime, the model store and the runtime's private HOME, removed by `DELETE /api/local-model`), `agent-skill-default-migrated.json` (written once by the 1.50.0 boot migration of `agentSkillEnabled`; while it exists the migration never runs again, so deleting it would switch a stored off on at the next start; never tracked or restored), `config-backup-id` (the random id config backups record as each manifest's `origin`, so instances sharing a backup folder keep to their own snapshots; mode 0600, never tracked or restored, and deleting it unlists this instance's earlier snapshots), `backups/config/` (the default config-backup folder, moved by `configBackupDir`: `cfg-YYYYMMDD-HHMMSS/` snapshots, 0700 with 0600 files, each with a `manifest.json` of SHA-256s, the origin and the retention in force (`keepCount`/`keepDays`), which a pass falls back to when `settings.json` lacks a retention key), `certs/` (self-signed TLS for `--https`), `.env` (CODEMAN_USERNAME/PASSWORD fallback for the `codeman attach` CLI), `install.log` (installer step output, written by `install.sh`'s `run_step`) `tailscale-rename` (the node name before `install.sh` renamed it, so uninstall can offer it back), `cli-installed` (empty, touched by `install.sh` when it installs a CLI: a running server reads only its mtime, and a change ends that CLI's negative-cache backoff) and `runtime/` (the Node.js and tmux `install.sh` downloaded on its no-admin route, linked from `~/.local/bin`; all four installer-route only). Transient: `self-update-runner.sh`. Multi-user case spaces live OUTSIDE the data dir at `~/codeman-users/<username>/cases` (shared across instances like `~/codeman-cases`, override `CODEMAN_USER_SPACES_DIR`).
All in `~/.codeman/`: `state.json` (sessions, settings, respawn, orchestrator, cron jobs/runs, owner tab layouts, case default groups), `mux-sessions.json` (tmux recovery), `settings.json` (user prefs), `push-keys.json` + `push-subscriptions.json`, `session-lifecycle.jsonl` (audit log), `update-status.json` (self-updater progress, polled across the service restart), `docker-env-applied.json` (Compose deployment only: sha256 of the Dockerfile + compose file the running container was built from, written by `Start-Codeman.sh`, read by the self-updater's environment gate), `docker-build-source.json` (Compose deployment only: the checkout's HEAD commit and `package-lock.json` hash the `codeman-node-modules`/`codeman-dist` volumes currently reflect, written by both `Start-Codeman.sh` and a successful in-place self-update, compared to detect and refresh a volume left stale by an externally-triggered rebuild), `linked-cases.json`, `webviews.json` (saved web-tab dashboard URLs), `remote-hosts.json` + `remote-cases.json`, `docker-hosts.json` + `docker-cases.json` + `docker-exports/`, `subagent-window-states.json` + `subagent-parents.json` (subagent window layout, GET/PUT `/api/subagent-window-states`/`-parents`), `hook-secret` (per-instance), `users.json` (multi-user, mode 0600) + `admin-audit.jsonl`, `intents.json` (Read My Mind intent profiles, mode 0600), `agent-inbox.json` (agent inbox snapshot, only while `agentInboxPersistEnabled` is on, mode 0600), `edit-history/<id>.json` (Edit history panel, one store per session, every diff an agent wrote, mode 0600), `webhook.json` (webhook notifications: enabled/service/scope plus the ntfy/Slack/Discord URL, a bearer secret, so mode 0600, kept out of `settings.json` and never returned by `/api/webhook`, which is admin-only in multi-user mode), `discord.json` (Discord bridge: bot token, a bearer secret, so mode 0600, never returned by `/api/discord`, admin-only in multi-user mode) + `discord-bridge.json` (sessionId to Discord thread id) + `discord-reply-dedupe.json` (replayed-reply guard: at most 2,048 Discord message IDs with timestamps, kept 7 days, mode 0600; a file that could not be read is never overwritten), `local-model.json` (local model install: state, step, model, port, pid, digest, the checked models of the library, the previous `customModelEndpointsEnabled` value; mode 0600, holds no path, not part of a config backup) + `local-model/` (the pinned runtime, the model store and the runtime's private HOME, removed by `DELETE /api/local-model`), `agent-skill-default-migrated.json` (written once by the 1.50.0 boot migration of `agentSkillEnabled`; while it exists the migration never runs again, so deleting it would switch a stored off on at the next start; never tracked or restored), `config-backup-id` (the random id config backups record as each manifest's `origin`, so instances sharing a backup folder keep to their own snapshots; mode 0600, never tracked or restored, and deleting it unlists this instance's earlier snapshots), `backups/config/` (the default config-backup folder, moved by `configBackupDir`: `cfg-YYYYMMDD-HHMMSS/` snapshots, 0700 with 0600 files, each with a `manifest.json` of SHA-256s, the origin and the retention in force (`keepCount`/`keepDays`), which a pass falls back to when `settings.json` lacks a retention key), `certs/` (self-signed TLS for `--https`), `.env` (CODEMAN_USERNAME/PASSWORD fallback for the `codeman attach` CLI), `install.log` (installer step output, written by `install.sh`'s `run_step`) `tailscale-rename` (the node name before `install.sh` renamed it, so uninstall can offer it back), `cli-installed` (empty, touched by `install.sh` when it installs a CLI: a running server reads only its mtime, and a change ends that CLI's negative-cache backoff) and `runtime/` (the Node.js and tmux `install.sh` downloaded on its no-admin route, linked from `~/.local/bin`; all four installer-route only). Transient: `self-update-runner.sh`. Multi-user case spaces live OUTSIDE the data dir at `~/codeman-users/<username>/cases` (shared across instances like `~/codeman-cases`, override `CODEMAN_USER_SPACES_DIR`).
**Generated top-level dirs** (all gitignored — don't edit or commit): `dist/` (esbuild output), `out/`, `coverage/`, `test-results/`, `tmp/`, `screenshots-echo-diag/`. The committed gesture bundle (`src/web/public/gesture/gesture-codeman.js`) IS tracked, but its runtime wasm/model assets (`src/web/public/gesture/wasm/`, `*.task`) are fetched and gitignored.
@@ -353,7 +355,7 @@ npm test -- -t "pattern" # By name
Three suites are deliberately left out, because they cannot pass on an arbitrary machine. Each has its own runner, and a failure there means "not runnable here", not a regression:
```bash
npm run test:browser # Playwright + chromium, live server; codex-predictive-echo also needs a real codex binary
npm run test:browser # Playwright + chromium, live server (own pretest vendor step); codex-predictive-echo also needs a real codex binary
npm run test:mobile # the above plus environment-specific PNG baselines (own config, own pretest vendor step)
npm run test:perf # wall-clock benchmarks — need an otherwise idle machine
npm run test:all # literally everything; fails ~87 tests on a clean master here, which is why it is not the default
@@ -371,7 +373,7 @@ A raw `npx vitest` used to find no config, so `setup.ts` never ran and the suite
**Ports**: every in-process test server binds port 0 (the one exception, `test/codex-predictive-echo.test.ts`, starts a separate lab server process on 3222). A test that constructs `WebServer` reads `server.boundPort` (mobile tests: `createTestServer()`, then `server.boundPort`); a raw `http`/`net`/Fastify/`ws` server listens on `0` and reads `address().port`. `test/test-ports-guard.test.ts` fails a `WebServer` built on any other port and a raw `listen` on a number or `…PORT` constant. A test that needs a port nothing listens on binds 0, reads it and closes (`closedPort()` in `test/daemon-control.test.ts`), never "the server's port + 1". Never 3000 (the live instance).
⚠️ **Browser tests can pass vacuously on mobile input paths.** Two traps, both hit on 2026-07-27 while fixing the phone Enter button: **(1)** driving input with `app.sendInput('…')` writes PAST the `LocalEchoOverlay`, so `pendingText` stays empty and any overlay bug is invisible — type with `page.keyboard.type()` instead; **(2)** headless Chromium reports `MobileDetection.isTouchDevice()` **false even with `hasTouch: true`**, so `_localEchoEnabled` is off and the local-echo branch never executes. Force it (`app._localEchoEnabled = true`) or the test proves nothing. Assert on real state (`app._localEchoOverlay.pendingText`, plus `tmux -L codeman capture-pane -p -t <pane>` for what actually reached the PTY), not on HTTP 200.
⚠️ **Browser tests can pass vacuously on mobile input paths.** Two traps, both hit on 2026-07-27 while fixing the phone Enter button: **(1)** driving input with `app._sendInputAsync(id, '…')` writes PAST the `LocalEchoOverlay`, so `pendingText` stays empty and any overlay bug is invisible — type with `page.keyboard.type()` instead; **(2)** headless Chromium reports `MobileDetection.isTouchDevice()` **false even with `hasTouch: true`**, so `_localEchoEnabled` is off and the local-echo branch never executes. Force it (`app._localEchoEnabled = true`) or the test proves nothing. Assert on real state (`app._localEchoOverlay.pendingText`, plus `tmux -L codeman capture-pane -p -t <pane>` for what actually reached the PTY), not on HTTP 200.
**Testing against the live instance**: prod is HTTPS-only on :3000 (`curl -sk https://localhost:3000/...`). ⚠️ `w1`/`w2`/`w3` are the user's REAL sessions — never send input to them. Create your own throwaway session (`POST /api/sessions` then `POST /api/sessions/:id/shell`; creation alone leaves `pid: null` and no pane), test against that, and `DELETE` it by exact id when done.
+2 -1
View File
@@ -708,7 +708,7 @@ By default Codeman launches sessions with `--dangerously-skip-permissions`, so t
- **Loopback by default** — the server binary binds `127.0.0.1`, reachable only from the same machine, so the no-password default is safe out of the box (the guided installer asks about network access and configures the binding + password for you). Binding a non-loopback host without `CODEMAN_PASSWORD` _starts but prints a loud warning_ with three concrete fixes (set a password, loopback + an authenticated tunnel, or explicitly acknowledge with `--allow-unauthenticated-network`)
- **Optional auth, real sessions** — HTTP Basic via `CODEMAN_USERNAME` (default `admin`) / `CODEMAN_PASSWORD`. Success issues an opaque 256-bit `codeman_session` cookie (`randomBytes(32)`) — validated server-side, not client-signed, so it can't be forged offline (24h TTL, auto-extend, device-context audit log)
- **Per-IP rate limiting** — 10 failed attempts → `429` with `Retry-After` (15-min decay). A valid cookie or correct password recovers _immediately_ even while an attacker hammers the same IP — important because all tunnel traffic shares one loopback IP. Multi-user mode allows 50 failures per IP instead, plus 10 failed guesses per account from one IP; both are checked before the password, so past either a correct password from that IP also waits for the decay, while the account still logs in from another IP. QR auth has its own separate limiter
- **Per-IP rate limiting** — 10 failed attempts → `429` with `Retry-After` (15-min decay). A valid cookie or correct password recovers _immediately_ even while an attacker hammers the same IP — important because all tunnel traffic shares one loopback IP. Multi-user mode allows 50 failures per IP instead, plus 10 failed guesses per account from one IP; both are checked before the password, so past either a correct password from that IP also waits for the decay, while the account still logs in from another IP. A request with no credentials (an open tab after a restart) is never counted and always gets the login prompt. QR auth has its own separate limiter
- **Configurable permission mode** - `--dangerously-skip-permissions` is only the default. **App Settings → Agents & CLIs → Claude → Startup Mode** can switch new sessions to Anthropic's classifier-guarded `auto` mode (low-prompt, needs Claude Code 2.1.207+), `normal` prompting, or an explicit allowed-tools list. In multi-user mode, non-granted users are forced to `auto`, and shell sessions / skip-permissions require an explicit per-user grant
### Always-on browser hardening (v0.9.5)
@@ -744,6 +744,7 @@ A full-screen dashboard for your sessions, in the terminal. Same states as the w
codeman tui # the dashboard
codeman tui --list # numbered session list, then exit (scriptable)
codeman tui 2 # attach straight to session 2 of that list
codeman tui api-docs # attach straight to the live session named api-docs
```
Sessions are grouped **NEEDS YOU → WORKING → IDLE → RECENT**, longest-waiting first. `↑↓`/`j`/`k` select, `1`-`9` and `[`/`]` switch between sessions, `Enter` attaches into the tmux pane (**`F1`** to come back). Inside a pane the bar across the top keeps the session strip visible and `Alt+1`-`Alt+9` switch without leaving. `y`/`n`/digit answer a pending permission dialog right from the list, `p` sends a one-line prompt, `n` starts a session and opens straight into it, `x` kills one (`y` confirms), `/` searches, `g` shows the away digest, `?` is help, `q` quits. Below 72 columns it drops the preview pane and becomes a single-column list, so it stays usable in Termius on a phone. With no server running it still starts in attach-only degraded mode.
+1
View File
@@ -741,6 +741,7 @@ Codeman 默认用 `--dangerously-skip-permissions` 启动会话,因此 Web UI
codeman tui # 仪表盘
codeman tui --list # 带编号的会话列表,随即退出(可用于脚本)
codeman tui 2 # 直接附着到列表里的第 2 个会话
codeman tui api-docs # 直接附着到名为 api-docs 的活动会话
```
会话按 **NEEDS YOU → WORKING → IDLE → RECENT** 分组,等得最久的排最前。`↑↓`/`j`/`k` 选择,`1`-`9` 与 `[`/`]` 切换会话,`Enter` 附着进 tmux 面板(按 **`F1`** 回来)。在面板里,顶部的横条会一直显示会话条,`Alt+1`-`Alt+9` 不用离开就能切换。`y`/`n`/数字可以直接在列表里回答待处理的权限对话框,`p` 发送一行提示,`n` 新建会话并直接进入,`x` 杀掉一个(`y` 确认),`/` 搜索,`g` 显示离开摘要,`?` 是帮助,`q` 退出。窄于 72 列时它会去掉预览面板、变成单列列表,所以在手机上的 Termius 里依然好用。没有服务器在跑时,它仍会以仅附着的降级模式启动。
+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.51.0",
"version": "1.52.0",
"websiteUrl": "https://getcodeman.com",
"repository": {
"url": "https://github.com/Ark0N/Codeman",
@@ -13,7 +13,7 @@
{
"registryType": "npm",
"identifier": "aicodeman",
"version": "1.51.0",
"version": "1.52.0",
"transport": {
"type": "stdio"
},
+3
View File
@@ -28,6 +28,7 @@ export const BROWSER_TEST_GLOBS = [
'test/tab-layout-editing.browser.test.ts',
'test/tab-rail-search.browser.test.ts',
'test/tab-focus.browser.test.ts',
'test/dialog-focus-return.browser.test.ts',
'test/session-sidebar-ux.browser.test.ts',
'test/header-divider.browser.test.ts',
'test/tab-strip-corner.browser.test.ts',
@@ -38,7 +39,9 @@ export const BROWSER_TEST_GLOBS = [
'test/webgl-fallback.test.ts',
'test/terminal-copy-shortcut.test.ts',
'test/terminal-keycode229-recovery.browser.test.ts',
'test/ios-native-input.browser.test.ts',
'test/capture-load-window.browser.test.ts',
'test/history-gap-repair.browser.test.ts',
'test/capture-geometry-retry.browser.test.ts',
'test/codex-predictive-echo.test.ts', // also needs a real codex binary
'test/split-pane-terminal.browser.test.ts',
+24 -1
View File
@@ -156,10 +156,33 @@ ask() {
fi
}
# True when host $1 accepts a connection on port $2 within about a second.
# A listening port answers at once and a closed one is normally refused at
# once, but on WSL a connect to a closed 127.0.0.1 port is dropped and only
# fails at the kernel's connect timeout, minutes later. No answer in time
# reads as free. Bash 3.2 clean: no `timeout` (macOS ships none), no `wait -n`.
port_answers() {
local pid tries=0
(exec 3<>"/dev/tcp/$1/$2") 2>/dev/null &
pid=$!
while kill -0 "$pid" 2>/dev/null; do
if ((tries >= 20)); then
kill "$pid" 2>/dev/null
# The 2>/dev/null keeps bash 3.2 from printing a "Terminated" job line on
# the first-run path; bash 5.2 prints nothing without it, so CI won't notice.
wait "$pid" 2>/dev/null
return 1
fi
tries=$((tries + 1))
sleep 0.05
done
wait "$pid"
}
# True when something on this host already accepts connections on the port.
# bash's /dev/tcp needs no extra tool on Linux or macOS.
port_in_use() {
(exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null || (exec 3<>"/dev/tcp/::1/$1") 2>/dev/null
port_answers 127.0.0.1 "$1" || port_answers ::1 "$1"
}
first_free_port() {
+43
View File
@@ -905,6 +905,49 @@ 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.
## Listing a directory (`GET /api/v1/sessions/:id/files?lazy=1`)
The Files panel opts into one-directory listings for local workspaces with
`lazy=1`. Without `path`, the response lists immediate children of the selected
root. Expanding a folder sends its returned `path` to the same endpoint.
Directories omit `children` until the browser loads them. No descendant scan or
shared depth/node budget is spent on a lazy listing.
For example, the panel starts with `?lazy=1&root=live-any`, then requests
`?lazy=1&root=live-any&path=<returned-path>` to expand a folder. URL-encode the
returned path; it is not necessarily relative to the selected root.
The success envelope contains `data.root`, `lazy: true`, `tree`, per-page
`totalFiles`/`totalDirectories`, and `truncated`. Pages contain at most 500 entries,
directories first and then names in ascending order. A non-final page includes
an opaque `nextCursor`; pass it back as `cursor` with the same session, root,
path and `showHidden` preference. A cursor is a continuation key, not a filesystem
snapshot: changes before that key become visible on Refresh. Each request reads
the named directory's entries and obtains file metadata only for its page.
`showHidden=true` adds dot-prefixed entries; the existing generated-directory
exclusions remain. Requested folders retain workspace realpath confinement and
bounded reachability probes. Missing folders return 404, non-directories 400,
out-of-scope/excluded/hidden paths 403, and unavailable folders 422. Invalid or
incompatible cursors return 400.
Symbolic links retain the existing file-row representation, so the browser does
not expand directory links. Preview and download still use their existing path guards.
The existing `root=live`/`root=live-any` worktree rules and `worktree` metadata
apply. Paths remain relative to `workingDir` for inside worktrees and absolute
for followed outside worktrees. SSH sessions retain the existing listing behavior;
this mode adds no remote filesystem capability.
Without `lazy=1`, recursive listing responses are unchanged. A valid `q` query
uses the existing flat search response, including when `lazy=1` is present.
Search retains its 5,000-entry scan budget, 1,000-match cap, depth limit (default
5, maximum 10), and read ceiling. It reports `truncated: true` when a limit or an
unreachable folder leaves the search incomplete. Existing `q` responses are unchanged.
The panel's filtering, search, pagination and retry controls are described in
[Working With Files](wiki/Working-With-Files.md#the-file-viewer).
## Deleting a file (`DELETE /api/v1/sessions/:id/files?path=`)
The Files panel's delete button. `path` is what the listing gave the row: relative to the
+55 -13
View File
@@ -18,7 +18,9 @@ Implementation detail extracted from `CLAUDE.md` so that file stays small enough
### The prefix table on Codeman's socket holds only send-prefix
**Browser tabs are tmux clients, so tmux's prefix table must not reach `switch-client`** (`src/tmux-prefix-table.ts`, called from `createSession` before `respawn-pane`, and from `reconcileSessions()` at boot whenever the socket lists a pane, so sessions that survived an upgrade are covered). Every keystroke typed into a browser terminal reaches the `tmux attach-session` client behind it, and app.js deliberately lets Ctrl+B through to the terminal (readline, Claude Code's "ctrl+b ctrl+b"). With tmux's stock prefix table, Ctrl+B then `(` `)` `L` `s` `w` moved that client onto ANOTHER session, which the tab then showed and typed into under the original's label; `d` detached it, `$` renamed the session, `:` opened tmux's prompt. So the table is reduced to `<prefix> send-prefix` (the socket's configured prefix, read with `show-options -gv prefix`), once per tmux server in practice: the reset only runs while `list-keys -T prefix` shows anything else. The same reduction is applied when Codeman creates the nested tmux behind a Docker case (`-L codeman-docker`) or an owned remote session (`-L codeman-remote`). Those servers set `prefix C-q` and used to keep tmux's stock prefix table, so inside the pane Ctrl+Q then `)` `(` `s` `w` or `L` ran `switch-client` / `choose-tree` on the inner server and moved its client onto a sibling session. `nestedPrefixTableResetCommands()` (bind `C-q send-prefix`, then `unbind-key -a -T prefix`, then bind it again, so a user config that left the prefix table empty cannot make `unbind-key -a` abort the `\;` chain) is appended to both create chains, before `remain-on-exit failed` on the remote chain so a remote tmux that rejects `failed` cannot drop it. Those sockets are dedicated to Codeman, so the server-global table is the right scope. A non-owned remote attach joins another Codeman's `-L codeman` and does not run it. ⚠️ Keep `send-prefix`: Claude Code inside tmux backgrounds a command with "ctrl+b ctrl+b". ⚠️ Never touch the `root` table, and tolerate (and re-bind after a reset) `C-<letter> detach-client`: `codeman tui`'s attach claims F1 and Alt+1..9 in `root` and the held-Ctrl alias `C-d` in `prefix` (`beginAttachHandoff`), and a session created mid-attach must not take that way out away. ⚠️ Key tables are server-wide. F1 and the held-Ctrl `C-d` still detach every client for the length of an attach (a way out, not a session move). **`M-1`..`M-9` do not move other clients.** `bindSwitchKey` binds them to `if-shell -F` (`tuiSwitchGuard`) so `switch-client` runs only when `#{client_tty}` is the TUI's terminal and `#{client_pid}` equals `@codeman-tui-pid`. A one-shot `client-attached[90]` hook (`tuiSwitchAttachHook`) sets that option as the TUI's client attaches, then removes itself. It is armed as the handoff's last tmux call before `spawnSync`, after the keys and the per-session bars, so only a TUI killed during the attach's own startup can leave that hook armed for its tty. A browser tab does not match, including Esc followed by a digit within `escape-time` (500 ms on tmux 3.4), which arrives as the same `M-<digit>`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-<digit>`, which writes Esc and the digit into that client's own pane, so a vim `<Esc>2j` in a browser tab is not eaten by the root binding. If the TUI is killed before `restore()`, the binding can remain, but the stored pid is the dead client and the hook will not re-arm a pty that reuses the number, so the key never switches and every client gets it in its pane through the else branch. `restore()` removes the keys only while they still name this tty, and the next attach that claims the strip releases any of these bindings first. A second TUI attach replaces the keys (one binding per key). Escape-time on Codeman's socket stays at tmux's default: lowering it would change Esc delivery for every pane, and the guard already refuses other clients. ⚠️ The consequence for every terminal attach: `Ctrl+B d` does not exist on this socket. Anything that attaches a user's terminal claims its own way out for the attach, as `beginAttachHandoff` and `scripts/tmux-manager.sh` (F1 in `root`) do, and never advertises tmux's stock chord. Tests: `test/tmux-prefix-table.test.ts` (real tmux on a private socket, driven through a pty attach client, including the nested `C-q` table), `test/tui/tui-switch-guard.test.ts` (the guarded Alt keys against a second client), the wiring in `test/tmux-manager.test.ts`, the script in `test/tmux-manager-script-attach.test.ts`.
**Browser tabs are tmux clients, so tmux's prefix table must not reach `switch-client`** (`src/tmux-prefix-table.ts`, called from `createSession` before `respawn-pane`, and from `reconcileSessions()` at boot whenever the socket lists a pane, so sessions that survived an upgrade are covered). Every keystroke typed into a browser terminal reaches the `tmux attach-session` client behind it, and app.js deliberately lets Ctrl+B through to the terminal (readline, Claude Code's "ctrl+b ctrl+b"). With tmux's stock prefix table, Ctrl+B then `(` `)` `L` `s` `w` moved that client onto ANOTHER session, which the tab then showed and typed into under the original's label; `d` detached it, `$` renamed the session, `:` opened tmux's prompt. So the table is reduced to `<prefix> send-prefix` (the socket's configured prefix, read with `show-options -gv prefix`), once per tmux server in practice: the reset only runs while `list-keys -T prefix` shows anything else. A blank answer there is read from the full `list-keys` listing instead (its `-T prefix` lines only): tmux 3.7 through 3.7c (tmux commit 09bd686327, fixed in 3.8 by 7ec94fda08) print nothing on stdout for `list-keys -T <table>` when the table holds exactly one binding (the line goes to a status message instead), which is the reduced shape, so the reduced table read as needing a reset on every call. `codeman tui` reads its key tables the same way (`listKeyTable` in `src/tui/tui-client.ts`), or a bound key there reads as free. The same reduction is applied when Codeman creates the nested tmux behind a Docker case (`-L codeman-docker`) or an owned remote session (`-L codeman-remote`). Those servers set `prefix C-q` and used to keep tmux's stock prefix table, so inside the pane Ctrl+Q then `)` `(` `s` `w` or `L` ran `switch-client` / `choose-tree` on the inner server and moved its client onto a sibling session. `nestedPrefixTableResetCommands()` (bind `C-q send-prefix`, then `unbind-key -a -T prefix`, then bind it again, so a user config that left the prefix table empty cannot make `unbind-key -a` abort the `\;` chain) is appended to both create chains, before `remain-on-exit failed` on the remote chain so a remote tmux that rejects `failed` cannot drop it. Those sockets are dedicated to Codeman, so the server-global table is the right scope. A non-owned remote attach joins another Codeman's `-L codeman` and does not run it. ⚠️ Keep `send-prefix`: Claude Code inside tmux backgrounds a command with "ctrl+b ctrl+b". ⚠️ Never touch the `root` table, and tolerate (and re-bind after a reset) `C-<letter> detach-client`: `codeman tui`'s attach claims F1 and Alt+1..9 in `root` and the held-Ctrl alias `C-d` in `prefix` (`beginAttachHandoff`), and a session created mid-attach must not take that way out away. ⚠️ Key tables are server-wide. F1 and the held-Ctrl `C-d` still detach every client for the length of an attach (a way out, not a session move). **`M-1`..`M-9` do not move other clients.** `bindSwitchKey` binds them to `if-shell -F` (`tuiSwitchGuard`) so `switch-client` runs only when `#{client_tty}` is the TUI's terminal and `#{client_pid}` equals `@codeman-tui-pid`. A one-shot `client-attached[90]` hook (`tuiSwitchAttachHook`) sets that option as the TUI's client attaches, then removes itself. It is armed as the handoff's last tmux call before `spawnSync`, after the keys and the per-session bars, so only a TUI killed during the attach's own startup can leave that hook armed for its tty. A browser tab does not match, including Esc followed by a digit within `escape-time` (500 ms on tmux 3.4), which arrives as the same `M-<digit>`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-<digit>`, which writes Esc and the digit into that client's own pane, so a vim `<Esc>2j` in a browser tab is not eaten by the root binding. If the TUI is killed before `restore()`, the binding can remain, but the stored pid is the dead client and the hook will not re-arm a pty that reuses the number, so the key never switches and every client gets it in its pane through the else branch. `restore()` removes the keys only while they still name this tty, and the next attach that claims the strip releases any of these bindings first. A second TUI attach replaces the keys (one binding per key). Escape-time on Codeman's socket stays at tmux's default: lowering it would change Esc delivery for every pane, and the guard already refuses other clients. ⚠️ The consequence for every terminal attach: `Ctrl+B d` does not exist on this socket. Anything that attaches a user's terminal claims its own way out for the attach, as `beginAttachHandoff` and `scripts/tmux-manager.sh` (F1 in `root`) do, and never advertises tmux's stock chord. Tests: `test/tmux-prefix-table.test.ts` (real tmux on a private socket, driven through a pty attach client, including the nested `C-q` table), `test/tui/tui-switch-guard.test.ts` (the guarded Alt keys against a second client),Line truncated
**The attach keeps each window it dressed following the client used last** (`TUI_FOLLOW_HOOKS` in `src/tui/tui-client.ts`, `set-hook -t` per session, never `-g`). Codeman's web resize runs `resize-window` and its own attach runs `setManualWindowSize()`, and either puts the window on `manual` at the browser's size, so before this a phone opening the session mid-attach pinned the terminal to a phone-sized pane until a detach. One hook, `client-active[91]`, puts `latest` back when the TUI's client becomes the latest one again (typing, pasting or resizing the terminal after another client was used, measured on tmux 3.8). A browser resize makes the tab's client the latest one, because `Session.resize()` resizes that client's pty before tmux sees the `resize-window`. ⚠️ A forced resize at an unchanged size (Redraw, a closing pop-out window, the split pane; a browser opening a session sends none, since `selectSession` resizes without `force` and the server drops an unchanged size) would not change the pty, so tmux would keep the terminal as the latest client and its next key would undo the user's Redraw. `Session.resize()` nudges the pty one row first (`FORCED_RESIZE_NUDGE_MS`), then applies the real size: under `manual` with no attach the window ignores the client's pty, so the agent sees no change. The nudge runs only for a tmux-backed session (`_useMux` and a mux session): on a direct PTY the process is the agent itself, which would get two height changes for nothing. Cost: the first browser resize after the terminal was used changes the agent's height twice (the window is on `latest`, so the tab's pty moves it, then `resize-window` does), where master changes it once; later resizes from the same tab cost one. Height changes cost Claude's inline renderer transcript lines (#672), which is why there is no second hook on `after-resize-window`: keeping `latest` through every browser resize cost three. The hook is a constant command that reads the session option `@codeman-tui-follow` (the owner's tty), so a hook whose owner is gone does nothing. `@codeman-tui-follow-pid` records the TUI process, because a tty proves nothing: Linux hands the next terminal the pty that just closed, and a browser tab's attach client can land on it. `restore()` drops the owner first, then the hook, only while the owner is this tty, and before the window sizes are put back. `clearLeakedFollowTyping()` drops every owner this process did not arm whose recorded pid is not another live process; it runs at TUI startup and again before each attach dresses its sessions, since a leaked hook undoes `presizeWindow()` and `codeman tui <n>` has no dashboard. ⚠️ When ours is the only entry of the event, the whole session array is unset: `set-hook -u` on one index leaves an empty session-level array, which keeps hiding a global hook on that event (the same trap as `status-format[0]`). For the same reason nothing is armed while the user has a global `client-active` hook. ⚠️ The command carries no `-t`: tmux parses a hook command when it is set, and an unquoted `#{session_name}` there starts a comment. Tests: `test/tui/tui-follow-typing.test.ts` (real tmux, two pty clients), `test/session-resize-arbitration.test.ts` (the nudge).
### Reverse-proxy base path
@@ -135,7 +137,7 @@ Further detail: ⚠️ An ADOPTED container may back SEVERAL cases at different
⚠️ **`param` is TWO namespaces.** `launch.params` keys, `env.configSetenv[].fromParam` and `capabilities.privilegedParams[].param` all name a LAUNCH PARAM; the legacy `<Mode>Config` wire field is a separate namespace, bridged only by `launch.legacyConfigAliases`. Getting `privilegedParams[].param` wrong is SILENT — it is the multi-user bypass clamp's only handle on a CLI's privilege switch, and a wrong name clamps nothing with no load error and no failing test — so `schema.ts` rejects an entry naming a param it never declared. Codex is the entry where the two names differ (`bypassApprovals` vs `dangerouslyBypassApprovals`) and therefore the one that catches a regression.
⚠️ Five fields are DECLARED-FOR-LATER and read by nothing (`accent`, `capabilities.echo`/`wheelForward`/`keyboardAccessory`/`maxFrameBytes`): all frontend behaviour, transcribed rather than measured (except `accent`, measured against styles.css on 2026-09-21), so re-measure before wiring one up; the list is pinned so it cannot quietly grow. (`shortBadge` left the list when the Settings CLI management list started showing it.)
⚠️ Four fields are DECLARED-FOR-LATER and read by nothing (`accent`, `capabilities.echo`/`keyboardAccessory`/`maxFrameBytes`): all frontend behaviour, transcribed rather than measured (except `accent`, measured against styles.css on 2026-09-21), so re-measure before wiring one up; the list is pinned so it cannot quietly grow. (`shortBadge` left the list when the Settings CLI management list started showing it, and `wheelForward` when the browser's wheel gate started reading it.)
Spawn commands are pinned as literal strings in `test/cli-registry-spawn-golden.test.ts`, remote/docker pane commands in `test/location-overlay-commands.test.ts`. ⚠️ That second golden no longer covers **remote claude or remote omp**: both now have their own arm in `buildRemoteLaunchCommand` (a `--session-id || --resume` pair, and `--continue`, so a respawn continues the same conversation) and never reach `defaultRemoteCommandForMode`, which is what that test asserts. Their real pins are `toContain` substrings in `test/tmux-manager.test.ts` and `test/remote-shared-sessions.test.ts`; changing either arm will NOT fail the golden.
@@ -145,7 +147,7 @@ Spawn commands are pinned as literal strings in `test/cli-registry-spawn-golden.
### Input delivery and WS resilience
**Input**: `session.writeViaMux()` for programmatic/curl input — the text as one tmux bracketed paste (`paste-buffer -p`, so Codex cannot fold the Enter into a paste burst) + `send-keys Enter`. A single character is typed with `send-keys -l` instead (`submitsAsKeys()`): Claude Code's and Codex's selection dialogs ignore a pasted `3`, and the Enter then confirms the highlighted option. A multi-line prompt keeps its line breaks inside that one paste, with or without the Enter (fire-and-once). Interactive **browser** input goes through a durable **exactly-once** layer: each frame carries a stable `clientId` + monotonic per-session `seq`, persisted to localStorage until the server ACKs (`{t:'ia',seq}` over WS, or HTTP 2xx), so a dropped link/reconnect can't lose or double-deliver a prompt. A duplicate is ACKed as `{t:'ia',seq,dup:true,last}` so a client whose persisted counter rolled back below the server's watermark can lift itself out instead of typing into a silently dead terminal (`docs/reliable-input-delivery.md`). **WS resilience** (#149): the upgrade URL carries `cid = clientId + ':' + perTabNonce`, and `ws-connection-registry.ts` supersedes only same-TAB reconnects (two tabs on one session coexist; input frames keep the bare `clientId` for seq dedup); reconnects back off exponentially (attempts preserved across `_connectWs`), and the header connection chip renders from a real `_wsState` lifecycle (`connecting`/`connected`/`fallback`/`reconnecting`/`disconnected`).
**Input**: `session.writeViaMux()` for programmatic/curl input — the text as one tmux bracketed paste (`paste-buffer -p`, so Codex cannot fold the Enter into a paste burst) + `send-keys Enter`. A single character is typed with `send-keys -l` instead (`submitsAsKeys()`): Claude Code's and Codex's selection dialogs ignore a pasted `3`, and the Enter then confirms the highlighted option. A multi-line prompt keeps its line breaks inside that one paste, with or without the Enter (fire-and-once). Interactive **browser** input goes through a durable **exactly-once** layer: each frame carries a stable `clientId` + monotonic per-session `seq`, persisted to localStorage until the server ACKs (`{t:'ia',seq}` over WS, or HTTP 2xx), so a dropped link/reconnect can't lose or double-deliver a prompt. **Session FIFO** (`_enqueueInput`, app.js, #830): every browser producer (typed main-pane input, toolbar submit, accessory keys and commands, paste, Compose, voice, image upload) captures its session id when the user acts and enqueues ops (`write`, `key`, `gap`) on that session's FIFO, which drains them in order: a `write` goes to `_enqueueReliableInput`, a `key` (a modified Enter such as Shift/Ctrl+Enter) is a direct `POST /api/sessions/:id/send-key` outside the exactly-once layer, and a `gap` delays the next op. ⚠️ A `gap` orders ENQUEUEING only: the next op is handed to the reliable layer after the delay, with no wait for the previous frame's ACK, so a delayed Enter keeps its session and its place but gains no delivery guarantee beyond the exactly-once layer. ⚠️ Ops for an id missing from `app.sessions` are dropped (a probe or deleted session never reaches the wire; tests must register their session). ⚠️ `_cleanupSessionData()` clears the session's FIFO and its pending gap timer, so a deleted session cannot type into a reused id. A duplicate is ACKed as `{t:'ia',seq,dup:true,last}` so a client whose persisted counter rolled back below the server's watermark can lift itself out instead of typing into a silently dead terminal (`docs/reliable-input-delivery.md`). **WS resilience** (#149): the upgrade URL carries `cid = clientId + ':' + perTabNonce`, and `ws-connection-registry.ts` supersedes only same-TAB reconnects (two tabs on one session coexist; input frames keep the bare `clientId` for seq dedup); reconnects back off exponentially (attempts preserved across `_connectWs`), and the header connection chip renders from a real `_wsState` lifecycle (`connecting`/`connected`/`fallback`/`reconnecting`/`disconnected`).
### Per-session env overrides: exact-key allowlist and CLAUDE_CONFIG_DIR
@@ -251,7 +253,9 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect`
### Full-scrollback replay
**Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 0.3 s at 100k lines); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes may still re-pull `full=1` at the TOP, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; outpLine truncated
**Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 1 s at 100k lines; measured capture details below); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marLine truncated
**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not Docker or adopted (their local pane hosts a nested tmux client in the alternate screen, so `?full=1` returns one screen the downgrade guard refuses; remote sessions stay eligible, since the route splices the remote scrollback in), not detached, not owned by tiles, with no pull or buffer load in flight, no terminal load state for the session (a tab switch sets it before the buffer load opens), and no drop-recovery refresh owning the session (`_terminalRefreshOwner`, set for the whole fetch, before that refresh opens its buffer load). `_maybeRefetchFullHistory` returns early on that same owner, so Reload, Load full history and the top-of-buffer pull all stand aside instead of running a second capture whose download-time queue the refresh's own load would replace; the refresh re-syncs the action when it starts and when its `finally` releases the owner. `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). The bar is a polite live region (`role="status"`), but only the truncation notice is announced: a reload-only bar sets `aria-live="off"` before it re-renders, since it comes back on nearly every scroll-up in a busy tab, and its button stays reachable with Tab. Its × is labelled for what the bar carries: "Dismiss history notice" with the notice, "Dismiss Reload history" without it. A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line, and shares Reload's loading state, so the re-render the in-flight pull triggers keeps it on Loading… instead of bringing it back enabled; otherwise it keeps the top anchor and no loading state, so the bar still hides on a scroll back to live output. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrLine truncated
**The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`.
@@ -267,7 +271,7 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect`
⚠️ **What a mouse-DECSET strip (full or mouse) removes, it must REMEMBER.** Stripping the mouse DECSETs means xterm's `modes.mouseTrackingMode` is permanently `'none'` for those modes, so the browser hand-encodes click reports to compensate (`_sendSyntheticSgrTap`). With no state to consult it did that on EVERY click, which delivered mouse reports to programs that never asked for them: the same pane runs a plain shell whenever the CLI has exited or a `shell` was started inside a claude-mode session, and a shell prints the report as literal text (`[<0;88;20M`), garbling the next line typed. `_recordStrippedMouseMode()` therefore records each stripped sequence as it goes and publishes `cliMouseTracking` through `toState()`, and `_shouldReportMouseToCli()` requires it. ⚠️ Only the TRACKING modes count (1000/1001/1002/1003): 1005/1006 select an ENCODING and 1007 is alt-scroll, and counting those would put the stray reports straight back. ⚠️ The change broadcasts IMMEDIATELY rather than through `broadcastSessionStateDebounced`, because the flag flips when a dialog opens and the user can click that dialog inside the 500ms debounce window. Measured on a live claude 2.x: the CLI holds a tracking mode on continuously in fullscreen (so clicks keep being reported exactly as before; the default inline renderer holds none, measured on 2.1.283 even with `/model` open), while a bash prompt in the same stripped mode reports nothing. Fails toward silence: after a server restart the flag is false until the CLI re-emits, which tmux does at client attach.
**Wheel forwarding requires observed mouse tracking: Claude ≥ 2.1.187, tracked Codex, tracked Copilot or tracked Pi** (`terminal-ui.js:_shouldForwardWheelToApp`). The original #227 measurement remains valid for **Codex 0.147.0 inline**: `alternate_on=0`, `mouse_any_flag=0`, growing tmux history, and SGR wheel reports do nothing. Claude 2.1.280 inline similarly reports `alternate_on=0`, `mouse_any_flag=0`; forwarding there swallows gestures, so it keeps local scrollback. Fullscreen Claude (`CLAUDE_CODE_NO_FLICKER=1` or `"tui": "fullscreen"`) enables mouse tracking and accepts reports. **Fresh Codex 0.163.0 fullscreen measurement (2026-10-18, isolated local tmux pane)**: `alternate_on=1`, `mouse_any_flag=1`; one `\x1b[<64;10;10M` report moves the transcript one row upward, and `\x1b[<65;10;10M` restores the original screen. This is capability evidence, not a minimum-version promise: untracked Codex (including a 0.162.0 measurement (2026-10) with `mouse_any_flag=0`) keeps local history or the hollow-pane paging fallback. Codex does not publish the Claude-only CLI version field, so its gate requires the observed flag rather than a Claude version. The registry records this as `wheelForward.mode: 'always'` (observed mouse tracking is still required); Claude remains `version-gated`. A stale/false flag after startup cannot authorize forwarding. ⚠️ A strip mode alone is not evidence that a CLI consumes SGR reports. Verify with a real `\x1b[<64;c;rM` write into a live pane before adding a mode here. Hand-encoded SGR taps remain independently gated by `_shouldReportMouseToCli()`; the older #325 no-op measurement describes untracked inline Codex and must not be generalized to newer tracked fullscreen renderers. Shift/local-history opt-outs and xterm's native mouse/alternate-screen handling remain intact.
**Wheel forwarding requires observed mouse tracking: Claude ≥ 2.1.187, tracked Codex, tracked Copilot or tracked Pi** (`terminal-ui.js:_shouldForwardWheelToApp`). The original #227 measurement remains valid for **Codex 0.147.0 inline**: `alternate_on=0`, `mouse_any_flag=0`, growing tmux history, and SGR wheel reports do nothing. Claude 2.1.280 inline similarly reports `alternate_on=0`, `mouse_any_flag=0`; forwarding there swallows gestures, so it keeps local scrollback. Fullscreen Claude (`CLAUDE_CODE_NO_FLICKER=1` or `"tui": "fullscreen"`) enables mouse tracking and accepts reports. **Fresh Codex 0.163.0 fullscreen measurement (2026-10-18, isolated local tmux pane)**: `alternate_on=1`, `mouse_any_flag=1`; one `\x1b[<64;10;10M` report moves the transcript one row upward, and `\x1b[<65;10;10M` restores the original screen. This is capability evidence, not a minimum-version promise: untracked Codex (including a 0.162.0 measurement (2026-10) with `mouse_any_flag=0`) keeps local history or the hollow-pane paging fallback. Codex does not publish the Claude-only CLI version field, so its gate requires the observed flag rather than a Claude version. The registry records this as `wheelForward.mode: 'always'` (observed mouse tracking is still required); Claude remains `version-gated`. That field is the gate's only per-CLI rule: `renderIndexHtml` publishes every CLI's `wheelForward` (disabled ones included, since their sessions keep running; `never` left out) as `window.__codemanWheelForward`, so a custom `clis.json` entry forwards under its own id, and a `minVersion` that is not `MAJOR.MINOR.PATCH` refuses forwarding. A stale/false flag after startup cannot authorize forwarding. ⚠️ A strip mode alone is not evidence that a CLI consumes SGR reports. Verify with a real `\x1b[<64;c;rM` write into a live pane before adding a mode here. Hand-encoded SGR taps remain independently gated by `_shouldReportMouseToCli()`; the older #325 no-op measurement describes untracked inline Codex and must not be generalized to newer tracked fullscreen renderers. Shift/local-history opt-outs and xterm's native mouse/alternate-screen handling remain intact.
**Copilot also receives forwarded reports** (1.0.95 measured in tmux: alt screen, `mouse_any_flag=1`): its mouse DECSETs are stripped so a drag selects, which also stops xterm encoding the wheel for it, so `_shouldForwardWheelToApp` sends the same SGR reports by hand while `cliMouseTracking` is true; six `\x1b[<64;…M` reports moved its transcript 18 lines, a phone swipe takes the same gate, and there is NO version gate.
@@ -297,7 +301,7 @@ Further detail, closing: ⚠️ **Closing has the mirror-image race and one owne
### An exited agent in a live pane (`paneExit`)
**Codeman creates every pane with `remain-on-exit on`, so a session whose agent exited still looks alive.** `/exit` ends the CLI, tmux keeps the pane and the tmux session, and the `tmux attach-session` process Codeman records as `Session.pid` runs on, so no PTY exit handler fires and the record keeps its pid and `status: 'idle'` (Ark0N/Codeman#446). `SessionState.paneExit` (`{status?, signal?, at}`) is the fact tmux already knows, published through `toState()` so it rides `session:updated` and lands in `state.json` on the same persist — there is no SSE event for it. One batched `tmux list-panes -a` per tick fills it, from `TmuxManager.startPaneExitWatcher()`, which has its OWN always-on interval: the stats collector cannot carry it, because the browser arms and disarms that one with the Monitor panel (`panels-ui.js`) and boot skips it entirely when no session was recovered. ⚠️ **The field is TRI-STATE and its third state is absence**, meaning UNKNOWN, which renders as nothing and must NEVER read as alive; it covers a running pane, a session the read did not list, a failed probe, and every session shape a dead local pane does not describe. `Session.paneExitApplies` is the single place that scoping lives, and it fails closed for four shapes: a direct-PTY session (no pane), a remote SSH session (the local pane is the ssh client, whose death is a transport drop OR an exit — the whole of #355), a docker case (the local pane is a `docker exec` into the container's own tmux), and a session rebuilt from the socket (`MuxSession.discovered`: its synthetic `restored-<fragment>` id matches no `state.json` entry, so a remote session rediscovered after `mux-sessions.json` was lost would arrive looking local). ⚠️ **Never set `status: 'error'`** for an exited pane — that value is the PTY-exit breaker's and the browser answers it with a "restart it?" confirm — and **never null the `pid`**, which is what makes `selectSession()` re-attach and launch a fresh CLI. Local panes keep `remain-on-exit on`; flipping them to `failed` ends the tmux session, nulls the pid and reintroduces the auto-revive #355 removed. ⚠️ **An absent `#{pane_dead_status}` is not 0**: measured on tmux 3.2a a SIGKILLed pane reports neither a status nor a signal (`#{pane_dead_signal}` did not exist before tmux 3.4), so folding it into 0 would turn an unexplained death into a clean exit. A session answers only when the read listed EXACTLY ONE pane for it, since Codeman never splits a pane and a session the user split by hand has none that speaks for the agent. The three synchronous `isPaneDead()` callers (the `/wait` route, the TUI, the attach path) keep their own probes — this watcher is never fresh enough for them. ⚠️ **A path that starts a command in a pane must clear the record AND persist**, since the watcher's next tick sees the field already cleared and writes nothing. ⚠️ **The always-on timer gates the READ, never the tick.** `hasObservablePaneSession()` (`tmux-manager.ts`) skips the tmux exec while every session on the manager is one of the shapes `paneExitApplies` forces to UNKNOWN, so an instance running only remote or Docker work keeps ticking and costs nothing; the two predicates are two copies of one rule, and `test/session-pane-exit.test.ts` pins them against each other for the four session shapes that exist today — a FIFTH condition added to one and not the other still fails nothing, so change them together. Skipping retracts nothing, for the same reason a failed read does not. ⚠️ **The muted status dot is a specificity fight, and it is fought on three surfaces.** The tab renders `status` as before, and `tab-agent-exited` only quiets the dot, so the rule excludes three states BY HAND: `.tab-alert-action` and `.tab-alert-idle` on the tab, and `.tab-status.error` on the dot itself. Each of those colours means "this needs you" — the two alerts because a human is blocked, `error` because the browser answers it with a "restart it?" confirm — and each must survive the exit. The rich tab rail needs a SECOND copy of the rule, because its own `tab-state-*` dot rules are (0,9,1) against the strip's (0,5,0) — measured, an exited session on a detailed rail kept a full green dot and the working halo beside a badge reading "exited". Its twin matches that specificity exactly and therefore must stay BELOW those rules in source order. mobile.css needs a THIRD copy, with `!important`, because the phone block enlarges a `busy` dot and gives it a green glow that way, and `status` stays `busy` for a pane whose agent died mid-turn — without it a phone renders a grey dot still wearing the green halo. `test/session-pane-exit-ui.test.ts` resolves the real stylesheets in jsdom rather than matching selector text — styles.css for the desktop cases and both files for the phone ones — so the ordering, the hand-written exclusions and a missing phone rule all fail there. Tests: `test/session-pane-exit.test.ts`, `test/tmux-manLine truncated
**Codeman creates every pane with `remain-on-exit on`, so a session whose agent exited still looks alive.** `/exit` ends the CLI, tmux keeps the pane and the tmux session, and the `tmux attach-session` process Codeman records as `Session.pid` runs on, so no PTY exit handler fires and the record keeps its pid and `status: 'idle'` (Ark0N/Codeman#446). `SessionState.paneExit` (`{status?, signal?, at}`) is the fact tmux already knows, published through `toState()` so it rides `session:updated` and lands in `state.json` on the same persist — there is no SSE event for it. One batched `tmux list-panes -a` per tick fills it, from `TmuxManager.startPaneExitWatcher()`, which has its OWN always-on interval: the stats collector cannot carry it, because the browser arms and disarms that one with the Monitor panel (`panels-ui.js`) and boot skips it entirely when no session was recovered. ⚠️ **The field is TRI-STATE and its third state is absence**, meaning UNKNOWN, which renders as nothing and must NEVER read as alive; it covers a running pane, a session the read did not list, a failed probe, and every session shape a dead local pane does not describe. `Session.paneExitApplies` is the single place that scoping lives, and it fails closed for four shapes: a direct-PTY session (no pane), a remote SSH session (the local pane is the ssh client, whose death is a transport drop OR an exit — the whole of #355), a docker case (the local pane is a `docker exec` into the container's own tmux), and a session rebuilt from the socket (`MuxSession.discovered`: its synthetic `restored-<fragment>` id matches no `state.json` entry, so a remote session rediscovered after `mux-sessions.json` was lost would arrive looking local). ⚠️ **Never set `status: 'error'`** for an exited pane — that value is the PTY-exit breaker's and the browser answers it with a "restart it?" confirm — and **never null the `pid`**, which is what makes `selectSession()` re-attach and launch a fresh CLI. Local panes keep `remain-on-exit on`; flipping them to `failed` ends the tmux session, nulls the pid and reintroduces the auto-revive #355 removed. ⚠️ **An absent `#{pane_dead_status}` is not 0**: measured on tmux 3.2a a SIGKILLed pane reports neither a status nor a signal (`#{pane_dead_signal}` did not exist before tmux 3.4), so folding it into 0 would turn an unexplained death into a clean exit. ⚠️ **A dead pane may have no pid**: measured on tmux 3.8, `#{pane_pid}` prints blank once the pane's program exits, so `parsePaneRows()` keeps a row with no pid whenever tmux answered `#{pane_dead}`, and skips only a row with neither. On tmux 3.8 the pid goes blank when the pty closes, and `#{pane_dead}` turns 1 only once tmux has collected the exit status, which took several seconds for some exits (measured on tmux 3.4, where the pid itself stays): a row with no pid and `pane_dead` 0 is that window, and a restart in it must not drop the session. `#{pane_dead_time}` then tells one exit from the next, next to the pid, so two reads of one exit still count as two and a hand-run `respawn-pane` that exits 0 again starts a new observation. `reconcileSessions()` keeps such a tracked session alive with its last known pid, and does not rediscover an untracked one, since a made-up pid would reach `killSession()`'s process-tree walk. ⚠️ Kept alive means restored: at the next server start the restore goes through the dead-pane branch of `Session._setupOrAttachMuxSession()`, which respawns the pane and clears `paneExit` (measured on tmux 3.8, and what tmux 3.7 and older always did, since they still printed the pid). So a row kept as evidence of a crash or a startup error survives a restart only until the CLI is relaunched in it. `killSession()` reads `#{pane_dead}` with the pid and, for a dead pane, signals nothing and walks no tree: the recorded pid belongs to the program that exited and may since have been reused by an unrelated process, so only `kill-session` runs (`parsePaneKillRead()`). ⚠️ The flag alone is not trusted: before tmux 3.7 `#{pane_dead}` means only that the pty is closed, so a program that closed its tty and ignores SIGHUP reads dead while it runs. A dead reading counts only with a blank pid or a set `#{pane_dead_time}`, which keeps the old close on tmux 3.3a to 3.6. A pid below 2 is no pid: an empty active pane (`split-window ''`) prints 0 before tmux 3.8, so the close falls back to the recorded pid (`pane.pid || session.pid`), and `isSignalablePid()` refuses 0 or 1 wherever it comes from. A session answers only when the read listed EXACTLY ONE pane for it, since Codeman never splits a pane and a session the user split by hand has none that speaks for the agent. The three synchronous `isPaneDead()` callers (the `/wait` route, the TUI, the attach path) keep their own probes — this watcher is never fresh enough for them. ⚠️ **A path that starts a command in a pane must clear the record AND persist**, since the watcher's next tick seLine truncated
⚠️ **The tab's badge is translated (zh-CN), so its updates compare with English, never the DOM.** `applyPaneExitBadge()` remembers the last English badge text (`data-label`) and the tab's accessible name (`data-aria-source`), both also seeded by the full render, and writes only when those change: the translator rewrites both in zh-CN, and a DOM compare (or an unconditional set) would write the English back on every incremental pass for it to translate again. i18n.js has `exited` and patterns for `exited (N)`, `exited (signal N)` and `<name> session, agent exited ...` (the name passed through); `test/i18n-exit-run-help.test.ts` covers every `paneExitLabel()` form.
@@ -682,6 +686,8 @@ Adding the header changed the preamble, so `CODEMAN_PREAMBLE` was bumped (1.22.0
⚠️ Both `POST` and `DELETE` sit at the **same privilege bar as the profile installer** (`canUsernameRunPrivilegedCommands`) even though the action reads as "open a page": booting a dsh profile executes the plugin code in it, and the server is a single shared instance, so stopping it in multi-user mode takes it out from under other users' tabs.
⚠️ dsh's browser-auth gate answers only a request carrying the one-time launch token from its boot banner, so the supervisor trades that token for dsh's `dsh-auth-*` session cookie once at startup (`getDeepSeekWebCookie()`), and the web-tab proxy presents the cookie on BOTH legs, HTTP and WebSocket, only to a `managed: 'deepseek-web'` tab whose upstream is `127.0.0.1` on the port it was minted for. Reuse therefore needs the same starter AND a working cookie: a server whose exchange failed, or one another owner started, is restarted rather than reused. The owner check applies only in multi-user mode (a record keeps the owner it was created under, while a single-user start has none), and the browser's own `codeman_session` cookie is filtered out of both legs whether or not the dsh cookie is injected. Details: `docs/deepseek-integration.md`.
### Custom Model Endpoint Profiles
**Custom Model Endpoint Profiles** (opt-in, `customModelEndpointsEnabled`, SYNCED, default OFF; `docs/custom-model-endpoints.md`, design doc `docs/custom-model-endpoints-plan.md`; full stack — settings-panel CRUD + the Run-menu picker, on top of the backend below): points a session at a user-configured custom OpenAI-compatible endpoint — local (llama.cpp, DGX Spark, Strix Halo) or cloud (Azure AI Foundry, OpenRouter) — instead of its harness's native cloud backend. Endpoints are a read/write-array store (`custom-model-hosts.ts`, `~/.codeman/custom-model-hosts.json`) discovered via `GET <baseUrl>/v1/models`; `CustomModelHost.authStyle` is `'bearer'` (default, `Authorization: Bearer`) or `'api-key'` (Azure's convention) — **never both**, live-tested against a real server: sending both headers on one request reliably hangs it indefinitely, reproduced 3×.
@@ -822,6 +828,32 @@ Frontend `readmymind-ui.js`: header 🧠 marker-hidden (`btn-readmymind--hidden`
### Files panel search
The panel browses local workspaces through opt-in `lazy=1` directory pages (#759),
documented in [Listing a directory](api-reference.md#listing-a-directory-get-apiv1sessionsidfileslazy1).
Each request reads one directory, returns at most 500 entries and supplies `nextCursor`
when more remain. Cursor scope includes the session, selected root, directory and hidden
preference. Directories without `children` are unloaded; symbolic links keep their legacy
file-row representation, so the browser does not expand directory links. Path confinement, bounded
probes and the inside/outside worktree rules apply to every request.
The browser caches loaded pages in the current tree epoch. Owner, epoch, hidden preference,
selected root and tree identity guard folder/page responses. Typing filters loaded entries
without a request; Enter uses the existing workspace search, and clearing restores the tree.
Expand All opens only loaded folders. Refresh retains visible expansion state; automatic
restoration skips recorded load errors and hidden-off expansions before requesting pages.
Hidden-path checks are relative to the listing root, so a worktree's dotted prefix does not
hide its ordinary folders. Explicit Retry loads the failed folder/page; errors retain entries
already loaded. A page lists the folder's directories before its files, and that order holds
across pages, so a restore or a reveal that has a file loaded for a folder stops asking for
more pages: the folder it looks for is not there. A restore then forgets that expansion
(the folder was deleted or renamed); one stopped by a failed page keeps it. An expanded
folder whose own request has not started is drawn with the loading line, never as an empty
folder, and a search-result folder opened while the tree was still loading runs the restore
when it is done. Tests: `test/routes/file-routes-lazy.test.ts`, `test/file-browser-lazy.test.ts`
and `test/mobile/file-browser.test.ts`.
The recursive listing and `q` search policies below remain unchanged for existing callers.
**Files panel search** (COD-236, the `q` param on `GET /api/sessions/:id/files`): `compileFileQuery()` (`utils/file-query.ts`, pure, no IO, so it unit-tests directly) compiles the query into a reusable predicate, which is what lets the server-side walk prune instead of streaming the whole tree.
⚠️ **A query turns that endpoint into a FLAT match list rather than a nested tree**, and the walk deliberately recurses past non-matching directories, since the whole point of searching is to reach a file whose ancestors do not match. An empty or whitespace-only query compiles to `null`, which is what keeps the default tree response byte-identical when no search is requested.
@@ -1081,7 +1113,7 @@ Tests: `test/tab-rail-search.test.ts` (gate) and `test/tab-rail-search.browser.t
### Split-pane sessions
**Split-pane sessions** (`showSplitButton`, header button, default OFF, per-device like `showFileViewerButton` — not in `SettingsUpdateSchema`, `displayKeys` in settings-ui.js): shows two live sessions side-by-side in one Codeman window. Pane A is the untouched, existing singleton terminal (`this.terminal`/`this._ws` in terminal-ui.js); Pane B is an independent `TerminalTile` (terminal-tile.js, constructed by the orchestration in terminal-split.js) with its own xterm instance and its own `/ws/sessions/:id/terminal` WebSocket, whose `cid` is the tab's identity with a `:tile` suffix, so it can never supersede the primary pane's socket (the registry supersedes by cid per session). ⚠️ **Pane B is deliberately plainer than Pane A** — no local-echo overlay, no CJK IME, no touch/mobile handlers, no keyboard accessory bar (it does carry the primary pane's hollow-buffer wheel paging and desktop click report, through terminal-ui.js's own gates aimed at the tile, and its own keyCode-229 soft-keyboard controller from terminal-keycode229-recovery.js, the #441 next-keydown drain and #541's edit-based diff for Android autocorrect, since the 1180px width gate is reachable by a wide Android tablet; see terminal-tile.js's fileoverview) — since this is a desktop-only feature (a split view needs a wide viewport) and those features exist for mobile/touch input; `.btn-split` is hard-hidden below 1180px regardless of the setting by the `@media (max-width: 1179px)` rule in styles.css (mobile.css only carries a comment pointing at it: that file loads up to 1023px, so it cannot cover the 1024-1179px tablet range the feature also needs to stay off), and the per-device setting means turning it on at a desk can never sync it onto a phone in the first place. No persistence: closing the browser tab or reloading always returns to the normal single-pane view; there is no localStorage key for split state. ⚠️ Splitting a session against itself is disallowed (the picker excludes the active session), **as is splitting against a popped-out (detached) session** — `buildSplitPickerSessions()` excludes `detachedSessions` because a detached session's own window is already claiming its PTY size, and `MAX_WS_PER_SESSION` needs no change since Pane A/B are always two different sessions. ⚠️ Either pane's session ending (deleted locally or from another client) auto-collapses the split — Pane A's session ending promotes Pane B to the new single pane via `selectSession(id, { auto: true })` (an app-driven selection, so it must not spend the session's idle alert — see the Approvals Inbox note above), never by trying to hot-swap the lightweight `TerminalTile` object into the primary singleton state. ⚠️ Pane B refits on every window/sidebar/tab-rail resize via the SAME trailing-edge `ResizeObserver` callback that resizes Pane A (`throttledResize` in terminal-ui.js) — it only ever measured Pane A's own container, so without the explicit `this._forEachTile?.((tile) => tile.fit(), { grid: false })` call there (grid tiles are left out: the grid's own observer refits them on the same resize) Pane B silently kept its stale PTY size through every resize that did not happen to be a divider drag. ⚠️ A dropped WebSocket writes a `[disconnected, reconnecting…]` marker into Pane B and reconnects on the primary pane's backoff ladder (`CodemanWsReconnect` plus jitter; the attempt count resets only on a successful open), then refreshes the buffer to close the output gap. ⚠️ The open handler clears `_wsClosed`/`_markerOwed` BEFORE that refresh, or the refresh re-owes the marker and stamps it under a healthy pane. ⚠️ 4003/4004/4009/4010 stop the pane for good, report once through `onExit(code)` and write a marker saying why (`CodemanWsReconnect` alone would retry 4003). ⚠️ A replacement socket detaches the old one first and every handler ignores a socket that is no longer `this.ws`, so a late 4010 from a superseded socket cannot stop its successor; `destroy()` cancels a pending reconnect. Related but distinct: `detachSession()` already opens one session in a separate OS-level browser window (`isSoloWindow`) — that is prior art for "two sessions visible at once" but not for one window with a draggable in-page divider, which is what this feature adds. ⚠️ Pane B installs its own `attachCustomKeyEventHandler` gating the same app-level chords Pane A's own handler gates (command palette, Alt+1-9/[/] tab nav, Alt+B sidebar toggle, Ctrl+Z suspend, Shift/Ctrl+Enter newline, smart-copy Ctrl+C) — without it the document capture-phase handler's `preventDefault()` (which never stops xterm) let each chord ALSO write its raw byte/escape sequence into Pane B's live PTY on top of whatever the app action did to Pane A (COD-153). Ctrl+Z is swallowed unless Pane B's own session is `mode === 'shell'`, mirroring terminal-ui.js's reasoning: in a plain shell it is the user's own job-control tool, everywhere else it silently suspends an unattenLine truncated
**Split-pane sessions** (`showSplitButton`, header button, default OFF, per-device like `showFileViewerButton` — not in `SettingsUpdateSchema`, `displayKeys` in settings-ui.js): shows two live sessions side-by-side in one Codeman window. Pane A is the untouched, existing singleton terminal (`this.terminal`/`this._ws` in terminal-ui.js); Pane B is an independent `TerminalTile` (terminal-tile.js, constructed by the orchestration in terminal-split.js) with its own xterm instance and its own `/ws/sessions/:id/terminal` WebSocket, whose `cid` is the tab's identity with a `:tile` suffix, so it can never supersede the primary pane's socket (the registry supersedes by cid per session). ⚠️ **Pane B is deliberately plainer than Pane A** — no local-echo overlay, no CJK IME, no touch/mobile handlers, no keyboard accessory bar (it does carry the primary pane's hollow-buffer wheel paging and desktop click report, through terminal-ui.js's own gates aimed at the tile, and its own soft-keyboard input owner: the iOS native-input owner (`_iosNativeInput`, terminal-ios-native-input.js, #830) on iOS WebKit touch, otherwise the keyCode-229 controller from terminal-keycode229-recovery.js, the #441 next-keydown drain and #541's edit-based diff for Android autocorrect, since the 1180px width gate is reachable by a wide Android tablet; see terminal-tile.js's fileoverview) — since this is a desktop-only feature (a split view needs a wide viewport) and those features exist for mobile/touch input; `.btn-split` is hard-hidden below 1180px regardless of the setting by the `@media (max-width: 1179px)` rule in styles.css (mobile.css only carries a comment pointing at it: that file loads up to 1023px, so it cannot cover the 1024-1179px tablet range the feature also needs to stay off), and the per-device setting means turning it on at a desk can never sync it onto a phone in the first place. No persistence: closing the browser tab or reloading always returns to the normal single-pane view; there is no localStorage key for split state. ⚠️ Splitting a session against itself is disallowed (the picker excludes the active session), **as is splitting against a popped-out (detached) session** — `buildSplitPickerSessions()` excludes `detachedSessions` because a detached session's own window is already claiming its PTY size, and `MAX_WS_PER_SESSION` needs no change since Pane A/B are always two different sessions. ⚠️ Either pane's session ending (deleted locally or from another client) auto-collapses the split — Pane A's session ending promotes Pane B to the new single pane via `selectSession(id, { auto: true })` (an app-driven selection, so it must not spend the session's idle alert — see the Approvals Inbox note above), never by trying to hot-swap the lightweight `TerminalTile` object into the primary singleton state. ⚠️ Pane B refits on every window/sidebar/tab-rail resize via the SAME trailing-edge `ResizeObserver` callback that resizes Pane A (`throttledResize` in terminal-ui.js) — it only ever measured Pane A's own container, so without the explicit `this._forEachTile?.((tile) => tile.fit(), { grid: false })` call there (grid tiles are left out: the grid's own observer refits them on the same resize) Pane B silently kept its stale PTY size through every resize that did not happen to be a divider drag. ⚠️ A dropped WebSocket writes a `[disconnected, reconnecting…]` marker into Pane B and reconnects on the primary pane's backoff ladder (`CodemanWsReconnect` plus jitter; the attempt count resets only on a successful open), then refreshes the buffer to close the output gap. ⚠️ The open handler clears `_wsClosed`/`_markerOwed` BEFORE that refresh, or the refresh re-owes the marker and stamps it under a healthy pane. ⚠️ 4003/4004/4009/4010 stop the pane for good, report once through `onExit(code)` and write a marker saying why (`CodemanWsReconnect` alone would retry 4003). ⚠️ A replacement socket detaches the old one first and every handler ignores a socket that is no longer `this.ws`, so a late 4010 from a superseded socket cannot stop its successor; `destroy()` cancels a pending reconnect. Related but distinct: `detachSession()` already opens one session in a separate OS-level browser window (`isSoloWindow`) — that is prior art for "two sessions visible at once" but not for one window with a draggable in-page divider, which is what this feature adds. ⚠️ Pane B installs its own `attachCustomKeyEventHandler` gating the same app-level chords Pane A's own handler gates (command palette, Alt+1-9/[/] tab nav, Alt+B sidebar toggle, Ctrl+Z suspend, Shift/Ctrl+Enter newline, smart-copy Ctrl+C) — without it the document capture-phase handler's `preventDefault()` (which never stops xterm) let each chord ALSO write its raw byte/escape sequence into Pane B's live PTY on top of whatever the app action did to Pane A (COD-153). Ctrl+Z is swallowed unless Pane B's own session is `mode === 'shell'`, mirroring Line truncated
### Tile grid
@@ -1139,7 +1171,9 @@ Tests: `test/tab-rail-search.test.ts` (gate) and `test/tab-rail-search.browser.t
**A fold is not a keyboard.** `KeyboardHandler.handleViewportResize()` (mobile-handlers.js) used to read any visual-viewport height drop over 150px as the keyboard appearing. A virtual keyboard only ever takes HEIGHT, so a resize that changes the WIDTH is the device changing shape (a rotation, or a foldable opening or closing) and is skipped by both detection branches. Closing an iPhone Duo (626→466pt wide, 890→678pt tall) otherwise latched `keyboardVisible` with no keyboard on screen: the accessory bar appeared, `main` grew 84px of dead padding, and `updateAppHeight()`, which bails while the keyboard is up, stopped refreshing `--app-height`. The latch was sticky because clearing it needed the height back within 100px of a baseline belonging to a display the user was no longer looking at. The shape branch re-baselines instead, which is also what lets a keyboard opened after the fold be detected, and `init()` seeds `lastViewportWidth` so the first resize of the page is not itself read as a shape change.
**With the keyboard up, the new baseline is `window.innerHeight`, never the shrunk visual height.** The page sets no `interactive-widget`, so the default resizes-visual mode holds on both engines: the keyboard shrinks only the visual viewport and the layout viewport stays the display's full height (`updateLayoutForKeyboard()` relies on the same fact). The first version baselined to the shrunk height, which made `heightDiff` 0, so the settle event the OS animation fires at the new width (or any later address-bar drift) satisfied the hide branch and ran `onKeyboardHide()` with the keyboard still on screen: accessory bar hidden, the toolbar lift dropped, `main`'s padding cleared. It could not recover, because no further 150px drop can re-arm the show branch against a baseline already sitting at the shrunk height. Reproduced against the real handler in the vm harness with both the fold flavour (626x590 → 466x378 → 466x378) and the rotation flavour (393x359 → 852x150 → 852x160); `test/viewport-shape-change.test.ts` models the two heights separately and pins both.
**With the keyboard up, the new baseline is `window.innerHeight`, never the shrunk visual height.** The page sets no `interactive-widget`, so the default resizes-visual mode holds on both engines: the keyboard shrinks only the visual viewport and the layout viewport stays the display's full height (`updateLayoutForKeyboard()` relies on the same fact, but measures that height as the larger of `innerHeight` and `documentElement.clientHeight`: on a first keyboard open iOS Safari briefly reported `innerHeight` as the shrunk visual height, 323 against a 640 layout viewport, which zeroed the bars' lift). The first version baselined to the shrunk height, which made `heightDiff` 0, so the settle event the OS animation fires at the new width (or any later address-bar drift) satisfied the hide branch and ran `onKeyboardHide()` with the keyboard still on screen: accessory bar hidden, the toolbar lift dropped, `main`'s padding cleared. It could not recover, because no further 150px drop can re-arm the show branch against a baseline already sitting at the shrunk height. Reproduced against the real handler in the vm harness with both the fold flavour (626x590 → 466x378 → 466x378) and the rotation flavour (393x359 → 852x150 → 852x160); `test/viewport-shape-change.test.ts` models the two heights separately and pins both.
**A pan of the visual viewport moves `.app` with it.** In resizes-visual mode a focused field that starts behind the keyboard makes Android pan the visual viewport down to reveal it: the pinned `#cjkInput` sits at the bottom of the layout viewport, and Chrome panned 285px with a 458px visual viewport in a 744px layout one. `.app` is sized to the visual viewport (`--app-height`) but laid out at the top of the layout viewport, so that pan left only the terminal's last line on screen. On phones `updateLayoutForKeyboard()` therefore sets `.app`'s `translateY` to `visualViewport.offsetTop` while the keyboard is up, whatever has focus (no pan, the usual case, moves nothing), and clears it on every other branch and in `resetLayout()`. ⚠️ The transform makes `.app` the box its `position: fixed` children are placed against (header, `.toolbar`, the accessory bar, which is inserted before the toolbar, `#cjkInput`, and the phone case sheet, `#mobileCasePickerModal`), so their lift is measured from `.app`'s bottom (`insideLift`), not the layout viewport's: lifting them by the layout gap as well floated them above the keyboard on a partial pan. Separately, `KeyboardHandler.isInputElement()` skips `#cjkInput` like xterm's inputs, because the focusin `scrollIntoView({ block: 'center' })` centred the fixed field in its ancestors and pushed the terminal off screen. Pinned by `test/keyboard-handler-pinned-field.test.ts`.
**The hinge is a reserved region, and the CSS is inert by construction.** The CSS Viewport Segments media features report two segments only while a foldable is actually bent; `--fold-inline-end` / `--fold-block-end` (end of styles.css) measure the strip to keep clear from the LEADING segment (`env(viewport-segment-right 0 0)` and `env(viewport-segment-bottom 0 0)`, physical sides in every text direction) and are `0px` on everything else. The seven centred overlays are all `position: fixed; inset: 0` flex boxes; each shrinks its CONTENT box with padding rather than the box itself, so the backdrop still covers the far side of the fold and still swallows taps there. The cascade traps, each measured in headless Chromium against styles.css + mobile.css in index.html link order: (1) a later `padding-right` longhand beats the earlier `padding` shorthand it composes with, so each fold rule re-states the overlay's own gutter; (2) a base gutter that a LATER `@media` block overrides needs its own fold restatement in that block on a ZERO base, since the unconditional rules at the end of the file otherwise put the gutter back (the phone path picker and path preview drop to `padding: 0` under 600px and came back at 16px and 18px on every phone); (3) a compound rule written to outrank a mobile.css shorthand must be scoped to the band where that shorthand applies, because outside it there is no gutter to compose with (the palette's `.modal.command-palette-modal` added 0.75rem at 393, 900 and 1400px and pushed the shell 6px off centre, and inside the band it lost its bottom gutter to the shorthand until it restated that side too); (4) mobile.css loads AFTER styles.css, so a same-specificity rule there wins under its own breakpoint (the response viewer's `max-height: 92dvh` under 600px beat the tabletop cap, which now has a twin at the end of mobile.css). `test/foldable-layout.test.ts` DERIVES the overlay list from the stylesheet, simulates the cascade across both files at every breakpoint with and without the fold rules, and requires the two results to differ by exactly the fold strip, so each of the four fails there instead of on hardware nobody has.
@@ -1207,7 +1241,7 @@ Tests: `test/terminal-touch-tap.test.ts`, `test/session-swipe-gesture.test.ts` (
⚠️ **The boxes ARE a DOM grouping**, unlike by state, which is safe only because a tab changes case far less often than it changes state: `_tabClusterLayout().key` is the whole structure, and the incremental path rebuilds whenever it differs from the last full render's. The keyboard walk keeps boxes together (box index first, then computed order, since a sorted rail orders rows inside each box). Drag only reorders inside one box, as it only reorders inside one state group (`_isTabDropAcrossGroups()`).
**Ledger.** CSS only, on `.tabs-ledger` inside `@media (min-width: 768px)` and the header host: the flat list on an auto-fill column grid with equal cells, mono type and a 3px status bar (`--ledger-bar`: yellow for a waiting alert, red for an action alert or an error, muted for stopped, exited and web tabs) instead of the dot. ⚠️ It must not change the markup (pinned: the ledger's innerHTML equals classic's); the rail, the sidebar and narrower strips show the plain list.
**Ledger.** CSS only, on `.tabs-ledger` inside `@media (min-width: 768px)` and the header host: the flat list on an auto-fill column grid with equal cells, mono type and a 3px status bar (`--ledger-bar`: yellow for a waiting alert, red for an action alert or an error, muted for stopped, exited and web tabs) instead of the dot. ⚠️ A WORKING cell keeps the dot (`.tab-status:not(.busy)` is what is hidden): the bar is green for idle and working alike, and the spinner is the dot's own `.tab-status.busy::after` ring, so hiding every dot left a busy session with no mark (pinned by `test/tab-clusters.test.ts`); an exited agent's cell hides it, as the classic strip hides the ring there. ⚠️ It must not change the markup (pinned: the ledger's innerHTML equals classic's); the rail, the sidebar and narrower strips show the plain list.
**Classic, wrapped: the L-shaped strip.** Once a classic desktop strip in the header host wraps (`tabs-auto-wrap`, or the manual `tabs-two-rows`), `_syncTabStripCorner()` (app.js) adds `.tabs-corner`: `#headerRight` goes `position: absolute` over the strip's top-right corner and the strip runs the header's full width, so only the row(s) beside the toolbar stop short of it and every later row uses the width under it. A flex line cannot be shortened on its own, so in that state the strip is `display: block` with `inline-flex` tabs flowing around a `::before` float sized from the toolbar's box (`--tab-corner-width` / `--tab-corner-height`); the old `row-gap` (lineage's `--lineage-row-gap` included) becomes the tabs' bottom margin and the bottom padding shrinks by the same amount, so row spacing and lineage routing room are unchanged. ⚠️ `updateTabOverflowMode()` removes `.tabs-corner` BEFORE it measures the wrap (the corner takes the toolbar out of the header's flow, which widens the strip), so the wrap is still judged against the one-row layout and an unwrapped strip looks exactly as before. ⚠️ Flex-only rules do not apply to the strip in that state. ⚠️ A strip that already scrolls (past `--tab-strip-max-height`) keeps the plain wrap, checked on the plain strip before the class goes on: the float scrolls with the tabs while the toolbar stays put, and toggling the class on a scrolled strip lets scroll anchoring move it; a strip pushed past the max-height by the float itself falls back too. A first tab too wide for the room beside the toolbar (the whole first line would drop below it) is trimmed to the room instead (`tab-corner-fit`, `max-width: var(--tab-corner-first-max)`, its name ellipsized): a selected tab is wider (gear and close show), so a fallback here made the whole layout follow the selection. Only a room under `TAB_CORNER_MIN_FIRST_TAB` keeps the plain wrap. ⚠️ The cap goes on the first tab on every pass, never only once it measures too wide: `selectSession()` widens a newly selected tab at once and this sync is debounced, so a cap set afterwards leaves the first row below the toolbar until it runs. It changes nothing on a tab narrower than the room. A `ResizeObserver` on the toolbar re-decides wrap and corner and redraws the connection lines when a reading or the header divider resizes it without a tab render. Scope: classic arrangement, desktop, header host only; state/case/ledger, the sidebar and the vertical rail never get the class (`applySessionListLayout()` drops it when the strip moves). Tests: `test/tab-strip-corner.browser.test.ts` (browser suite).
@@ -1269,7 +1303,7 @@ The age stamps are refreshed **in place** by a 20s clock (`_tickHomeSessionsTime
⚠️ It must disarm on ALL of: use, second tap, any other accessory key, session switch, keyboard dismissal, and a layout swap; a modifier left armed turns the next innocent keystroke into a control byte.
⚠️ **onData is not the only input path** — with `cjkInputEnabled` on, the CJK textarea owns the keyboard (onData returns early for everything it swallows, and the focus router sends `terminal.focus()` there, which is where the bar refocuses after every key), so `_handleCjkInput()` applies the modifier too. It is that module's single choke point to the PTY, so one call covers typed characters, IME flushes, Enter, backspace and arrows. Without it an armed modifier could neither fire NOR be spent, and survived to a later keystroke.
⚠️ **onData is not the only input path** — with `cjkInputEnabled` on, the CJK textarea owns the keyboard (onData returns early for everything it swallows, and the focus router sends `terminal.focus()` there, which is where the bar refocuses after every key), so `_handleCjkInput()` applies the modifier too. It is that module's single choke point to the PTY in live mode, so one call covers typed characters, IME flushes, Enter, backspace and arrows; in Send on Enter a held answer leaves through `_sendCjkPrompt()` instead, which spends the modifier, while an armed next character still goes through `_handleCjkInput()`. Without it an armed modifier could neither fire NOR be spent, and survived to a later keystroke.
Mapping is `ctrlByteFor()` (`code & 0x1f` over @A-Z[\]^_ and a-z, plus Ctrl+Space=NUL / Ctrl+?=DEL); characters with no control equivalent pass through unchanged, like a hardware keyboard.
@@ -1281,7 +1315,7 @@ Mapping is `ctrlByteFor()` (`code & 0x1f` over @A-Z[\]^_ and a-z, plus Ctrl+Spac
⚠️ **Drafts are per-session and in memory only** (`_composerDrafts`, never persisted: prompts routinely carry secrets, and persisting them would need the 0600 treatment the intent store gets). Every non-Send exit (Cancel, backdrop, Escape, "Use terminal keyboard") leaves the taken text ONLY in the draft, with the dot on the key (`has-draft`, kept in step by `_syncComposerDraftIndicator`) as the signal that the terminal prompt is empty on purpose, and `_cleanupSessionData` discards the draft with the session.
⚠️ **Delivery is a hand-built bracketed-paste frame** (`\x1b[200~` + the text with newlines mapped to `\r` + `\x1b[201~`, byte-identical to what `terminal.paste()` would emit) through `_sendInputAsync` WITHOUT `{ useMux: true }`, plus a SEPARATE Enter 120 ms later WITH it (codex drops keys that share a PTY read with a bracketed paste). Not `terminal.paste()`, for two reasons: xterm's `bracketedPasteMode` mirror is false for every session after a tab switch or reload (`terminal.reset()` in the replay re-clones the DEC modes, the tmux capture carries no `?2004h`, and tmux never forwards the pane's DECSET to a client after attach), so a paste through xterm would go out unbracketed and the CLI would submit at the first `\r`; and xterm's onData is where the local-echo paste branch flushes pending overlay text AHEAD of the block, text the composer has already taken and erased from the PTY, so the frame goes straight to the wire with the composer as the prompt's only owner. The unconditional frame is safe for a CLI that never enabled DECSET 2004 because tmux does the gating (measured against a live pane: markers stripped for a `cat -v` pane, forwarded intact to a process that had emitted `?2004h`).
⚠️ **Delivery is a hand-built bracketed-paste frame** (`\x1b[200~` + the text with newlines mapped to `\r` + `\x1b[201~`, byte-identical to what `terminal.paste()` would emit) enqueued on the session FIFO (`_enqueueInput`, `_sendBracketedPaste()`) WITHOUT `{ useMux: true }`, then a 120 ms `gap` and a SEPARATE Enter WITH it, all reserved for the composer's session at Send (codex drops keys that share a PTY read with a bracketed paste). Not `terminal.paste()`, for two reasons: xterm's `bracketedPasteMode` mirror is false for every session after a tab switch or reload (`terminal.reset()` in the replay re-clones the DEC modes, the tmux capture carries no `?2004h`, and tmux never forwards the pane's DECSET to a client after attach), so a paste through xterm would go out unbracketed and the CLI would submit at the first `\r`; and xterm's onData is where the local-echo paste branch flushes pending overlay text AHEAD of the block, text the composer has already taken and erased from the PTY, so the frame goes straight to the wire with the composer as the prompt's only owner. The unconditional frame is safe for a CLI that never enabled DECSET 2004 because tmux does the gating (measured against a live pane: markers stripped for a `cat -v` pane, forwarded intact to a process that had emitted `?2004h`).
⚠️ The frame must never take the mux fallback: `TmuxManager.sendInput()` strips every `\r`, the frame's line separator, so the lines weld into one, pasted inside a second pair of markers, and get submitted.
@@ -1299,6 +1333,8 @@ Tests: `test/mobile-prompt-composer.test.ts` (in the CI gate, deliberately not u
**(2)** In `_handleMobileTerminalTap`, a second tap on **inert `content`** (`startedWithTerminalFocus`) blurs instead of re-focusing. ⚠️ Scoped to `content` on purpose: the prompt row (`input`) keeps focus-then-position so a second tap still places the caret, and actionable rows blur earlier via `_isActionableMobileTerminalTap`.
⚠️ **The pinned CJK field keeps its focus through a swipe.** `initTerminal`'s touchstart blurs the focused input on `content` before the gesture is known to be a tap or a scroll. For xterm's helper textarea that blur, with the `preventDefault` beside it, is what keeps the compatibility click from opening the keyboard. The visible `#cjkInput` owns the keyboard instead, so `_contentTouchStartBlurs()` leaves it focused; blurring it closed the keyboard on every swipe that started on the live screen. A real tap still closes it: inert content through (2), a link in `_handleMobileTerminalTap`'s link branch (which blurs because touchstart did not), a long press in `_beginTouchSelection`. A sideways session swipe keeps it open, since the field's draft is per session. Pinned by `test/terminal-touch-tap.test.ts`.
⚠️ **A scroll ends in `touchend` too** — dismissing there closes the keyboard and drops the composer mid-read, so travel is tracked from `touchstart` and multi-touch is never a tap. Both classifiers MUST share one threshold: `initTerminal`'s `TAP_THRESHOLD` reads `MOBILE_KEYBOARD_DISMISS_TAP_SLOP`, since a gesture the terminal calls a scroll and the dismiss handler calls a tap is exactly that bug.
⚠️ **An accessory key that keeps the keyboard up must not take focus on the press.** The keys that act on the terminal and leave the keyboard open (`ACCESSORY_REFOCUS_ACTIONS` in keyboard-accessory.js: scroll, arrows, Tab, Shift+Tab, Ctrl, Esc, clear input and the rest) cancel the `mousedown` default, the same pattern as the Attach input, so the hidden textarea keeps focus through the press; the `terminal.focus()` in the click handler stays as the fallback. Letting the tap blur the terminal and refocusing it afterwards made every such key start a keyboard dismissal, a blur/focus pair per tap that shifted the toolbar each time. A first tap on clear/compact only arms the confirm and is treated the same; the confirming tap, and keys that open a dialog or dismiss the keyboard on purpose, keep the default. Pinned against the real module by `test/accessory-keeps-terminal-focus.test.ts`.
@@ -1353,7 +1389,7 @@ Tests: `test/mobile-prompt-composer.test.ts` (in the CI gate, deliberately not u
| **CSRF / Origin** | Always-on cross-site Origin guard rejects state-changing requests from foreign origins (covers self-update, session create/input, settings/tunnel toggles). **A missing Origin is allowed** so curl/CLI and Claude Code hooks keep working. The global body parser keeps `text/plain` RAW (no auto-JSON-parse, which had enabled simple-request CSRF); `/api/crash-diag` self-parses. WebSocket upgrade validates Origin+Host (anti-CSWSH) in `ws-routes.ts`. Added in `c669518` (closes 2026-06-09 review CRITICALs) |
| **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 logins/IP → 429 (15min decay). Multi-user mode instead has two gates checked before scrypt, so past either even a correct password from that IP gets 429: 50/IP (`AUTH_IP_FAILURE_MAX`) and 10 per (username, IP) (`AUTH_FAILURE_MAX`; the same account still logs in from another IP). A 10-per-username bucket (multi-user only) is checked after the verify: 429 to failed guesses from the 10th on, from any IP, never to a correct password. QR has separate limiter |
| **Rate limit** | 10 failed logins/IP → 429 (15min decay). Multi-user mode instead has two gates checked before scrypt, so past either even a correct password from that IP gets 429: 50/IP (`AUTH_IP_FAILURE_MAX`) and 10 per (username, IP) (`AUTH_FAILURE_MAX`; the same account still logs in from another IP). A 10-per-username bucket (multi-user only) is checked after the verify: 429 to failed guesses from the 10th on, 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, since a 429 never re-prompts a browser; a malformed one is counted. QR has separate limiter |
| **Hook bypass** | `/api/hook-event` (and `/api/status-telemetry`, the statusLine exporter) skip Basic auth (localhost-only, schema-validated). When auth is active (`CODEMAN_PASSWORD` set), the loopback bypass requires the per-instance `X-Codeman-Hook-Secret` header **unconditionally** — COD-54 introduced it tunnel-gated; COD-91 (PR #127) made it always-on because Codeman can't detect a user's own loopback reverse proxy (own cloudflared/`tailscale serve`/nginx → 127.0.0.1), closing that residual plain-bypass gap. Hook curls cat the secret file at exec time via `$CODEMAN_HOOK_SECRET_FILE` (session env, `config/hook-secret.ts`); a missing/wrong secret gets 401 and rate-limits in a dedicated bucket (never locks out login). Tunnel enable **refuses** without a login (`CODEMAN_PASSWORD` or multi-user mode) unless exposure is acknowledged — via `CODEMAN_ALLOW_UNAUTHENTICATED_TUNNEL=1` / `--allow-unauthenticated-tunnel` (#706; until then the guard took `CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK=1`, COD-55, which `install.sh` writes for every passwordless LAN install, so the bind acknowledgement silently published the tunnel too) **or** the per-request `acknowledgeUnauthTunnel:true` action field (1.1.9). With no login the browser asks BEFORE every enable (welcome link, tunnel panel, an App Settings save that turns it on) through `_confirmTunnelEnable()`, reading `loginConfigured` from `GET /api/tunnel/status`, and on confirm sends that flag; the 403 handler stays the fallback when the status read fails (server logs a loud warning on every passwordless tunnel start; curl/API stay refused without password/env/flag). The flag is an action field, never persisted |
| **Env vars** | `CODEMAN_MUX` (managed session), `CODEMAN_API_URL` (auto-set for hooks), `CODEMAN_ALLOWED_HOSTS` (extra Host/Origin allowlist entries for reverse proxies, comma-separated; bare `.suffix` matches subdomains), `CODEMAN_DOCKER_BRIDGE_HOOKS`=1 (opt-in hooks-only listener on the docker bridge gateway so in-container hooks reach a loopback-bound server; bind IP from `CODEMAN_DOCKER_BRIDGE_HOST` or auto-detect) |
| **Validation** | Zod schemas, Unicode-aware path allowlist regex, env prefix allowlist (`CLAUDE_CODE_*`/`OPENCODE_*`/`CODEX_*`/`GEMINI_*`/`GOOGLE_*`/`ANTIGRAVITY_*`/`PI_*`) |
@@ -1379,6 +1415,8 @@ Target: 20 sessions, 50 agent windows at 60fps. Limits in `src/config/`: termina
⚠️ Truncation is reported through `onTruncated` rather than silently, with BOTH caps named: a silent depth cap hides a deep tree exactly as effectively as a silent node cap hides a wide one.
⚠️ **A kill never takes pid 0 or 1** (2026-11-25). A bound limits how MUCH a walk collects, not what it is a walk of: the children of pid 0 are init and everything below it, so `killSession()` with pid 0 signalled every process of the account, which took down every session, tmux itself and the systemd user manager (the machine did not reboot, and with the manager gone the server did not come back until the next login). It was reached by a script that drove the real `killSession()` on an empty pane lookup (`Number('')` is 0), but it needs no script. tmux answers `0` for `#{pane_pid}` of a pane without a process (`split-window ''`; measured on 3.4), `parsePaneRows()` keeps that row, and `reconcileSessions()` at server start writes it to `session.pid`, where the last pane of a session wins. The next close read 0 from tmux, fell back to the record, found 0 there too, and walked it. Reproduced on master with the signals logged instead of sent, inside a PID namespace: "Killing session codeman-feed1234 (PID 0)", "Found 15 child processes to kill". So 0 is an ordinary answer and means "nothing to signal". Three layers, all pinned in `test/kill-pid-guard.test.ts`: `killSession()` decides once (`isSignalablePid()`, an integer above 1) and otherwise leaves the close to `tmux kill-session`; `getChildPidsFresh()` walks nothing for such a root; and `signalProcess()`, the only place in `tmux-manager.ts` that sends a signal, refuses it for the group form as well (`kill(-1)` is every process, `kill(0)` is our own group). `collectDescendants()` itself stays a plain walk. A recorded 0 is deliberately left on the record rather than replaced by the older pid: that pid belongs to a process that may have exited since and been reused.
## Local packages and build artifacts
### xterm-zerolag-input is single-source
@@ -1417,7 +1455,7 @@ Tests that delete case trees go through `safeRmHomeTree()` (`test/mocks`), which
**`install.sh`** (repo root) is the public entry point: `curl -fsSL <raw url> | bash` installs Node/tmux/git/build tools if missing, clones to `~/.codeman/app`, builds, and offers a systemd/launchd service. Since installer v2 (2026-09-20) it is **look, ask, work, done**: `preflight_detect` prints what is on the machine, every human step runs BEFORE the build (one consent for all missing packages, ONE sudo prompt kept warm by `sudo_session_start`, the AI CLI menu, the Tailscale login/operator/HTTPS-toggle preflight), then the clone/`npm install`/build/service/serve run unattended behind `run_step` spinners (output in `~/.codeman/install.log`, tail shown on failure), and `print_done_screen` ends on the URL with a terminal QR code (the `qrcode` package Codeman already ships). Design + verification record: `docs/installer-v2-plan.md`.
The network-access question is 3-way: **Tailscale** (loopback bind + `tailscale serve`, curl-verified end-to-end), **LAN** (0.0.0.0 + password prompt), or **local-only**; it preserves the existing binding on re-runs via `read_existing_binding()`, which also reads back `CODEMAN_BASE_URL`/`CODEMAN_PORT` from the unit, and the flag/env PRESET paths keep an existing password too (`${CODEMAN_PASSWORD:-$EXISTING_PASSWORD}`: `--lan --service` on a password-protected unit used to rewrite it open with the unauthenticated ack, found in review 2026-09-21); `--password`/`--port` flip `RECONFIGURE` so they reach the unit instead of taking the quiet update path.
The network-access question is 3-way: **Tailscale** (loopback bind + `tailscale serve`, curl-verified end-to-end), **LAN** (0.0.0.0 + password prompt), or **local-only**; it preserves the existing binding on re-runs via `read_existing_binding()`, which also reads back `CODEMAN_BASE_URL`/`CODEMAN_PORT` and `CODEMAN_MULTIUSER` from the unit (both setup functions write a set `CODEMAN_MULTIUSER=1` back; systemd `Environment=` lines go through `read_systemd_environment()`, which unquotes the way systemd does, so a hand-written `KEY="value"` reads as `value`), and the flag/env PRESET paths keep an existing password too (`${CODEMAN_PASSWORD:-$EXISTING_PASSWORD}`: `--lan --service` on a password-protected unit used to rewrite it open with the unauthenticated ack, found in review 2026-09-21); `--password`/`--port` flip `RECONFIGURE` so they reach the unit instead of taking the quiet update path.
⚠️ The env a hand-started `codeman web` needs (host, password, ack, base URL, port) is composed in ONE place, `start_command_hint` for the done screen's Start line and `export_bind_env` for main()'s `exec` branch, so the two cannot disagree; `stop_background_helpers` runs right before that `exec`, because exec skips the EXIT trap and the sudo keepalive (keyed on `$$`, which becomes the server's pid) would otherwise refresh the sudo timestamp for the server's whole life. Ctrl+C in the HTTPS-toggle poll is trapped for the poll only and skips Tailscale for the run rather than killing the installer.
@@ -1549,3 +1587,7 @@ updates `lastSubmitAt` just like any other Enter.
- **Files.** Received files come only from Discord's HTTPS hosts into `<tab folder>/.codeman-discord/` (bounded probe, refused if a symlink, self-ignoring). A sent file's real path must lie inside the tab's folder; both the folder and the file are probed with the bounded probe first.
- **The whole last message.** A finished turn or an error posts the CLI's whole last message, not the screen: `WebServer.lastResponseFor` is the response viewer's reader (the body of `GET /api/sessions/:id/last-response`, registered on the route context by `registerSessionRoutes`), so the source is the same per-CLI transcript, or the pane split into turns where a CLI keeps none; a dialog and a shell keep the screen tail (its composer row and the status lines under it cut, never a `❯ 1.` option row). The read is bounded to 4 s and any failure or empty read falls back to the screen. It is split into at most 8 posts of 1,900 characters, a cut code fence closed and reopened, and Markdown tables become aligned code blocks (the separator test strips whitespace first: a regex over a run of spaces is quadratic, and the text is steerable by whatever the agent read). The repeat check is keyed on the text plus the turn it came from (the transcript stamp, else the last submit) and is recorded only after the first post succeeds, so a failed post is sent again and a later turn ending on the same words is not dropped. Only some CLIs raise a turn end (`/api/hook-event`: Claude's `stop` and `idle_prompt`, DeepSeek's `stop`), so the others reach this path through errors, a blocked respawn or a crash loop.
- **Cost guards.** The alert tail is a function called only once a post will happen (no tmux exec while off), and `discord-notify` is a per-session token bucket (6 a minute, `429 RATE_LIMITED`).
### Discord reply replay metadata
`discord-reply-dedupe.json` is a private 0600 data-directory file containing at most 2,048 reply IDs and timestamps retained for seven days. An allowed reply is claimed by message ID before rate-limit or exited-agent checks, attachments, or terminal input. Store failures log once and fall back to memory; they never cost a reply. An unreadable or unsafe file is never overwritten, and reads retry later. Invalid or oversized regular-file ID-only content warns and heals on the next write. Recovery keeps older disk rows before newer outage claims so bounded eviction drops the oldest IDs first. Ambiguous terminal input is never replayed automatically.
+5 -1
View File
@@ -300,7 +300,7 @@ This matters because it is invisible when it is wrong. `capabilities.privilegedP
## Fields declared for later
`accent`, `capabilities.echo`, `capabilities.wheelForward`, `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.) 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.
`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.
Treat those values as **transcribed, not authoritative** — nothing enforces that `echo.policy` matches `_updateLocalEchoState`'s fallthrough, so re-measure before wiring one up. `accent` is the one exception: it was measured against styles.css on 2026-09-21 (method in the comment above `CLAUDE` in `stock.ts`), though nothing keeps it in step with the CSS either. A field that is both wrong and unread is worse than an absent one, because the next reader trusts it; `test/cli-registry-no-id-branching.test.ts` pins the list so it cannot quietly grow, and wiring one up makes its line there fail, which is the direction you want.
@@ -308,6 +308,10 @@ Treat those values as **transcribed, not authoritative** — nothing enforces th
Everything else in the interface is live, including `overlays.remote` / `overlays.docker`, which back `defaultRemoteCommandForMode()` and `defaultDockerCommandForMode()` directly. Those two used to be hardcoded `Record<…CommandMode, string>` tables duplicating the registry with nothing keeping the two in step; `test/location-overlay-commands.test.ts` pins every resulting command as a literal string.
### Wheel forwarding for a custom full-screen CLI
`capabilities.wheelForward` reaches the browser as `window.__codemanWheelForward` (id to rule, every CLI whose mode is not `never`, disabled ones included, since disabling a CLI leaves its running sessions open), and `_shouldForwardWheelToApp` in terminal-ui.js reads only that map, so a custom entry gets the same wheel as a stock one under its own id. A full-screen TUI that turns mouse tracking on itself (a wrapper around pi, for example) needs two values in its `clis.json` entry, the ones stock pi carries: `"altScreen": "strip-mux-and-mouse"` (the server strips its mouse DECSETs and publishes `cliMouseTracking`, and a drag selects locally) and `"wheelForward": { "mode": "always" }` (the wheel goes to the CLI as SGR reports while that flag is on). With the custom-entry defaults (`strip-mux-only`, `never`) the DECSETs reach xterm, which handles the wheel only until a tab switch or reload replays the pane without them; from then on the wheel scrolls an empty local buffer. Use `always` rather than `version-gated` for such an entry: a `version-gated` rule forwards only when the session has a `cliVersion`, and the server probes one only for an entry that declares `capabilities.gates` (`cliNeedsVersionProbe` in `session.ts`), so a custom entry with `version-gated` and no gates never forwards, and nothing says why. ⚠️ Saving the entry from the Settings form rebuilds its capabilities from those defaults, so both values have to be set again in the file after an edit there.
## Consumers outside the server
Two things need the catalogue but cannot import TypeScript, so `npm run generate:cli-catalog`
+33
View File
@@ -288,6 +288,39 @@ dsh fences its `/api` behind a browser-trust check on the request authority, and
Codeman web tab reaches it through Codeman's own origin via the webview proxy, not
directly. Without it the page renders and every API call fails.
Since dsh's browser-auth gate, the index is not public either: boot prints
`dsh web: http://127.0.0.1:<port>/?token=<one-time token>` and only a request
carrying that token is answered with the `dsh-auth-*` cookie that authorizes
everything after it. The saved tab deliberately keeps the clean URL, so the
browser can never present that token, and the tab used to open on dsh's 401 page.
`src/deepseek-web-server.ts` now reads the token out of the captured boot output,
trades it for the cookie once at startup, and `webview-routes.ts` presents that
cookie on both the HTTP and WebSocket legs — scoped to the exact loopback
authority it was minted for, so a repointed or stale tab cannot carry it
elsewhere. The reader scans every `dsh web:` line (dsh prints diagnostics such as
`dsh web: loading profiles` under the same prefix before the banner) and only
complete lines, so a banner split across two output chunks is waited for rather
than parsed truncated. Before the token URL is fetched it must name `127.0.0.1`
on the port the supervisor just spawned, so a banner cannot aim the server-side
request at another host or local service. A dsh without the gate prints a
token-less banner and keeps working unchanged. If a token is printed but the
exchange still fails, the server keeps running (its page serves, just 401) and is
marked unusable for reuse: the next start request stops and respawns it, which is
the "restart `dsh web`" the warning asks the user to perform.
The cookie is also bound to a person, not to a URL. `managed` is accepted from the
client on `POST/PATCH /api/webviews` and `GET /api/deepseek/web` publishes the live
port, so a saved record pointing at that port is not an entitlement by itself: the
proxy presents the cookie only when the tab's owner holds the same
privileged-commands grant `POST /api/deepseek/web` requires, and in multi-user mode
only to the owner whose request started that process. A different owner's start
request restarts the server rather than reusing a cookie that is not theirs, which
is why the shared instance is effectively single-user at a time. On a trusted
managed tab the cookie is sent ahead of whatever cookies dsh itself set in the
browser, rather than replacing them; leading matters because a `Cookie` header can
name the same cookie twice and the first value is the one the dashboard parses, so
a stale browser copy must not shadow the one the running process minted.
## 7. Docker and remote cases
Docker cases work: the agent image installs `dsh` and bootstraps a `dsh-tui`
+6
View File
@@ -135,3 +135,9 @@ The text explains `codeman notify "message" --urgent`. `codeman` is on the PATH
| Posts arrive but replies do nothing | Message Content Intent is off, or your user ID is not in the allowlist |
| Thread is not deleted | The bot lacks Manage Threads on the parent channel |
| Nothing arrives on the phone | Check the Discord app's notification setting for the server |
## Reply replay protection
The bridge remembers up to 2,048 recent Discord reply IDs for seven days in the private `discord-reply-dedupe.json` metadata file. It claims an allowed reply before rate-limit or exited-agent checks, downloading attachments, or typing into its session, so a gateway replay normally cannot type it twice, including after a restart. The file contains IDs and timestamps only, with mode 0600.
This is best-effort replay protection, not an exactly-once guarantee. A full disk, unreadable file, or invalid metadata logs one content-free warning and falls back to in-memory checks. Invalid or oversized regular-file ID metadata is replaced on the next write. Files that could not be read are left untouched. Reads and writes retry on later replies; a restart during a metadata outage can lose those checks. At capacity the oldest entries are evicted, so capacity never blocks new replies. Notifications retain their existing delivery and retry behavior; this store never suppresses an outbound alert or replays terminal input.
+27
View File
@@ -0,0 +1,27 @@
# iOS keyboard ownership (#830)
On iOS WebKit touch devices, `terminal-ios-native-input.js` owns the terminal's native textarea. Its support check shares `MobileImePreview.isIosWebKitTouch`; it loads after the preview and before the primary terminal and tile hosts. These hosts do not also install keyCode-229 recovery on iOS. Other coarse-pointer devices retain that recovery.
The native field retains the editable line, including dictation hypotheses and native newlines. Reconciliation emits shell-safe transactions rather than forwarding each browser event. A dictated line break must never send CR or LF. Trackpad movement changes only the visual caret; it sends no terminal arrows, never focuses the field and never changes its selection.
The owner exposes `caret(): { visible, text, offset, generation }`, with projected text and a UTF-16 offset into that projection (CRLF and LF each become one space). `generation` advances only when an edit is reconciled (sent) or the line is reset; a clipboard snapshot borrowing the field and its restoration leave it unchanged. The marker has two authoritative positioning modes:
- **Local echo:** the field must be an exact suffix of the overlay's last displayed `committedText`. The marker queries `getInputAnchor(base + offset)` for the painted cell, including wide-character wraps. A mismatch or unavailable/clipped layout hides it.
- **Parsed buffer:** with echo off, passthrough, tiles or Pane B, the marker matches the full native text backwards from xterm's cursor, crossing only soft wraps. It skips wide-glyph continuation cells and validated empty wrap padding, then maps the offset to an actual buffer cell. A mismatch, an identical preceding repetition, an offset inside a combined cell (such as a combining mark or ZWJ cluster), or an offscreen row hides it. When `generation` changes it also hides until xterm parses its next write. That wait is a heuristic, not a delivery acknowledgement: any parsed write clears it, so if unrelated output arrives before the echo and identical text already sits before the cursor, the cells can still match the older text.
Both modes hide for an unfocused field, composition, a range selection, the end of the field, a pending/unreconciled edit, an invalidated baseline, a failed transaction sink or a borrowed clipboard snapshot. No mode estimates the caret by subtracting a text width from an end anchor.
Programmatic input calls `_prepareExternalInput` on the captured pane before sending. Toolbar Enter calls `submitFromToolbar()`. The per-session FIFO reserves pending local-echo text, an 80ms gap, and CR together, so switching sessions cannot redirect CR or let later edits overtake it. This is enqueue ordering, not an acknowledgement-completion fence. Logical ACK fences, tagged HTTP success semantics, HTTP/WebSocket handover gating and `/send-key` ACK fencing are outside this fix.
## Browser regression suite
```sh
node scripts/prepare-test-vendor.mjs
npm run test:browser -- test/ios-native-input.browser.test.ts
```
The browser runner also prepares the source-served vendor overlay through `pretest:browser`. `src/web/public/vendor/` is gitignored; source vendor is generated, not tracked. Production builds independently regenerate the overlay from `packages/xterm-zerolag-input` and content-hash it. The overlay must include `getInputAnchor` and `committedText` before running these tests.
The suite serves the real application with Chromium, an iPhone user agent, touch points and a coarse pointer. It observes `_enqueueReliableInput` without replacing `_sendInputAsync`, and reuses the phone-validated WebKit replay defaults. Assertions cover suggestion op boundaries, phrase replacement, held delete, dictation newline suppression, toolbar submission and subsequent suggestions, old-session CR ownership during the gap, trusted CDP paste, caret geometry in both echo modes, emoji deletion, tile session ownership and non-iOS recovery.
These are browser wiring tests, not a substitute for device replay. The logged iPhone event sequences they replay are in [#830](https://github.com/Ark0N/Codeman/issues/830).
+1 -1
View File
@@ -579,7 +579,7 @@ step 1 is a real step). Before shipping:
browser, confirm the reply renders and scrollback survives a tab switch. Do not touch
`w1`/`w2`/`w3`.
4. **Local-echo policy gate (§2.10):** on a phone profile, type into the pi editor through the
buffer overlay (drive with `page.keyboard.type()`, never `app.sendInput()`, and force
buffer overlay (drive with `page.keyboard.type()`, never `app._sendInputAsync()`, and force
`app._localEchoEnabled = true`; headless Chromium reports touch as false) and confirm pi's
composer renders the flushed text correctly on Enter. If it mis-renders, flip pi to the `'off'`
branch in `_updateLocalEchoState` and pin that instead.
+1 -1
View File
@@ -75,7 +75,7 @@ Both transports refuse a frame longer than `MAX_INPUT_LENGTH` (64 KiB,
at the head of the queue, was re-sent every 2 s forever, blocked every later
input for the session, and came back from localStorage on each reload.
- `_sendInputAsync()` splits a paste over the frame limit into in-limit frames
- `_enqueueReliableInput()` (the session FIFO's transport edge) splits a paste over the frame limit into in-limit frames
(`CodemanInputLimit.split`, constants.js, never cutting a surrogate pair). They
go out in seq order, so the PTY sees one contiguous stream. A paste over
`PASTE_MAX_CHARS` (1 MiB), or an oversized `useMux` write (one paste plus its own Enter, never
+15 -5
View File
@@ -138,9 +138,18 @@ loopback bind matters. The auth pipeline (`src/web/middleware/auth.ts`,
allow.
3. **HTTP Basic** check — correct credentials short‑circuit to allow and clear
that IP's failure counter.
4. **Rate‑limit gate** — if neither cookie nor credentials passed and the IP is
locked out, return `429` with a `Retry-After` header.
5. Otherwise return `401`, incrementing the IP's failure counter.
4. **No `Authorization` header** — return `401` with the `WWW-Authenticate`
challenge, **without counting it** and even while the IP is locked out (both
modes; in multi-user mode this comes before the pre-verify gates and the
verify, which a missing header could never pass). Such a request is no guess
and runs no password check. Counting it let an open tab's background requests
after a restart (cookie sessions live in memory) fill the bucket in seconds,
and a `429` carries no challenge, so the browser never showed its login dialog
again.
5. **Rate‑limit gate** — if the credentials did not pass and the IP is locked
out, return `429` with a `Retry-After` header.
6. Otherwise (wrong credentials, or an `Authorization` header that is not valid
Basic) return `401`, incrementing the IP's failure counter.
### Session cookies
@@ -152,9 +161,10 @@ by presence in a server‑side map, so they cannot be forged offline.
### Rate limiting / lockout recovery
Failed logins are tracked **per IP**: 10 failures (`AUTH_FAILURE_MAX`) → `429`, with a 15‑minute decay. Multi-user mode replaces that with three buckets, all with the same decay: a wider per-IP **pre-gate** of 50 failures (`AUTH_IP_FAILURE_MAX`), checked before the scrypt verify, which bounds scrypt cost from one source and tolerates many users behind one egress IP; a **per-(username, IP)** gate of 10 failures (`AUTH_FAILURE_MAX`), also checked before the verify, which is what caps verified guesses against one account from one source; and a **per-username** bucket, checked after the verify, that answers `429` to failed guesses from the 10th on, from any IP (the count is incremented before the check). The last two exist in multi-user mode only. So the wider per-IP cap does not widen guessing against any one account from one IP, and other IPs cannot lock an account out.
The QR path has its own separate limiter.
A request with no `Authorization` header, or an empty one, is never counted (step 4), so an open
tab after a restart cannot fill any bucket. The QR path has its own separate limiter.
The lockout check sits **after** the cookie/credential checks (step 4, not first).
The lockout check sits **after** the cookie/credential checks (step 5, not first).
This is deliberate: a user with a **valid cookie or correct password recovers
immediately** even while an attacker is hammering the same IP — important because
all traffic through a tunnel shares one source IP (loopback). Wrong credentials
+25
View File
@@ -18,6 +18,7 @@ tmux rather than proxying bytes.
codeman tui # the dashboard
codeman tui --list # print the numbered session list and exit
codeman tui 2 # attach straight to session 2 of that list
codeman tui api-docs # attach straight to the live session named api-docs
```
The two fast paths are the scriptable ones.
@@ -84,6 +85,15 @@ The same world through `--list`:
The numbers are the same on both surfaces, so `codeman tui --list` then
`codeman tui 4` is one thought.
A number moves as sessions change state; a name does not. `codeman tui <name>`
attaches to the live session whose name is exactly `<name>` (case-sensitive,
never a prefix, never the folder), so the same line gets you back into the same
session from any folder or a fresh SSH login. Digits only always mean a list
number. Session names are not unique in Codeman, so when two live sessions share
the name it refuses and prints their numbers instead of guessing; a name only a
RECENT row carries says the session has finished. Both refusals are printed
before the terminal check, so a script can tell them apart without a TTY.
## The four groups
Groups are always in this order, and a session is in exactly one of them:
@@ -206,6 +216,21 @@ exactly as it was on detach, along with each window's size. Every session the st
can switch to is dressed and sized the same way, so switching is instant and lands
in a pane that already fills your terminal.
The window follows whoever used it last, as plain tmux does. If a browser tab (a
phone, say) resizes the session while you are attached, the window takes that tab's
size, and your terminal shows a smaller pane. Type, paste or resize your terminal and
the window fills it again; type in the tab, or press its Redraw, and the tab gets it
back. A tab that only opens the session at the size it already had changes nothing.
The TUI does this with one hook on each session it dressed (`client-active[91]`) and
two session options naming your terminal and the TUI process (`@codeman-tui-follow`,
`@codeman-tui-follow-pid`), and removes all three on detach. It sets nothing on a
session where you have a hook of your own at that index, or anywhere while you have
a global `client-active` hook, which a session hook would hide. A TUI that was killed
while attached (a closed window, a dropped SSH) leaves them behind; the next
`codeman tui`, including `codeman tui <n>`, removes them before it attaches. tmux
older than 3.3 has no `client-active` hook, so there the pane stays at the browser's
size until you detach and attach again.
Detaching leaves the agent running; typing `exit` or pressing `Ctrl+D` would end it,
which is the difference the bar exists to make obvious. If an agent does exit, its
pane stays as a corpse: the TUI refuses to attach to a dead pane and offers `r` to
+24 -2
View File
@@ -144,9 +144,21 @@ per-device (`localStorage`), since that is workspace layout rather than config.
Worth knowing, because it is where this feature does its least obvious work. Three
layers cooperate so a dashboard talking to its own backend just works:
1. `<base href>` handles relative URLs in the markup.
1. `<base href>` handles relative URLs in the markup. A page that ships its own
**relative** base (`<base href="./">`, what a Vite build emits) has it resolved
against the document's own directory inside the proxy prefix first, so a
document at `/webview/<cap>/app/page.html` gets `/webview/<cap>/app/` rather
than the proxy root: the page's URL is masked a few paragraphs below, a base is
resolved against that URL, so `./` would otherwise point at Codeman's root and
404 every module script behind an otherwise-painted page.
2. Attribute rewriting handles root-absolute `src`/`href`/`action` in the page the
proxy serves.
proxy serves — and root-absolute dynamic `import("/...")` specifiers inside
`<script>` bodies. The import is the one URL no other layer can reach: `<base>`
does not apply to a `/`-rooted specifier and it is not a `fetch()`. SvelteKit's
inline bootstrap is exactly this shape; without the rewrite the module loads
from Codeman's root, 404s, and the app sits on its own loading spinner forever.
Visible text is left alone: a `<pre>import("/x")</pre>` example is not a
loader and is not rewritten.
3. A small injected script rebases URLs built at **runtime**, which the first two
cannot see: `fetch('/api/data')` and `new WebSocket('/live')`, but equally
`card.innerHTML = '<img src="/api/hero">'`, `img.src = '/api/slide'`, and
@@ -190,6 +202,16 @@ then every API call fails, which looks like the dashboard being broken.
EventSource, normal markup, the DOM sinks a page uses to build markup at runtime,
and `url()` inside stylesheets. Something that constructs requests by an unusual
route can still slip through. Symptom: the page renders but a panel stays empty.
- **Root-absolute URLs the proxy never sees.** Only the HTML is rewritten, and only
literal `/`-rooted specifiers in it. Still escape: an `import()` built at runtime
(`import('/' + name)`), an import written inside an external `.js`, a static
`import x from "/x"` in an inline script, `navigator.serviceWorker.register("/sw.js")`,
and `url(/img.png)` inside an external stylesheet. They cannot be relayed either —
the masked frame's `Referer` carries no capability — so the failure is quiet: a
blank page, or a spinner that never resolves. Codeman now logs
`[Webview] <path> escaped the proxy` (once per path per five minutes) when such a
request reaches its 404, which is the fastest way to tell this class apart from a
dashboard that is genuinely broken.
- **A root-absolute `url()` inside an inline `<style>` is not rescued.** Masking the
page's URL (layer 5) trades away the `Referer` safety net of layer 4 for
requests the shim cannot see, and only HTML is rewritten server-side. An
+16
View File
@@ -67,6 +67,22 @@ below the terminal that owns composition, then delivers the composed text to the
Ctrl- and Alt-modified navigation keys typed through it reach the CLI as the modified
sequences, so word jumps and history keys keep working.
On a phone, **Input Field: Send on Enter** (beside CJK input) turns that field into a chat box:
typed text stays in it until Enter, so you can scroll the terminal back to a question and edit
your answer before sending. With a hardware keyboard, Shift+Enter adds a line (a phone's on-screen
keyboard has no Shift+Enter, and the extended bar's newline key goes to the CLI, not the field),
Esc clears the field, and autocorrect is on. Enter always goes out as its own write, a moment
after the text, to the session the answer was typed for: a single character is typed, so CLI menus
that take a digit still work, and anything longer goes like the prompt composer's Send, as one
paste. The one exception is a lone digit while a permission or question dialog is waiting: the
digit answers the dialog by itself, so no Enter follows it, which would otherwise confirm whatever
the CLI shows next. The toolbar's Enter button sends the field too. With the keyboard bar's
one-shot Ctrl armed, the next key you type goes out as a control key (Ctrl, then `c` is Ctrl+C)
instead of being held. With a hardware keyboard, Ctrl shortcuts (undo, select all, copy) act on
the field while it holds a draft and reach the CLI only when it is empty. With the keyboard down
the field stays one line tall. A draft stays with its session: switching tabs and coming back
brings it back.
## Voice dictation
`Ctrl+Shift+V`, or the microphone button. There are three providers and the default is
+38 -1
View File
@@ -190,6 +190,41 @@ and is not one.
Also make sure the proxy forwards WebSocket upgrades. The terminal is a WebSocket, and the
upgrade runs the same Host and Origin checks, closing with code `4003` on failure.
### Persist the allowlist for a systemd user service
On Linux, add the hostname to the service environment with a systemd drop-in. For the
default service, run:
```bash
systemctl --user edit codeman-web.service
```
Add this to the editable portion:
```ini
[Service]
Environment="CODEMAN_ALLOWED_HOSTS=codeman.example.com"
```
If the service already has allowed hosts, include them in the same comma-separated
value. If you already set the variable through an `EnvironmentFile=`, update that
file. For a named instance the unit is `codeman-web-<instance>.service` (for example
`codeman-web-beta.service`; `CODEMAN_INSTANCE=beta codeman service status` prints it).
Use that name in both commands.
Save the drop-in and restart Codeman:
```bash
systemctl --user restart codeman-web.service
```
Re-running the installer or `codeman service install` rewrites `codeman-web.service`
itself and does not carry `CODEMAN_ALLOWED_HOSTS` over, so keep the setting in the
drop-in (`~/.config/systemd/user/codeman-web.service.d/override.conf`), not in the unit
file. Installs, updates and `install.sh uninstall` leave that folder alone, so delete it
by hand if you remove Codeman. Open the proxy URL and attach to a terminal to check both
the page and the WebSocket connection.
### Mounting under a sub-path
By default Codeman assumes it is served at the origin root (`/`). To mount it under a
@@ -236,7 +271,8 @@ Notes and current limits:
The first request prompts for HTTP Basic credentials. On success the server issues an opaque
`codeman_session` cookie (24 hour lifetime, extended on activity, validated server-side so
it cannot be forged offline). Ten failed attempts from one IP produce a `429` with a 15
minute decay.
minute decay. A request with no credentials, such as an open tab whose cookie a restart
invalidated, is never counted and always gets the login prompt.
A valid cookie or a correct password recovers immediately even while an attacker is hammering
the same IP, which matters because all tunnel traffic arrives from one loopback address.
@@ -255,6 +291,7 @@ works well in SSH clients like Termius or Blink:
```bash
codeman tui # the dashboard
codeman tui 2 # attach straight to session 2
codeman tui api-docs # attach to the live session named api-docs
codeman tui --list # numbered list, then exit
```
+1 -1
View File
@@ -54,7 +54,7 @@ When authentication is enabled:
| ------------------- | ------------------------------------------------------------------------------------------------ |
| **HTTP Basic** | `CODEMAN_USERNAME` (default `admin`) and `CODEMAN_PASSWORD`. |
| **Session cookie** | A 256-bit opaque token validated server side, so it cannot be forged offline. 24 hours, extended on activity, with a device-context audit trail. |
| **Rate limiting** | Ten failed attempts per IP produce a `429` with a 15 minute decay. A correct password or valid cookie recovers immediately even under attack, which matters because all tunnel traffic shares one loopback address. In multi-user mode the per-IP cap is 50, and each account allows ten failed guesses from any one IP. Both are checked before the password, so past either a correct password from that IP also waits for the decay (the account still logs in from another IP, and a valid cookie keeps working). From the tenth failed guess on, an account's wrong guesses get a `429` from every IP, which never refuses a correct password. |
| **Rate limiting** | Ten failed attempts per IP produce a `429` with a 15 minute decay. A correct password or valid cookie recovers immediately even under attack, which matters because all tunnel traffic shares one loopback address. In multi-user mode the per-IP cap is 50, and each account allows ten failed guesses from any one IP. Both are checked before the password, so past either a correct password from that IP also waits for the decay (the account still logs in from another IP, and a valid cookie keeps working). From the tenth failed guess on, an account's wrong guesses get a `429` from every IP, which never refuses a correct password. A request with no credentials at all (such as an open tab after a restart) is never counted and always gets the login prompt. |
| **QR auth** | Single-use 60-second tokens with their own separate rate limiter, so a mistyped password cannot lock out QR login. |
| **Hook endpoints** | The hook and telemetry endpoints skip Basic auth because they are called from localhost by the CLI, but when auth is on, that bypass additionally requires a per-instance hook secret. |
+2
View File
@@ -48,8 +48,10 @@ non-updatable. See [Running As A Service](Running-As-A-Service).
| Local Echo | On for touch devices | Paints keystrokes locally and flushes on Enter. See [Input And Voice](Input-And-Voice). |
| Keep Size Under Keyboard | On | For local Claude sessions, the on-screen keyboard no longer resizes the session: the terminal keeps its rows and the view scrolls so the prompt sits just above the keyboard. Resizing made Claude reprint its screen and drop transcript lines from history. Codex, Claude's fullscreen mode, remote and Docker sessions resize as before. See [Mobile Guide](Mobile-Guide). |
| CJK Input | Off | IME composition through a dedicated text field. |
| Input Field: Send on Enter | Off | With CJK Input on, typed text stays in the pinned field until Enter instead of streaming to the CLI, so on a phone you can scroll the terminal and edit an answer first. With a hardware keyboard, Shift+Enter adds a line (a phone's on-screen keyboard has none). Esc clears, autocorrect is on. |
| Extended Keyboard Bar | Per device | Which accessory bar phones get. Shell sessions override it while they are active. |
| Wheel Scrolls Local History | Off | Keeps the wheel on the local buffer instead of forwarding it to the CLI. Fullscreen pi leaves that buffer empty and has no paging fallback, so with this on the wheel does nothing there. |
| History Reload Button | On (per device) | Offers **Reload history** in the history banner while you are scrolled up in a non-shell session that has had live output since its last full capture; a tap re-pulls the full tmux history and keeps your reading position. |
| Auto Copy Selection | Off | Copies highlighted terminal text to the clipboard the moment you finish selecting it. Ctrl+C still copies on demand. |
| Trim The Pane Margin On Copy | On | Takes the left margin a full-screen agent CLI paints down its own edge off a copy, so the text pastes flush. Each CLI declares its own width, and the strip never exceeds the indent every selected line shares, so nesting is kept. Claude Code and Codex declare a margin; a shell does not. |
| Normal / Bold font weight | xterm defaults | Per device, each slot from 100 to 900. The bundled JetBrains Mono renders every step, so a lighter normal weight makes Claude's bold headings stand out. Applies live to the terminal, both echo overlays and open team panes. |
+7 -3
View File
@@ -43,7 +43,7 @@ per device, so a sidebar on your desktop does not force one onto your phone.
| ---------------------- | ------------------------------------------------------------------------------------ |
| **By state** | Groups the tabs by what each session needs from you (below). |
| **By case** | One box per case, labelled with the case and its tab count. Inside a box, `w75-api-gateway` reads just `w75`. A case with one tab gets a box with a colour swatch. |
| **Ledger** | The same list on an aligned column grid: equal cells, monospace names, a coloured bar on the left of each cell instead of the dot (yellow waiting, red needs you). Desktop header only. |
| **Ledger** | The same list on an aligned column grid: equal cells, monospace names, a coloured bar on the left of each cell instead of the dot (yellow waiting, red needs you); a working session keeps its spinning ring. Desktop header only. |
| **Classic** (default) | The single list in tab order, as before. |
**By state** groups the tabs like this, most urgent on top:
@@ -243,10 +243,14 @@ Worth knowing:
reloads only the current screen, which keeps tab switches fast.
Shell sessions open from a bounded recent tail so a large transcript cannot stall tab
switching. Scrolling to the top of a Shell pane pulls the most recent 1 MiB of its tmux
history; press **Load full history** to pull the rest explicitly. That notice only
history; press **Load full history** to pull the rest explicitly. That truncation notice only
appears once you scroll to the top, leaves when you scroll back down, and stays away
for that tab once you close it. Sessions whose CLI keeps its own history (fullscreen
Claude) never show it, since there is nothing more to load. Automatic output
Claude) never show it, since there is nothing more to load. The same bar can also offer
**Reload history** while scrolled up in an agent session after new output (toggle:
Settings → Terminal & Input → History Reload Button). When a reload finds nothing more
than the browser already shows, such as fullscreen Claude whose pane keeps no tmux
history, the action is withdrawn until the next full capture. Automatic output
recovery stays within the bounded browser buffer.
- **Wheel and touch scrolling** are forwarded into Claude's own transcript when a recent
Claude runs fullscreen (`CLAUDE_CODE_NO_FLICKER=1`, or `"tui": "fullscreen"` in
+32 -8
View File
@@ -11,14 +11,38 @@ moved into ([Git Worktrees](Git-Worktrees#when-an-agent-moves-into-a-worktree)).
button is on by default on a desktop and off on a phone. The setting is per device: switch it
in **App Settings → Header & Panels** on the device you want it on.
The panel and its search list up to 5,000 files and folders per load, shallow levels first and
taking turns between folders, so one huge folder cannot use up that limit before the ones after it,
or the folders inside it, get a turn. They also stop opening folders after reading 250,000 entries,
so a workspace with several enormous folders can still leave later ones unread. When a workspace is
bigger than either limit the status line says `(truncated)`, and an expanded folder the scan did
not finish shows **Not fully scanned** rather than looking empty. A folder that does not answer,
such as a network mount that went away, is skipped rather than waited on and is marked the same way,
so a search can miss what is inside it. The panel's Refresh button tries it again.
For local workspaces, opening the panel lists the root's immediate files and folders.
Expanding a folder loads its contents, without scanning the folders inside it. Each page holds
up to 500 entries; **Load more** beneath a folder, or at the bottom of the root listing, adds
the next page. A large subtree no longer uses up the listing budget for unrelated folders.
Collapsing and reopening a loaded folder reuses its cached contents.
Use the search box as follows:
- **Type to filter loaded entries.** This makes no request and cannot find a file in a folder
you have not loaded. Matching ignores case; `*` separates pieces that must appear in order.
- **Press Enter to search the workspace**, including folders you have not opened, under the
root the panel is showing. Click a folder in the results to load its ancestors and browse it.
- **Clear the box to return to your tree**, with its expanded folders and loaded pages.
Workspace search keeps its existing limits: a 5,000-entry scan budget, up to 1,000 matches,
and depth and read limits. A limit or an unreachable folder can leave the search incomplete.
The status then says `(truncated)`; with no results the panel says **Search incomplete; no
matches in scanned files**, rather than implying the whole workspace has no matches. You can
still browse folders directly to reach files the search did not scan.
**Expand/Collapse All** opens folders whose contents are already loaded, or collapses them;
it does not fetch every folder in the workspace. The show-hidden button adds dot-prefixed files and
folders alongside ordinary entries and keeps the current filter or search and applicable
expanded folders. Generated directories such as `.git`, `node_modules`, `dist` and `build`
remain excluded.
**Refresh** clears the search and reloads the root and visible expanded folders, keeping
their expansion state. Contents behind a collapsed folder load when you reopen it. If a
folder or its next page fails to load, its error and **Retry loading** button appear there;
entries already loaded stay visible. Retry acts on that folder or page, while Refresh
reloads the visible tree. A failed load is never presented as an empty folder.
If the initial root listing fails, use Refresh.
Each file row has a download arrow and a × that deletes the file after you confirm. Both show
when you point at the row, and always on a touch screen. Delete removes one file at a time,
+87 -8
View File
@@ -161,6 +161,7 @@ TS_RENAME_RECORD="$HOME/.codeman/tailscale-rename"
# tailscale_choose_mapping (path mode) or read back from the service file.
BIND_BASE_URL=""
EXISTING_BASE_URL=""
EXISTING_MULTIUSER="0"
EXISTING_VERSION=""
# Answer presets from flags. LAUNCH_PRESET: 1 = run now, 2 = service, 3 = do
@@ -2339,26 +2340,61 @@ xml_unescape() {
printf '%s' "$1" | sed -e 's/&lt;/</g' -e 's/&gt;/>/g' -e 's/&amp;/\&/g'
}
# Read one assignment from the unit's Environment= directives. Each line can
# hold several assignments. Quotes are removed wherever they sit in a word, as
# systemd does (KEY="a b" and "KEY=a b" are the same assignment); backslash
# escapes inside quotes are kept for systemd_env_unescape, and a line whose
# quote never closes assigns nothing. Later assignments and empty directives
# override earlier values. The unit is read as data.
read_systemd_environment() {
awk -v key="$2=" '
/^[[:space:]]*Environment[[:space:]]*=/ {
line = $0
sub(/^[[:space:]]*Environment[[:space:]]*=[[:space:]]*/, "", line)
if (line == "") { value = ""; next }
n = length(line); word = ""; inword = 0; q = ""
for (i = 1; i <= n + 1; i++) {
c = (i <= n) ? substr(line, i, 1) : " "
if (q != "") {
if (c == "\\" && i < n) { word = word c substr(line, i + 1, 1); i++; continue }
if (c == q) { q = ""; continue }
word = word c; continue
}
if (c == "\"" || c == "\047") { q = c; inword = 1; continue }
if (c ~ /[[:space:]]/) {
if (inword && index(word, key) == 1) value = substr(word, length(key) + 1)
word = ""; inword = 0; continue
}
word = word c; inword = 1
}
}
END { print value }
' "$1"
}
# Read the binding out of an already-installed service file, if any. A service
# file WITHOUT our CODEMAN_HOST line is a pre-1.8 install, which effectively
# ran loopback (the server default), so it reports 127.0.0.1. Also reads back
# the sub-path (CODEMAN_BASE_URL) and the port the service was written with,
# and the installed version, for the preflight summary and the re-run defaults.
# the service sub-path, port, multi-user mode, and installed version for the
# preflight summary and the re-run defaults.
read_existing_binding() {
EXISTING_FOUND="0"; EXISTING_HOST=""; EXISTING_PASSWORD=""; EXISTING_ACK="0"; EXISTING_BASE_URL=""
EXISTING_FOUND="0"; EXISTING_HOST=""; EXISTING_PASSWORD=""; EXISTING_ACK="0"; EXISTING_BASE_URL=""; EXISTING_MULTIUSER="0"
local unit="$HOME/.config/systemd/user/codeman-web.service"
local plist="$HOME/Library/LaunchAgents/com.codeman.web.plist"
local existing_port=""
if [[ -f "$unit" ]]; then
EXISTING_FOUND="1"
EXISTING_HOST=$(sed -n 's/^Environment=CODEMAN_HOST=//p' "$unit" | head -1)
EXISTING_HOST=$(read_systemd_environment "$unit" CODEMAN_HOST)
local pwline
pwline=$(sed -n 's/^Environment="CODEMAN_PASSWORD=\(.*\)"$/\1/p' "$unit" | head -1)
pwline=$(read_systemd_environment "$unit" CODEMAN_PASSWORD)
[[ -n "$pwline" ]] && EXISTING_PASSWORD=$(systemd_env_unescape "$pwline")
grep -q '^Environment=CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK=1' "$unit" && EXISTING_ACK="1"
EXISTING_BASE_URL=$(sed -n 's/^Environment=CODEMAN_BASE_URL=//p' "$unit" | head -1)
existing_port=$(sed -n 's/^Environment=CODEMAN_PORT=//p' "$unit" | head -1)
[[ "$(read_systemd_environment "$unit" CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK)" == "1" ]] && EXISTING_ACK="1"
EXISTING_BASE_URL=$(read_systemd_environment "$unit" CODEMAN_BASE_URL)
case "$(read_systemd_environment "$unit" CODEMAN_MULTIUSER)" in
1|true) EXISTING_MULTIUSER="1" ;;
esac
existing_port=$(read_systemd_environment "$unit" CODEMAN_PORT)
elif [[ -f "$plist" ]]; then
EXISTING_FOUND="1"
EXISTING_HOST=$(awk '/<key>CODEMAN_HOST<\/key>/{getline; print}' "$plist" | sed -n 's/.*<string>\(.*\)<\/string>.*/\1/p')
@@ -2367,6 +2403,14 @@ read_existing_binding() {
[[ -n "$pwraw" ]] && EXISTING_PASSWORD=$(xml_unescape "$pwraw")
grep -q '<key>CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK</key>' "$plist" && EXISTING_ACK="1"
EXISTING_BASE_URL=$(awk '/<key>CODEMAN_BASE_URL<\/key>/{getline; print}' "$plist" | sed -n 's/.*<string>\(.*\)<\/string>.*/\1/p')
if awk '/<key>CODEMAN_MULTIUSER<\/key>/ {
sub(/.*<key>CODEMAN_MULTIUSER<\/key>[[:space:]]*/, "")
while ($0 ~ /^[[:space:]]*$/ && getline > 0) {}
enabled = ($0 ~ /^[[:space:]]*<string>(1|true)<\/string>/)
}
END { exit !enabled }' "$plist"; then
EXISTING_MULTIUSER="1"
fi
existing_port=$(awk '/<key>CODEMAN_PORT<\/key>/{getline; print}' "$plist" | sed -n 's/.*<string>\(.*\)<\/string>.*/\1/p')
fi
@@ -3636,6 +3680,11 @@ setup_launchd_service() {
<string>$(xml_escape "$CODEMAN_PORT")</string>"
fi
if [[ "$EXISTING_MULTIUSER" == "1" ]]; then
bind_plist+=$'\n'" <key>CODEMAN_MULTIUSER</key>
<string>1</string>"
fi
cat > "$agent_plist" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
@@ -3719,6 +3768,10 @@ setup_systemd_service() {
bind_env="${bind_env:+$bind_env$'\n'}Environment=CODEMAN_PORT=$CODEMAN_PORT"
fi
if [[ "$EXISTING_MULTIUSER" == "1" ]]; then
bind_env="${bind_env:+$bind_env$'\n'}Environment=CODEMAN_MULTIUSER=1"
fi
# Create service file
cat > "$service_file" << EOF
[Unit]
@@ -4416,6 +4469,32 @@ print_done_screen() {
echo -e " ${DIM}(the same variables apply to: codeman web -d)${NC}"
fi
fi
if [[ "$EXISTING_MULTIUSER" != "1" ]]; then
echo -e " ${BOLD}Users${NC} Create the first admin with ${CYAN}codeman users add <name> --admin${NC} before enabling multi-user mode."
# Only where no service runs: next to a working service this line would start a
# second server on the same data dir and tmux socket.
if [[ "$launch" != "2" || "$service_ok" != "true" ]]; then
echo -e " To start manually, run ${CYAN}$(start_command_hint) --multiuser${NC}"
fi
if [[ "$launch" == "2" ]]; then
case "$svc" in
systemd)
if [[ -f "$unit" ]]; then
echo -e " In ${CYAN}~/.config/systemd/user/codeman-web.service${NC}, add ${CYAN}Environment=CODEMAN_MULTIUSER=1${NC} under [Service]."
echo -e " Then run ${CYAN}systemctl --user daemon-reload && systemctl --user restart codeman-web${NC}"
fi
;;
launchd)
if [[ -f "$agent_plist" ]]; then
echo -e " In ${CYAN}~/Library/LaunchAgents/com.codeman.web.plist${NC}, add this entry to EnvironmentVariables."
echo -e " ${CYAN}<key>CODEMAN_MULTIUSER</key><string>1</string>${NC}"
echo -e " Then run ${CYAN}launchctl unload ~/Library/LaunchAgents/com.codeman.web.plist${NC}"
echo -e " followed by ${CYAN}launchctl load ~/Library/LaunchAgents/com.codeman.web.plist${NC}"
fi
;;
esac
fi
fi
if [[ -f "$INSTALL_DIR/$SOURCE_MARKER" && ! -d "$INSTALL_DIR/.git" ]]; then
echo -e " ${BOLD}Update${NC} re-run the install line ${DIM}(installed without git, so the in-app updater is off)${NC}"
else
+3 -3
View File
@@ -1,12 +1,12 @@
{
"name": "aicodeman",
"version": "1.51.0",
"version": "1.52.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "aicodeman",
"version": "1.51.0",
"version": "1.52.0",
"hasInstallScript": true,
"license": "MIT",
"workspaces": [
@@ -13363,7 +13363,7 @@
}
},
"packages/xterm-zerolag-input": {
"version": "0.4.2",
"version": "0.4.3",
"license": "MIT",
"devDependencies": {
"@xterm/headless": "^6.0.0",
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "aicodeman",
"version": "1.51.0",
"version": "1.52.0",
"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",
@@ -23,6 +23,7 @@
"test:watch": "vitest --config config/vitest.ci.config.ts",
"test:coverage": "vitest run --config config/vitest.ci.config.ts --coverage",
"test:ci": "vitest run --config config/vitest.ci.config.ts",
"pretest:browser": "node scripts/prepare-test-vendor.mjs",
"test:browser": "vitest run --config config/vitest.browser.config.ts",
"test:perf": "vitest run --config config/vitest.perf.config.ts",
"test:all": "vitest run --config config/vitest.config.ts",
+24
View File
@@ -65,6 +65,15 @@ pub fn respond(request: Request<Vec<u8>>) -> Response<Cow<'static, [u8]>> {
/// server restarted, and nothing in the page asks for the login again.
/// - defines `__codemanDesktopRefused(id)` (not enumerable) for
/// [`refused_script`].
/// - answers `document.execCommand('paste')` with false, the way Chromium
/// does, without asking WebKit. Codeman's ⌘V handler calls it on its hidden
/// paste trap (`_handleImagePaste` in src/web/public/image-input.js). From a
/// WKWebView, WebKit answers that call by opening its "Paste" access menu at
/// the last click and holding the page until it is picked or the clipboard
/// changes, so the key's own paste, the one that carries a copied image, got
/// stuck behind it and a pasted picture never arrived. With this answer each
/// ⌘V delivers exactly one paste event to the trap, measured on macOS 27.2
/// for image data, a screenshot, a file copied in Finder, and text.
pub const HOST_SHIM: &str = r#"(function () {
'use strict';
if (!/^https?:$/.test(location.protocol) || window.CodemanHost) return;
@@ -119,6 +128,19 @@ pub const HOST_SHIM: &str = r#"(function () {
}
});
// Cmd+V: Codeman's paste trap calls document.execCommand('paste'). WebKit
// answers that from a WKWebView with its "Paste" access menu and holds the
// page until someone picks it, and the key's own paste (the one carrying a
// copied image) is stuck behind it. Refuse it as Chromium does; every other
// command reaches WebKit unchanged.
var nativeExec = typeof Document === 'function' ? Document.prototype.execCommand : null;
if (typeof nativeExec === 'function') {
Document.prototype.execCommand = function execCommand(command) {
if (typeof command === 'string' && command.toLowerCase() === 'paste') return false;
return nativeExec.apply(this, arguments);
};
}
var markDownload = function (ev) {
if (ev.button > 1) return;
var a = link(ev);
@@ -322,6 +344,8 @@ mod tests {
"'auxclick'",
"MAX_URL = 4096",
"typeof id === 'string' && id !== ''",
"Document.prototype.execCommand = function execCommand(command)",
"command.toLowerCase() === 'paste') return false",
] {
assert!(HOST_SHIM.contains(needle), "{needle}");
}
+34
View File
@@ -1,5 +1,39 @@
# xterm-zerolag-input
## 0.4.3
### Patch Changes
- 7a3bbce: ### Thanks
- @HadrienKerlero for two big ones: the iPhone keyboard fix (#839, nine review rounds) and the Reload history action (#815, eighteen rounds), and for the reports that started both (#830, #814).
- @DodgyBadger for the Files panel that loads one folder at a time (#848), built on the design from #759.
- @kkalisz for three fixes: the login lockout after a restart (#838), exited agents on tmux 3.8 (#840, five review rounds), and the terminal dashboard's window size (#853).
- @bearyjd for the installer's multi-user guidance (#847) and the wiki section on keeping reverse-proxy hostnames across restarts (#845), a first contribution.
**Closing a tab can no longer signal every process of your account.** tmux reports pid 0 for a pane that has no process, such as an empty split beside the agent. A server restart could record that 0 for the tab, and closing the tab while that pane was the active one then signalled the children of pid 0, which is every process of the account: all sessions, tmux and the systemd user manager. A kill now never takes pid 0 or 1. Such a tab is closed by tmux alone and nothing else is signalled.
**The Files panel loads one folder at a time (#848).** Opening the panel reads only the top folder, and a folder is read when you open it, 500 entries a page with Load more. Large workspaces no longer stop at a scan limit, and Refresh keeps the folders you had open. Behaviour change: typing in the search box filters the folders already loaded, and Enter searches the whole workspace.
**iPhone keyboard suggestions, dictation and hold-delete work in the terminal (#839, fixes #830).** Tapping a suggestion used to send only its first letter, and holding delete never went word by word. Suggestions, text replacement, dictation and held delete now reach the agent as one ordered edit, in the main terminal, the split pane and every tile. A delayed Enter or paste stays with the session it was typed for when you switch tabs, and backspace deletes a whole emoji.
**Mac app: server tabs (#816).** The Mac app keeps several Codeman servers open in one window, one tab each in the title bar, and switches between them with a click or ⌘1 to ⌘8. Every tab shows whether its server needs you, is waiting, is working or is offline, and ⌘0 shows all servers at once with the ones that need you first. ⌘T opens another server, a tab can be renamed, coloured and dragged, ⇧⌘T reopens a closed one, and your tabs come back at the next launch. On macOS 14 and later every server keeps its own login and cookies; before macOS 14 a second tab on the same machine is refused. Behaviour change: only the server you used last keeps its per-device settings (font size, skin); every other server starts those fresh once.
**Fixes.**
- **An open tab after a restart no longer locks everyone out (#838).** A request with no `Authorization` header always gets the login prompt and is no longer counted as a failed login. Before, an open tab's background requests filled the per-IP limit within seconds of a restart, and everyone behind the same tunnel address was locked out for 15 minutes. Wrong passwords and malformed headers are counted as before.
- **Missing lines above the live screen can be fetched again (#815, fixes #814).** In some agent sessions (seen with OMP) a few lines were missing right above the live output until you scrolled to the very top. The history banner now has a Reload history action, on desktop and on phones, that fetches the whole history again and keeps the text you are reading in place. It can be switched off per device in Settings > Terminal & Input > Scrolling & rendering. Also, while you are scrolled up, new output no longer moves the text you are reading once the scrollback is full.
- **An agent that exited is seen again on tmux 3.8 (#840).** tmux 3.8 prints no process number for a finished pane, so a session whose agent had exited stayed on the board as idle, and a restart of Codeman dropped its record while its tmux session stayed behind. Such a session is now seen as exited and closed, as on older tmux. Finished sessions that piled up on tmux 3.8 are relaunched once, at the first start after this update. A dead `codeman-*` tmux session that was orphaned before this fix is not found again: remove it with `tmux -L codeman kill-session -t codeman-<id>`.
- **`codeman tui` takes its window size back (#853).** While a terminal is attached, the window follows whichever client was used last, as plain tmux does. Before, a browser tab that opened or resized the same session pinned the window to the tab's size until you detached and attached again. Now typing, pasting or resizing the terminal fills it again, and typing in the tab, or its Redraw, gives the tab the size. Needs tmux 3.3 or newer.
- **Closing a dialog you opened with the mouse puts the keyboard back in the terminal (#857).** After App Settings or Session Options was opened with a click and closed again, nothing you typed reached the terminal until you clicked it. A dialog now returns the keyboard to the field you were typing in when you clicked, which with the tile grid or the split open is the pane you were in. The Session Manager and the command palette follow the same rule, and a dialog opened with the keyboard still returns to the control it was opened from.
- **The Ledger tab layout shows the working spinner again (#851).** The ledger hid the status dot and the spinner with it, so a busy session looked like an idle one. A working cell now keeps the ring.
- **The phone toolbar sits directly on the keyboard (#819).** With the keyboard open on an iPhone, an empty band sat between the toolbar and the keyboard, and the last line of the prompt you were typing was hidden under the bar above it. Both are gone.
- **Mac app: pasting an image works (#817).** ⌘V with a copied picture did nothing in the Mac app, while the same server worked in a browser. Screenshots, images copied from an app, files copied in Finder and plain text now paste with one ⌘V, also from servers on older Codeman versions.
- **The installer explains multi-user mode and keeps it across re-runs (#847).** The done screen says how to create the first admin and switch multi-user sign-in on for a systemd unit or a LaunchAgent, and a re-run keeps an existing `CODEMAN_MULTIUSER` setting.
- **A hand-written quoted value in the systemd unit survives an installer re-run.** `Environment=CODEMAN_PASSWORD="my pass"` used to be dropped when the installer rewrote the unit, which left a server bound to the LAN without its password. It is now read the way systemd reads it.
**Fixes applied while landing.** The installer prints the manual multi-user start line only where no service runs, since next to a running service it would start a second server on the same data (#847). The Files panel no longer pages through a whole large folder looking for an open folder that was deleted, shows a folder that is still waiting to load as loading instead of empty, and its error line and single-match count read correctly in Chinese and English (#848). The resize nudge that lets a browser's Redraw win back the window runs only for sessions that have tmux behind them (#853), and the test for closing a live pane no longer reads the machine's real process list (#840).
**Docs and tests.** The Remote Access wiki page shows how to keep `CODEMAN_ALLOWED_HOSTS` across restarts with a systemd drop-in (#845), and the kill guard, the installer's unit reader and the Files panel restore have tests that fail without them.
## 0.4.2
### Patch Changes
+7 -1
View File
@@ -203,7 +203,7 @@ Implements the xterm.js `ITerminalAddon` interface. It deliberately does **not**
|--------|---------|-------------|
| `addChar(char)` | `void` | Add a single printable character. Auto-detects existing buffer text on the first keystroke. |
| `appendText(text)` | `void` | Append multiple characters (paste). |
| `removeChar()` | `'pending'` \| `'flushed'` \| `false` | Remove the last character and drop any IME composition. See [backspace handling](#backspace-handling). |
| `removeChar()` | `'pending'` \| `'flushed'` \| `false` | Remove the last grapheme cluster (one user-perceived character: a red heart, a skin-tone emoji, a flag or a ZWJ family is one) and drop any IME composition. See [backspace handling](#backspace-handling). |
| `clear()` | `void` | Clear all state, the composition included, and hide the overlay. Call on Enter, Ctrl+C, Escape. |
| `setComposition(text)` | `void` | Show text an IME is still composing as an underlined tail after the typed text. Pass `''` to remove it. See [IME composition](#ime-composition). |
| `setRowLimit(limit)` | `void` | Narrow the row bound the overlay keeps itself on screen with (normally `terminal.rows`) to the first `limit` screen rows, so it grows upward from the last of them; `null` restores all rows, and a limit above `terminal.rows` changes nothing. For hosts that keep the terminal taller than the box showing it, e.g. while an on-screen keyboard covers the bottom. |
@@ -220,6 +220,8 @@ Implements the xterm.js `ITerminalAddon` interface. It deliberately does **not**
The cascade order is pending text, then flushed text, then auto-detected buffer text (which is what makes backspace work after tab completion). Backspace "just works" across any combination of typed, in-flight and completed text.
One call removes one grapheme cluster: the unit a soft-keyboard Backspace removes, and what Claude Code and Codex delete per `\x7f`. So when it returns `'flushed'`, one `\x7f` removes the same character in those CLIs; a line editor that deletes by code point (bash readline, for a skin tone or a flag) removes less. For `'pending'` or `false`, send nothing. Grapheme boundaries come from `Intl.Segmenter`; where it is missing, one code point is removed instead.
### IME composition
While an input method (Japanese kana, Chinese pinyin, Korean) is still composing, the text is not committed yet, so it is not in `pendingText` either. `setComposition(text)` draws it as an underlined, `aria-hidden` tail right after the pending and flushed text, using the same wrapping and on-screen layout as the rest of the overlay.
@@ -260,6 +262,9 @@ Finds text that exists after the prompt but was never typed through the overlay.
|--------|-------------|
| `rerender()` | Force a re-render. Call after buffer reloads, screen redraws, resizes and reconnects. A no-op when there is nothing to draw, so it needs no guard. |
| `refreshFont()` | Re-cache font and color properties from the terminal. Call after a font size or theme change. |
| `getInputEndAnchor()` | Where the overlay's visible text ends, from its last layout: `{ col, row }` in viewport cells (`col` equals the column count at a full line's right edge), or `null` while the overlay is hidden. For placing a caret marker against the drawn input. |
| `getInputAnchor(offset)` | Resolve an offset in UTF-16 units into the last displayed flushed + pending + composition text to `{ col, row }` in viewport cells. Wrap boundaries prefer the next line; the final offset returns the end anchor. Returns `null` when hidden, out of range, inside a surrogate pair, or on a tail-sliced row. Performs no width measurement or DOM work. |
| `onLayout(callback)` | Call `callback` after each layout, a hide included. Returns an unsubscribe function. |
### Prompt
@@ -274,6 +279,7 @@ Finds text that exists after the prompt but was never typed through the overlay.
| Property | Type | Description |
|----------|------|-------------|
| `pendingText` | `string` | Unacknowledged text (read-only) |
| `committedText` | `string` | Flushed + pending text exactly as last displayed, excluding composition; `''` when hidden (read-only). Visual correspondence data, not a delivery acknowledgement. Offsets use UTF-16 units. |
| `hasPending` | `boolean` | `true` if there is pending or flushed text. Excludes the IME composition, so it can be `false` while the overlay still shows one |
| `composition` | `string` | The text set by `setComposition()`, `''` when none (read-only) |
| `state` | `ZerolagInputState` | Full snapshot: `pendingText`, `flushedLength`, `flushedText`, `visible`, `promptPosition` |
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "xterm-zerolag-input",
"version": "0.4.2",
"version": "0.4.3",
"description": "Instant keystroke feedback overlay for xterm.js: Mosh-inspired local echo that removes perceived input latency over SSH, tunnels and other high-RTT connections",
"type": "module",
"main": "dist/index.cjs",
@@ -8,6 +8,7 @@ export type {
ZerolagInputState,
PromptFinder,
PromptPosition,
InputEndAnchor,
CellDimensions,
} from './types.js';
export type { PredictiveEchoOptions, PredictionState } from './predictive-echo-addon.js';
@@ -1,4 +1,4 @@
import type { RenderParams, FontStyle, XtermTerminal } from './types.js';
import type { RenderParams, FontStyle, XtermTerminal, InputEndAnchor } from './types.js';
// ─── CJK / fullwidth character width detection ───────────────────────
@@ -88,6 +88,13 @@ function holdsOnlyRendered(container: HTMLDivElement, state: RenderedLines): boo
return !state.cursor || children[state.lines.length] === state.cursor;
}
interface OverlayPlacement {
end: InputEndAnchor | null;
firstVisible: number;
topRow: number;
keepsPromptLine: boolean;
}
/**
* Render the overlay content into the container element.
*
@@ -102,7 +109,7 @@ function holdsOnlyRendered(container: HTMLDivElement, state: RenderedLines): boo
* DOM work, layout and paint, which a long prompt on a phone paid for in
* dropped frames.
*/
export function renderOverlay(container: HTMLDivElement, params: RenderParams): void {
export function renderOverlay(container: HTMLDivElement, params: RenderParams): OverlayPlacement {
const {
lines,
compositionStart,
@@ -233,11 +240,11 @@ export function renderOverlay(container: HTMLDivElement, params: RenderParams):
state.lines.length = visibleLines.length;
state.lineKeys.length = visibleLines.length;
// Block cursor at end of last line (use visual width for CJK support)
if (showCursor) {
const lastLine = visibleLines[visibleLines.length - 1];
const lastLineLeft = visibleLines.length === 1 && keepsPromptLine ? startCol : 0;
const cursorCol = lastLineLeft + stringCellWidth(terminal, lastLine);
// Publish the text end from this layout even when the block cursor is hidden.
const lastLine = visibleLines[visibleLines.length - 1];
const lastLineLeft = visibleLines.length === 1 && keepsPromptLine ? startCol : 0;
const cursorCol = lastLineLeft + stringCellWidth(terminal, lastLine ?? '');
if (showCursor && lastLine !== undefined) {
if (cursorCol < totalCols) {
const cursor = document.createElement('span');
cursor.style.cssText = 'position:absolute;display:inline-block';
@@ -252,6 +259,12 @@ export function renderOverlay(container: HTMLDivElement, params: RenderParams):
}
container.style.display = '';
return {
end: lastLine === undefined ? null : { col: cursorCol, row: topRow + visibleLines.length - 1 },
firstVisible,
topRow,
keepsPromptLine,
};
}
/**
@@ -66,6 +66,14 @@ export interface PromptPosition {
col: number;
}
/** Viewport position at the end of the visible overlay input. */
export interface InputEndAnchor {
/** Column (0-based); equals the column count at a full line's right edge. */
col: number;
/** Viewport-relative row (0 = top of viewport). */
row: number;
}
/**
* Prompt detection strategy.
*
@@ -6,6 +6,7 @@ import type {
PromptPosition,
PromptFinder,
FontStyle,
InputEndAnchor,
} from './types.js';
import { getCellDimensions } from './cell-dimensions.js';
import { findPrompt, readTextAfterPrompt, promptRowInViewport } from './prompt-finder.js';
@@ -18,6 +19,57 @@ const DEFAULT_BG = '#0d0d0d';
const DEFAULT_FG = '#eeeeee';
const DEFAULT_CURSOR = '#e0e0e0';
interface InputLayoutLine {
start: number;
end: number;
startCol: number;
cols: number[];
codeUnits: number[];
}
interface InputLayout {
text: string;
committedLength: number;
lines: InputLayoutLine[];
firstVisible: number;
topRow: number;
keepsPromptLine: boolean;
startCol: number;
totalCols: number;
}
type GraphemeSegmenter = {
segment(input: string): { containing(index: number): { segment: string } | undefined };
};
const GRAPHEME_SEGMENTER: GraphemeSegmenter | null = (() => {
try {
const Segmenter = (
Intl as typeof Intl & {
Segmenter?: new (locale?: string, options?: { granularity: 'grapheme' }) => GraphemeSegmenter;
}
).Segmenter;
return Segmenter ? new Segmenter(undefined, { granularity: 'grapheme' }) : null;
} catch {
return null;
}
})();
/**
* UTF-16 width of the final grapheme cluster (one for an empty legacy flushed string).
* `containing()` finds the cluster at the end without walking the whole string (measured
* 0.09 ms at 60,000 characters, against 41 ms for a full scan), and segments with the
* whole text as context, so a cluster of any length and an odd run of flags come out right.
*/
function lastGraphemeWidth(text: string): number {
if (!text) return 1;
if (GRAPHEME_SEGMENTER) return GRAPHEME_SEGMENTER.segment(text).containing(text.length - 1)?.segment.length ?? 1;
const last = text.charCodeAt(text.length - 1);
const previous = text.charCodeAt(text.length - 2);
return last >= 0xdc00 && last <= 0xdfff && previous >= 0xd800 && previous <= 0xdbff ? 2 : 1;
}
/**
* xterm.js addon that provides instant keystroke feedback via a DOM overlay.
*
@@ -76,6 +128,9 @@ export class ZerolagInputAddon implements XtermAddon {
// Render cache
private _lastRenderKey = '';
private _lastPromptPos: PromptPosition | null = null;
private _inputEndAnchor: InputEndAnchor | null = null;
private _layout: InputLayout | null = null;
private _layoutListeners = new Set<() => void>();
// Font cache
private _font: FontStyle = {
@@ -130,6 +185,9 @@ export class ZerolagInputAddon implements XtermAddon {
try {
if (!promptRowInViewport(this._terminal!)) {
this._overlay!.style.display = 'none';
this._inputEndAnchor = null;
this._layout = null;
this._notifyLayout();
if (this._scrollTimer) {
clearTimeout(this._scrollTimer);
this._scrollTimer = null;
@@ -171,6 +229,7 @@ export class ZerolagInputAddon implements XtermAddon {
this._scrollViewport = null;
this._scrollHandler = null;
this._terminal = null;
this._layoutListeners.clear();
}
// ─── Input methods ────────────────────────────────────────────────
@@ -196,10 +255,12 @@ export class ZerolagInputAddon implements XtermAddon {
}
/**
* Remove the last character from the overlay.
* Remove the last grapheme cluster (one user-perceived character).
*
* Cascade order:
* 1. Remove from `pendingText` if non-empty → returns `'pending'`
* 1. Remove the last visible cluster from pending text; if it crosses into
* trustworthy flushed text, remove that tail too → returns `'flushed'`,
* otherwise returns `'pending'`
* 2. Decrement `flushedOffset` if pending is empty but flushed exists → returns `'flushed'`
* 3. Try `detectBufferText()` if both are empty, then decrement → returns `'flushed'`
*
@@ -207,8 +268,8 @@ export class ZerolagInputAddon implements XtermAddon {
*
* - `'pending'`: A character was removed from unsent text. The consumer
* should NOT send backspace to the PTY (the text was never transmitted).
* - `'flushed'`: A character was removed from text already sent to the PTY.
* The consumer SHOULD send backspace to the PTY.
* - `'flushed'`: A character was removed wholly or partly from text already
* sent to the PTY. The consumer SHOULD send one backspace to the PTY.
* - `false`: Nothing to remove. The consumer should NOT send backspace.
*
* Any IME composition is dropped in every case, and the overlay is repainted
@@ -219,32 +280,30 @@ export class ZerolagInputAddon implements XtermAddon {
const droppedComposition = this._composition.length > 0;
this._composition = '';
if (this._pendingText.length > 0) {
this._pendingText = this._pendingText.slice(0, -1);
const pendingLength = this._pendingText.length;
const hasFlushedText = this._flushedOffset > 0 && this._flushedText.length === this._flushedOffset;
const width = lastGraphemeWidth(hasFlushedText ? this._flushedText + this._pendingText : this._pendingText);
const flushedWidth = Math.max(0, width - pendingLength);
this._pendingText = this._pendingText.slice(0, -width);
if (flushedWidth > 0) {
this._flushedOffset -= flushedWidth;
this._flushedText = this._flushedText.slice(0, -flushedWidth);
}
if (this._pendingText.length > 0 || this._flushedOffset > 0) {
this._render();
} else {
this._hide();
}
return 'pending';
}
if (this._flushedOffset > 0) {
this._flushedOffset--;
this._flushedText = this._flushedText.slice(0, -1);
if (this._flushedOffset > 0) {
this._render();
} else {
this._hide();
}
return 'flushed';
return flushedWidth > 0 ? 'flushed' : 'pending';
}
// Both empty — try detecting text already on the prompt line
// (handles tab completion, arrow-key edits, etc.)
this._detectBufferText();
// (handles tab completion, arrow-key edits, etc.).
if (this._flushedOffset === 0) this._detectBufferText();
if (this._flushedOffset > 0) {
this._flushedOffset--;
this._flushedText = this._flushedText.slice(0, -1);
const width = lastGraphemeWidth(this._flushedText);
this._flushedOffset -= width;
this._flushedText = this._flushedText.slice(0, -width);
if (this._flushedOffset > 0) {
this._render();
} else {
@@ -320,6 +379,42 @@ export class ZerolagInputAddon implements XtermAddon {
// ─── Rendering control ────────────────────────────────────────────
/** Viewport text end from the renderer's last visible layout, or null when hidden. */
getInputEndAnchor(): InputEndAnchor | null {
return this._inputEndAnchor ? { ...this._inputEndAnchor } : null;
}
/** Resolve a UTF-16 offset in the last displayed text, with forward wrap affinity. */
getInputAnchor(offset: number): InputEndAnchor | null {
const layout = this._layout;
if (!layout || !Number.isInteger(offset) || offset < 0 || offset > layout.text.length) return null;
if (offset === layout.text.length) return this.getInputEndAnchor();
for (let i = layout.lines.length - 1; i >= layout.firstVisible; i--) {
const line = layout.lines[i];
if (offset < line.start || offset >= line.end) continue;
const index = line.codeUnits.indexOf(offset - line.start);
if (index < 0) return null;
return {
col: (i === 0 && layout.keepsPromptLine ? layout.startCol : 0) + line.cols[index],
row: layout.topRow + i - layout.firstVisible,
};
}
return null;
}
/** Last displayed flushed + pending text, not a delivery acknowledgement. */
get committedText(): string {
return this._layout ? this._layout.text.slice(0, this._layout.committedLength) : '';
}
/** Subscribe after each layout, including hide. Returns an unsubscribe function. */
onLayout(cb: () => void): () => void {
this._layoutListeners.add(cb);
return () => {
this._layoutListeners.delete(cb);
};
}
/**
* Force a re-render of the overlay at the current prompt position.
* Call after terminal resets, buffer reloads, or full-screen redraws
@@ -578,22 +673,35 @@ export class ZerolagInputAddon implements XtermAddon {
}
}
private _notifyLayout(): void {
for (const cb of this._layoutListeners) {
try {
cb();
} catch {
// A visual observer must not interrupt input or the other listeners.
}
}
}
private _hide(): void {
if (!this._overlay) return;
this._lastRenderKey = '';
this._lastPromptPos = null;
this._overlay.innerHTML = '';
this._overlay.style.display = 'none';
this._inputEndAnchor = null;
this._layout = null;
this._notifyLayout();
}
private _render(): void {
if (!this._terminal || !this._overlay) return;
if (!this._hasContent()) {
this._overlay.style.display = 'none';
return;
}
let layoutChanged = true;
try {
if (!this._hasContent()) {
this._overlay.style.display = 'none';
return;
}
const buf = this._terminal.buffer.active;
// Hide the overlay while the cursor row is scrolled out of view
@@ -647,6 +755,7 @@ export class ZerolagInputAddon implements XtermAddon {
}
// The composition is a styled tail after everything the user has typed.
const committedLength = displayText.length;
const compositionStart = [...displayText].length;
displayText += this._composition;
@@ -658,44 +767,61 @@ export class ZerolagInputAddon implements XtermAddon {
// redundant render.
const totalRows = this._layoutRows();
const renderKey = `${displayText}:${compositionStart}:${startCol}:${activePrompt.row}:${activePrompt.col}:${totalCols}:${totalRows}:${this._flushedOffset}`;
if (renderKey === this._lastRenderKey && this._overlay.style.display !== 'none') return;
if (renderKey === this._lastRenderKey && this._overlay.style.display !== 'none') {
layoutChanged = false;
return;
}
this._lastRenderKey = renderKey;
// Split into visual lines by column width (CJK wide chars = 2 cols)
const firstLineCols = Math.max(1, totalCols - startCol);
const chars = [...displayText]; // proper Unicode iteration
const lines: string[] = [];
const layoutLines: InputLayoutLine[] = [];
let codeUnit = 0;
let ci = 0;
// First line: remaining columns after prompt
{
let lineStr = '';
let lineCols = 0;
const line: InputLayoutLine = { start: codeUnit, end: codeUnit, startCol, cols: [], codeUnits: [] };
while (ci < chars.length) {
const cw = charCellWidth(this._terminal, chars[ci]);
if (lineCols + cw > firstLineCols) break;
line.cols.push(lineCols);
line.codeUnits.push(codeUnit - line.start);
codeUnit += chars[ci].length;
lineStr += chars[ci];
lineCols += cw;
ci++;
}
lines.push(lineStr);
line.end = codeUnit;
layoutLines.push(line);
}
// Subsequent lines: full terminal width
while (ci < chars.length) {
let lineStr = '';
let lineCols = 0;
const line: InputLayoutLine = { start: codeUnit, end: codeUnit, startCol: 0, cols: [], codeUnits: [] };
while (ci < chars.length) {
const cw = charCellWidth(this._terminal, chars[ci]);
if (lineCols + cw > totalCols) break;
line.cols.push(lineCols);
line.codeUnits.push(codeUnit - line.start);
codeUnit += chars[ci].length;
lineStr += chars[ci];
lineCols += cw;
ci++;
}
lines.push(lineStr);
line.end = codeUnit;
layoutLines.push(line);
}
const cursorColor = this._options.cursorColor ?? this._terminal.options.theme?.cursor ?? DEFAULT_CURSOR;
renderOverlay(this._overlay, {
const placement = renderOverlay(this._overlay, {
lines,
compositionStart: this._composition ? compositionStart : undefined,
startCol,
@@ -711,6 +837,17 @@ export class ZerolagInputAddon implements XtermAddon {
cursorColor,
terminal: this._terminal,
});
this._inputEndAnchor = placement.end;
this._layout = {
text: displayText,
committedLength,
lines: layoutLines,
firstVisible: placement.firstVisible,
topRow: placement.topRow,
keepsPromptLine: placement.keepsPromptLine,
startCol,
totalCols,
};
} catch {
// Hide on render error but preserve pendingText —
// next rerender() will retry when terminal is ready.
@@ -718,6 +855,12 @@ export class ZerolagInputAddon implements XtermAddon {
this._overlay.innerHTML = '';
this._overlay.style.display = 'none';
}
} finally {
if (this._overlay.style.display === 'none') {
this._inputEndAnchor = null;
this._layout = null;
}
if (layoutChanged) this._notifyLayout();
}
}
}
@@ -531,6 +531,29 @@ describe('renderOverlay — staying on screen (totalRows)', () => {
expect(container.style.top).toBe(6 * 17 + 'px');
});
it('returns the same placement used for upward growth and tail clipping', () => {
const container = document.createElement('div');
const params = makeParams({ lines: ['ab', '你好', 'x'], startCol: 3, promptRow: 5, totalRows: 6 });
expect(renderOverlay(container, params)).toEqual({
end: { col: 1, row: 5 },
firstVisible: 0,
topRow: 3,
keepsPromptLine: true,
});
expect(renderOverlay(container, { ...params, totalRows: 2 })).toEqual({
end: { col: 1, row: 1 },
firstVisible: 1,
topRow: 0,
keepsPromptLine: false,
});
expect(renderOverlay(container, { ...params, lines: [] })).toEqual({
end: null,
firstVisible: 0,
topRow: 5,
keepsPromptLine: true,
});
});
});
describe('renderOverlay: rebuilding only the lines that changed', () => {
@@ -1,6 +1,7 @@
import { describe, it, expect, afterEach } from 'vitest';
import { describe, it, expect, afterEach, vi } from 'vitest';
import { createMockTerminal } from './helpers.js';
import { ZerolagInputAddon } from '../src/zerolag-input-addon.js';
import type { InputEndAnchor } from '../src/types.js';
function setup(lines: string[] = ['$ '], promptChar = '$') {
const mock = createMockTerminal({ buffer: { lines } });
@@ -91,6 +92,113 @@ describe('ZerolagInputAddon', () => {
expect(addon.pendingText).toBe('a');
});
it('removes a whole pending emoji without changing flushed UTF-16 offsets', () => {
const { addon } = tracked();
addon.setFlushed(2, 'ab');
addon.appendText('c😀');
expect(addon.removeChar()).toBe('pending');
expect(addon.pendingText).toBe('c');
expect(addon.getFlushed()).toEqual({ count: 2, text: 'ab' });
expect(addon.removeChar()).toBe('pending');
expect(addon.pendingText).toBe('');
});
it.each([
['combining accent', 'a', '\u0301'],
['skin-tone modifier', '\u{1F44D}', '\u{1F3FD}'],
])('removes a %s cluster across the pending/flushed boundary', (_name, base, suffix) => {
const { addon } = tracked();
addon.setFlushed(base.length, base);
addon.appendText(suffix);
expect(addon.removeChar()).toBe('flushed');
expect(addon.getFlushed()).toEqual({ count: 0, text: '' });
expect(addon.pendingText).toBe('');
expect(addon.state.visible).toBe(false);
});
it('keeps flushed text when removing a separate pending character', () => {
const { addon } = tracked();
addon.setFlushed(1, 'a');
addon.appendText('b');
expect(addon.removeChar()).toBe('pending');
expect(addon.getFlushed()).toEqual({ count: 1, text: 'a' });
expect(addon.pendingText).toBe('');
});
it('removes a whole flushed emoji and subtracts its UTF-16 width', () => {
const { addon } = tracked();
addon.setFlushed(3, 'a😀');
expect(addon.removeChar()).toBe('flushed');
expect(addon.getFlushed()).toEqual({ count: 1, text: 'a' });
expect(addon.removeChar()).toBe('flushed');
expect(addon.getFlushed()).toEqual({ count: 0, text: '' });
expect(addon.state.visible).toBe(false);
});
it('removes a whole emoji from newly detected buffer text', () => {
const { addon } = tracked(['$ a😀']);
expect(addon.removeChar()).toBe('flushed');
expect(addon.getFlushed()).toEqual({ count: 1, text: 'a' });
});
it('hides after deleting the only pending emoji', () => {
const { addon } = tracked();
addon.appendText('😀');
expect(addon.removeChar()).toBe('pending');
expect(addon.pendingText).toBe('');
expect(addon.state.visible).toBe(false);
});
const graphemeCases = [
['red heart', '\u2764\uFE0F'],
['skin-tone thumbs up', '\u{1F44D}\u{1F3FD}'],
['flag', '\u{1F1EB}\u{1F1F7}'],
['ZWJ family', '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}\u200D\u{1F466}'],
];
it.each(graphemeCases)('removes a whole pending %s grapheme', (_name, emoji) => {
const { addon } = tracked();
addon.appendText('ok' + emoji);
expect(addon.removeChar()).toBe('pending');
expect(addon.pendingText).toBe('ok');
});
it('removes a cluster longer than 64 UTF-16 units in one call', () => {
const { addon } = tracked();
// `a` plus 80 combining acute accents is one grapheme cluster of 81 units.
const cluster = 'a' + '\u0301'.repeat(80);
addon.appendText('ok' + cluster);
expect(addon.removeChar()).toBe('pending');
expect(addon.pendingText).toBe('ok');
});
it('pairs regional indicators from the start of the run', () => {
const { addon } = tracked();
// Five flags then a lone indicator: the last cluster is the lone one, not a pair.
const flags = '\u{1F1EB}\u{1F1F7}'.repeat(5);
addon.appendText('ok' + flags + '\u{1F1EB}');
expect(addon.removeChar()).toBe('pending');
expect(addon.pendingText).toBe('ok' + flags);
expect(addon.removeChar()).toBe('pending');
expect(addon.pendingText).toBe('ok' + '\u{1F1EB}\u{1F1F7}'.repeat(4));
});
it('removes the last grapheme of a long draft', () => {
const { addon } = tracked();
const family = '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}\u200D\u{1F466}';
addon.appendText('a'.repeat(60000) + family);
expect(addon.removeChar()).toBe('pending');
expect(addon.pendingText).toBe('a'.repeat(60000));
});
it.each(graphemeCases)('removes a whole flushed %s grapheme and subtracts its UTF-16 width', (_name, emoji) => {
const { addon } = tracked();
const text = 'ok' + emoji;
addon.setFlushed(text.length, text);
expect(addon.removeChar()).toBe('flushed');
expect(addon.getFlushed()).toEqual({ count: 2, text: 'ok' });
});
it('returns false when nothing to remove', () => {
const { addon } = tracked();
expect(addon.removeChar()).toBe(false);
@@ -831,3 +939,304 @@ describe('setRowLimit', () => {
expect(overlay().style.top).toBe(`${9 * 17}px`);
});
});
describe('input end anchor and layout subscriptions', () => {
function layoutSetup({ cols = 20, rows = 6, promptRow = 1, showCursor = true } = {}) {
const lines = Array.from({ length: rows }, (_, i) => (i === promptRow ? '$ ' : ''));
const mock = createMockTerminal({ buffer: { lines }, cols, rows });
const addon = new ZerolagInputAddon({
prompt: { type: 'character', char: '$', offset: 2 },
showCursor,
});
mock.terminal.loadAddon(addon);
cleanups.push(() => {
addon.dispose();
mock.cleanup();
});
return { addon, mock };
}
it('returns the text end on a short line, including flushed and wide characters', () => {
const { addon } = layoutSetup();
addon.setFlushed(1, 'a');
addon.appendText('你😀');
expect(addon.getInputEndAnchor()).toEqual({ col: 7, row: 1 });
const anchor = addon.getInputEndAnchor()!;
anchor.col = 0;
expect(addon.getInputEndAnchor()).toEqual({ col: 7, row: 1 });
});
it('returns the short text end rather than the row edge with showCursor false', () => {
const { addon, mock } = layoutSetup({ showCursor: false });
addon.appendText('abc');
expect(addon.getInputEndAnchor()).toEqual({ col: 5, row: 1 });
const overlay = mock.terminal.element.querySelector('.xterm-screen')!.lastElementChild!;
expect(overlay.children.length).toBe(1); // line only, no cursor span
});
it('returns the unindented end of a wrapped line', () => {
const { addon } = layoutSetup();
addon.appendText('x'.repeat(23)); // 18 cells on the first line, then 5
expect(addon.getInputEndAnchor()).toEqual({ col: 5, row: 2 });
});
it('uses the renderer bottom clamp rather than the original prompt row', () => {
const { addon } = layoutSetup({ promptRow: 5 });
addon.appendText('x'.repeat(23));
expect(addon.getInputEndAnchor()).toEqual({ col: 5, row: 5 });
});
it('follows a narrowed row limit and a clipped tail without prompt indentation', () => {
const { addon } = layoutSetup({ promptRow: 5 });
addon.appendText('x'.repeat(43)); // lines of 18, 20 and 5 cells
addon.setRowLimit(2);
expect(addon.getInputEndAnchor()).toEqual({ col: 5, row: 1 });
addon.setRowLimit(1);
expect(addon.getInputEndAnchor()).toEqual({ col: 5, row: 0 });
});
it('reports the right edge of an exactly full line without requiring a cursor span', () => {
const { addon } = layoutSetup();
addon.appendText('x'.repeat(18));
expect(addon.getInputEndAnchor()).toEqual({ col: 20, row: 1 });
});
it('returns null before showing, after clear, and after dispose', () => {
const { addon } = layoutSetup();
expect(addon.getInputEndAnchor()).toBeNull();
addon.appendText('abc');
addon.clear();
expect(addon.getInputEndAnchor()).toBeNull();
addon.appendText('x');
addon.dispose();
expect(addon.getInputEndAnchor()).toBeNull();
});
it('returns null after deleting or clearing the last visible text', () => {
const { addon } = layoutSetup();
addon.addChar('x');
addon.removeChar();
expect(addon.getInputEndAnchor()).toBeNull();
addon.setFlushed(1, 'x');
addon.clearFlushed();
expect(addon.getInputEndAnchor()).toBeNull();
});
it('keeps painting at the last prompt when a redraw briefly hides the prompt marker', () => {
const { addon, mock } = layoutSetup();
addon.appendText('abc');
const before = addon.getInputEndAnchor();
expect(before).not.toBeNull();
mock.setLines(['output without a prompt']);
addon.rerender();
expect(addon.state.visible).toBe(true);
expect(addon.getInputEndAnchor()).toEqual(before);
});
it('publishes null on a scroll hide before repainting', () => {
const { addon, mock } = layoutSetup();
addon.appendText('abc');
const anchors: (InputEndAnchor | null)[] = [];
addon.onLayout(() => anchors.push(addon.getInputEndAnchor()));
mock.setScroll(0, 30);
mock.terminal.element.querySelector('.xterm-viewport')!.dispatchEvent(new Event('scroll'));
expect(anchors).toEqual([null]);
expect(addon.getInputEndAnchor()).toBeNull();
});
it('publishes null when render finds the cursor outside the viewport', () => {
const { addon, mock } = layoutSetup();
addon.appendText('abc');
mock.setScroll(0, 30);
addon.rerender();
expect(addon.getInputEndAnchor()).toBeNull();
});
it('publishes null when cell dimensions disappear', () => {
const { addon, mock } = layoutSetup();
addon.appendText('abc');
Reflect.deleteProperty(mock.terminal._core._renderService, 'dimensions');
addon.rerender();
expect(addon.getInputEndAnchor()).toBeNull();
});
it('publishes null on render failure while preserving the pending input', () => {
const { addon } = layoutSetup();
addon.appendText('abc');
addon.setPrompt({
type: 'custom',
find: () => {
throw new Error('buffer unavailable');
},
});
expect(addon.getInputEndAnchor()).toBeNull();
expect(addon.pendingText).toBe('abc');
});
it('notifies after each layout and hide, and stops after disposal of the listener', () => {
const { addon } = layoutSetup();
const anchors: (InputEndAnchor | null)[] = [];
const dispose = addon.onLayout(() => anchors.push(addon.getInputEndAnchor()));
addon.addChar('a');
addon.addChar('b');
addon.rerender();
addon.clear();
expect(anchors).toEqual([{ col: 3, row: 1 }, { col: 4, row: 1 }, { col: 4, row: 1 }, null]);
dispose();
dispose();
addon.addChar('c');
addon.clear();
expect(anchors).toHaveLength(4);
});
it('isolates listener failures from rendering and other listeners', () => {
const { addon } = layoutSetup();
addon.onLayout(() => {
throw new Error('observer failed');
});
const anchors: (InputEndAnchor | null)[] = [];
addon.onLayout(() => anchors.push(addon.getInputEndAnchor()));
expect(() => addon.appendText('abc')).not.toThrow();
expect(addon.state.visible).toBe(true);
expect(() => addon.clear()).not.toThrow();
expect(anchors).toEqual([{ col: 5, row: 1 }, null]);
});
it('maps a wide wrap with forward affinity from column 78', () => {
const { addon } = layoutSetup({ cols: 80 });
addon.setPrompt({ type: 'custom', offset: 0, find: () => ({ col: 78, row: 1 }) });
addon.appendText('a你b');
expect([0, 1, 2, 3].map((offset) => addon.getInputAnchor(offset))).toEqual([
{ col: 78, row: 1 },
{ col: 0, row: 2 },
{ col: 2, row: 2 },
{ col: 3, row: 2 },
]);
expect(addon.getInputEndAnchor()).toEqual({ col: 3, row: 2 });
});
it('maps multiple wide wraps including an empty prompt line', () => {
const { addon } = layoutSetup({ cols: 5 });
addon.setPrompt({ type: 'custom', offset: 0, find: () => ({ col: 4, row: 1 }) });
addon.appendText('你好世界a你b');
expect([0, 1, 2, 3, 4, 5, 6, 7].map((offset) => addon.getInputAnchor(offset))).toEqual([
{ col: 0, row: 2 },
{ col: 2, row: 2 },
{ col: 0, row: 3 },
{ col: 2, row: 3 },
{ col: 4, row: 3 },
{ col: 0, row: 4 },
{ col: 2, row: 4 },
{ col: 3, row: 4 },
]);
});
it('maps ZWJ code points and combining marks without accepting surrogate interiors', () => {
const { addon, mock } = layoutSetup();
Object.assign(mock.terminal, {
unicode: {
getStringCellWidth: (ch: string) => (ch === '\u200d' || ch === '\u0301' ? 0 : ch.length === 2 ? 2 : 1),
},
});
addon.appendText('👩\u200d💻e\u0301x');
expect([0, 1, 2, 3, 4, 5, 6, 7, 8].map((offset) => addon.getInputAnchor(offset))).toEqual([
{ col: 2, row: 1 },
null,
{ col: 4, row: 1 },
{ col: 4, row: 1 },
null,
{ col: 6, row: 1 },
{ col: 7, row: 1 },
{ col: 7, row: 1 },
{ col: 8, row: 1 },
]);
});
it('queries the composition tail but exposes only the last displayed committed text', () => {
const { addon } = layoutSetup({ cols: 8 });
addon.setFlushed(2, '😀');
addon.appendText('ab');
addon.setComposition('你好');
expect(addon.committedText).toBe('😀ab');
expect(addon.getInputAnchor(4)).toEqual({ col: 6, row: 1 });
expect(addon.getInputAnchor(5)).toEqual({ col: 0, row: 2 });
expect(addon.getInputAnchor(6)).toEqual({ col: 2, row: 2 });
expect(addon.getInputEndAnchor()).toEqual({ col: 2, row: 2 });
addon.setFlushed(2, 'zz', false);
expect(addon.committedText).toBe('😀ab');
expect(addon.state).not.toHaveProperty('committedText');
expect(addon.state).not.toHaveProperty('composition');
});
it('uses upward growth and hides tail-sliced caret rows', () => {
const { addon } = layoutSetup({ cols: 6, rows: 4, promptRow: 3 });
addon.appendText('abcdefghijkl'); // abcd / efghij / kl
expect(addon.getInputAnchor(0)).toEqual({ col: 2, row: 1 });
expect(addon.getInputAnchor(4)).toEqual({ col: 0, row: 2 });
expect(addon.getInputAnchor(10)).toEqual({ col: 0, row: 3 });
addon.setRowLimit(2);
expect(addon.getInputAnchor(0)).toBeNull();
expect(addon.getInputAnchor(3)).toBeNull();
expect(addon.getInputAnchor(4)).toEqual({ col: 0, row: 0 });
expect(addon.getInputAnchor(10)).toEqual({ col: 0, row: 1 });
expect(addon.getInputAnchor(12)).toEqual({ col: 2, row: 1 });
});
it('keeps the final offset at the right edge of a full final row', () => {
const { addon } = layoutSetup({ cols: 6 });
addon.appendText('abcdefghij');
expect(addon.getInputAnchor(4)).toEqual({ col: 0, row: 2 });
expect(addon.getInputAnchor(10)).toEqual({ col: 6, row: 2 });
expect(addon.getInputEndAnchor()).toEqual({ col: 6, row: 2 });
});
it('does no width measurement for a redundant render or an anchor query', () => {
const { addon, mock } = layoutSetup();
const width = vi.fn((ch: string) => (ch === '你' ? 2 : 1));
Object.assign(mock.terminal, { unicode: { getStringCellWidth: width } });
addon.setFlushed(3, 'a你b');
expect(width).toHaveBeenCalled();
width.mockClear();
addon.setFlushed(3, 'a你b'); // same key, unlike forced rerender()
expect(addon.getInputAnchor(1)).toEqual({ col: 3, row: 1 });
expect(addon.getInputAnchor(3)).toEqual({ col: 6, row: 1 });
expect(addon.committedText).toBe('a你b');
expect(width).not.toHaveBeenCalled();
});
it('rejects invalid offsets and clears visual correspondence on hide and disposal', () => {
const { addon, mock } = layoutSetup();
expect(addon.getInputAnchor(0)).toBeNull();
expect(addon.committedText).toBe('');
addon.appendText('abc');
for (const offset of [-1, 4, 0.5, NaN, Infinity]) expect(addon.getInputAnchor(offset)).toBeNull();
mock.setScroll(0, 30);
mock.terminal.element.querySelector('.xterm-viewport')!.dispatchEvent(new Event('scroll'));
expect(addon.getInputAnchor(0)).toBeNull();
expect(addon.committedText).toBe('');
mock.setScroll(0, 0);
addon.rerender();
expect(addon.committedText).toBe('abc');
addon.clear();
expect(addon.getInputAnchor(0)).toBeNull();
expect(addon.committedText).toBe('');
addon.appendText('x');
addon.dispose();
expect(addon.getInputAnchor(0)).toBeNull();
expect(addon.committedText).toBe('');
});
it('clears offset anchors and committed text on render failure', () => {
const { addon } = layoutSetup();
addon.appendText('abc');
addon.setPrompt({
type: 'custom',
find: () => {
throw new Error('buffer unavailable');
},
});
expect(addon.getInputAnchor(0)).toBeNull();
expect(addon.committedText).toBe('');
expect(addon.pendingText).toBe('abc');
});
});
+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.51.0",
"version": "1.52.0",
"author": {
"name": "Ark0N",
"url": "https://github.com/Ark0N"
+2
View File
@@ -114,6 +114,7 @@ appendFileSync(
// 4. Minify frontend assets
run('minify input-cjk.js', 'npx esbuild dist/web/public/input-cjk.js --minify --outfile=dist/web/public/input-cjk.js --allow-overwrite');
run('minify mobile-ime-preview.js', 'npx esbuild dist/web/public/mobile-ime-preview.js --minify --outfile=dist/web/public/mobile-ime-preview.js --allow-overwrite');
run('minify terminal-ios-native-input.js', 'npx esbuild dist/web/public/terminal-ios-native-input.js --minify --outfile=dist/web/public/terminal-ios-native-input.js --allow-overwrite');
run('minify terminal-keycode229-recovery.js', 'npx esbuild dist/web/public/terminal-keycode229-recovery.js --minify --outfile=dist/web/public/terminal-keycode229-recovery.js --allow-overwrite');
run('minify i18n.js', 'npx esbuild dist/web/public/i18n.js --minify --outfile=dist/web/public/i18n.js --allow-overwrite');
run('minify sanitize-html.js', 'npx esbuild dist/web/public/sanitize-html.js --minify --outfile=dist/web/public/sanitize-html.js --allow-overwrite');
@@ -145,6 +146,7 @@ console.log('\n[build] content-hash cache busting');
'keyboard-accessory.js',
'input-cjk.js',
'mobile-ime-preview.js',
'terminal-ios-native-input.js',
'terminal-keycode229-recovery.js',
'sanitize-html.js',
'tab-layout-browser.js',
+1 -1
View File
@@ -17,7 +17,7 @@
* this script adds is FRESHNESS and independence from install time: a checkout
* installed with `--ignore-scripts`, or one borrowing another tree's
* `node_modules`, never ran postinstall, and an edit to the zerolag package after
* install leaves the bundle stale. It runs as `pretest:mobile`.
* install leaves the bundle stale. It runs as `pretest:mobile` and `pretest:browser`.
*
* Mirrors the vendor steps in scripts/build.mjs, targeting the source tree. Same
* inputs and output names, so the page markup needs no test-only branch. That
+11 -1
View File
@@ -927,7 +927,7 @@ program
program
.command('tui')
.argument('[n]', 'attach straight to the nth session of `codeman tui --list`')
.argument('[session]', 'attach straight to a session: its number in `codeman tui --list`, or its exact session name')
.description('Terminal dashboard for your sessions (the web UI remains the primary surface)')
.option('-l, --list', 'Print the numbered session list and exit, instead of opening the dashboard')
.action(async (position: string | undefined, options: { list?: boolean }) => {
@@ -940,6 +940,16 @@ program
return;
}
if (position !== undefined) {
// Digits only is a list number, as it always was; anything else is a session name.
if (!/^\d+$/.test(position)) {
if (position.trim() === '') {
console.error(palette.err('An empty session name matches nothing.'));
process.exitCode = 1;
return;
}
process.exitCode = await runTuiAttach(position);
return;
}
const n = Number.parseInt(position, 10);
if (!Number.isSafeInteger(n) || n < 1) {
console.error(palette.err(`"${position}" is not a session number.`));
+4 -4
View File
@@ -303,8 +303,8 @@ const CLAUDE: CliEntry = {
transcript: 'claude-jsonl',
altScreen: 'strip-full',
echo: { policy: 'buffer', anchor: { kind: 'glyph', glyph: '❯', offset: 2 } },
// Declared-for-later: the live rule (`_shouldForwardWheelToApp`, terminal-ui.js) is this version
// AND the server-published `cliMouseTracking` flag (#498), so wiring this field up needs both.
// Read by `_shouldForwardWheelToApp` (terminal-ui.js) through `window.__codemanWheelForward`;
// forwarding also needs the server-published `cliMouseTracking` flag (#498).
wheelForward: { mode: 'version-gated', minVersion: '2.1.187' },
// A repaint-mode Claude pane keeps no local history, so when the wheel is not
// forwarded (older CLI, inline renderer, the local-scrollback opt-out) a scroll is
@@ -1926,8 +1926,8 @@ const COPILOT: CliEntry = {
// (`cliMouseTracking`). Same shape and reason as opencode. The wheel keeps working because
// `_shouldForwardWheelToApp` forwards it as SGR reports while the CLI is tracking.
altScreen: 'strip-mux-and-mouse',
// Forwards the wheel as SGR reports while the CLI is tracking the mouse, at any version
// (`_shouldForwardWheelToApp` in terminal-ui.js has no version check for copilot).
// Forwards the wheel as SGR reports while the CLI is tracking the mouse, at any version:
// `always` is what keeps `_shouldForwardWheelToApp` (terminal-ui.js) from checking one.
wheelForward: { mode: 'always' },
// Pages its own transcript on PageUp/PageDown (1.0.95, measured in tmux: three PageUp moved
// lines 109-140 to 010-042 and PageDown returned). This is the fallback when the
+15 -6
View File
@@ -596,10 +596,18 @@ export interface CliCapabilities {
* Forwarding the wheel to the CLI's own transcript. 'never' keeps local scrollback;
* 'version-gated' forwards from `minVersion` on; 'always' forwards at any version. Either
* forwarding mode applies only while the CLI has mouse tracking on (`cliMouseTracking`).
* Read by the browser's gate (`_shouldForwardWheelToApp` in terminal-ui.js) through
* `window.__codemanWheelForward`, which the server builds from this field for every CLI
* whose mode is not `never`, disabled ones included (their running sessions stay open).
*
* ⚠️ Declared only: nothing reads this field yet (see DECLARED-FOR-LATER below). The browser's
* gate is `_shouldForwardWheelToApp` in terminal-ui.js, which keeps its own hand-written
* per-CLI rules, so changing a value here changes nothing until that gate is changed too.
* ⚠️ 'version-gated' needs the session's `cliVersion`, and the server probes a version only
* for an entry that declares `capabilities.gates` (`cliNeedsVersionProbe`, session.ts). An
* entry without gates never forwards under 'version-gated', silently, so it uses 'always'.
*
* ⚠️ `cliMouseTracking` is only ever set for a CLI whose mouse DECSETs the server strips
* (`altScreen: 'strip-full'` or `'strip-mux-and-mouse'`), so a forwarding mode on any other
* `altScreen` never forwards: xterm keeps the DECSETs and encodes the wheel itself, until a
* replay drops its mouse mode.
*/
wheelForward: { mode: 'never' | 'version-gated' | 'always'; minVersion?: string };
/**
@@ -1009,14 +1017,15 @@ export interface CliOverlays {
/**
* ⚠️ DECLARED-FOR-LATER: fields no code reads yet.
*
* `accent`, `overlays.credStore`, `capabilities.echo`, `capabilities.wheelForward`,
* `capabilities.keyboardAccessory` and `capabilities.maxFrameBytes` all describe FRONTEND
* `accent`, `overlays.credStore`, `capabilities.echo`, `capabilities.keyboardAccessory` and
* `capabilities.maxFrameBytes` all describe FRONTEND
* behaviour, and most of the frontend is deliberately untouched by the change that introduced
* this registry — `app.js`, `terminal-ui.js`, `styles.css` and friends keep their own
* hand-authored per-CLI rules, and moving them is its own piece of work with its own way of
* being verified (a mobile/browser suite the CI gate cannot see). `shortBadge` graduated out of
* this list (docs/cli-enable-disable-plan.md, Phase 2): `GET /api/clis` reads it for the
* CLI-management Settings list.
* CLI-management Settings list, and so did `capabilities.wheelForward`, which the browser's wheel
* gate reads through `window.__codemanWheelForward`.
*
* They are declared now because each entry should describe its CLI completely, and because
* transcribing them while the hand-written source is still on screen is when the values are
+52
View File
@@ -0,0 +1,52 @@
/**
* @fileoverview The header CPU reading: CPU use over all cores since the previous reading, from each core's
* busy and idle time as `os.cpus()` reports it (the kernel's per-core counters on Linux, macOS and Windows).
*
* It replaces the 1-minute load average divided by the core count. Load counts runnable tasks, not busy time,
* so a host with bursty short-lived processes, or a VM whose vCPU threads count as runnable, read 100% while
* most of its cores were idle.
*/
import type { CpuInfo } from 'node:os';
/** Readings closer together than this reuse the last value, so several open browsers never shrink the window. */
export const CPU_USAGE_MIN_WINDOW_MS = 1000;
interface CpuTimes {
busy: number;
total: number;
at: number;
}
/**
* A meter that answers the CPU use, 0 to 100, between this reading and the previous one. Without usable core
* times (none reported, or counters that went backwards, as when a core goes offline) it answers the last
* reading, else `fallback()`. The first reading covers the time since the meter was created.
*/
export function createCpuUsageMeter(
readCores: () => Pick<CpuInfo, 'times'>[],
clock: () => number,
fallback: () => number
): () => number {
const sample = (): CpuTimes => {
let busy = 0;
let total = 0;
for (const { times } of readCores()) {
const all = times.user + times.nice + times.sys + times.idle + times.irq;
total += all;
busy += all - times.idle;
}
return { busy, total, at: clock() };
};
let base = sample();
let last: number | undefined;
return () => {
const now = sample();
if (last !== undefined && now.at - base.at < CPU_USAGE_MIN_WINDOW_MS) return last;
const busy = now.busy - base.busy;
const total = now.total - base.total;
base = now;
if (!(total > 0) || busy < 0) return last ?? fallback();
last = Math.min(100, Math.max(0, Math.round((busy / total) * 100)));
return last;
};
}
+263 -10
View File
@@ -27,6 +27,11 @@
* - **Failures reported, not swallowed.** The shell tab used to be where the
* stack trace landed. With no tab, the spawn's own output is captured and
* handed back to the caller instead.
* - **The launch token traded, not forwarded.** `dsh web` gates its own index
* behind a one-time token it prints on stdout and exchanges for a browser
* cookie. The tab stores a clean URL, so nothing on the browser side could
* ever present that token and every load answered 401. This module trades it
* here, once, and hands the cookie to the proxy (`getDeepSeekWebCookie`).
*/
import { spawn, type ChildProcess } from 'node:child_process';
@@ -53,6 +58,23 @@ const READY_POLL_MS = 400;
const KILL_GRACE_MS = 3_000;
/** Bound on captured child output, so a chatty boot cannot grow without limit. */
const OUTPUT_CAP = 16_384;
/**
* Bound on the boot-output window searched for the launch banner.
*
* Deliberately larger and separate from {@link OUTPUT_CAP}: that one only has to
* keep an error tail, while this one must survive a chatty plugin tree's boot
* logs long enough to see a banner printed after them. 256 KB of one-line output
* is far beyond anything a real boot prints, and a bound still exists because a
* wedged child can print forever.
*/
const BANNER_SCAN_CAP = 262_144;
/** How long boot waits for `dsh web` to print the launch URL it gates itself on. */
const LAUNCH_URL_WAIT_MS = 4_000;
/** Bound on the one-shot token→cookie exchange (loopback, so this is generous). */
const TOKEN_EXCHANGE_TIMEOUT_MS = 5_000;
/** Cookie name `dsh web` mints for a browser session that presented the token. */
const DSH_AUTH_COOKIE_PREFIX = 'dsh-auth-';
export interface DeepSeekWebStatus {
running: boolean;
@@ -66,7 +88,33 @@ interface RunningServer {
child: ChildProcess;
port: number;
authority: string;
/**
* Username of the Codeman user whose request started this server. Undefined in
* single-user mode, where no owner exists. The cookie bought with the launch
* token belongs to that identity and is presented to nobody else (see
* `getDeepSeekWebCookie`).
*/
starter: string | undefined;
output: () => string;
/**
* Boot output scanned for the launch banner, on its own (larger) budget than
* `output`. Read through this rather than `output` so a banner printed after
* the error-tail cap filled is still found.
*/
banner: () => string;
/**
* The `dsh-auth-*` cookie bought with this process's launch token, once the
* exchange succeeded. Null on a dsh old enough to serve its index without a
* token, which is why "no cookie" is not a startup failure.
*/
cookie: string | null;
/**
* True when a token-bearing banner was found but the exchange produced no
* cookie. Such a server cannot authenticate its tab and must not be reused: the
* warning tells the user to restart `dsh web`, and the next start request is
* what performs that restart.
*/
cookieFailed: boolean;
}
let current: RunningServer | null = null;
@@ -105,6 +153,158 @@ async function answersHttp(port: number): Promise<boolean> {
}
}
/**
* Remove SGR sequences so a coloured banner still parses.
*
* A coloured banner would otherwise hide the URL behind escape codes and turn a
* perfectly working server into a 401.
*/
function stripSgr(output: string): string {
// Built from the code point rather than written as `\x1b` so the linter's
// no-control-regex rule does not read it as an accidental control character.
return output.replace(new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, 'g'), '');
}
/**
* The first `dsh web:` payload that parses as an absolute http(s) URL.
*
* Lines whose payload is not a URL are skipped, which is what makes a
* `dsh web: loading profiles` diagnostic harmless. `requireToken` skips an
* http(s) URL that carries no `token` as well, so a diagnostic that happens to
* contain a plain link cannot shadow the real banner. Null when no line qualifies.
*/
function firstLaunchBannerUrl(output: string, requireToken = false): string | null {
// Fresh per call: a module-level /g pattern carries lastIndex between calls.
const line = /dsh web:\s*(\S+)/g;
for (const match of stripSgr(output).matchAll(line)) {
let url: URL;
try {
url = new URL(match[1]);
} catch {
continue;
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') continue;
if (requireToken && !url.searchParams.get('token')) continue;
return url.href;
}
return null;
}
/**
* The authenticated URL `dsh web` prints once it is up.
*
* Its browser-auth gate made the index private: boot writes
* `dsh web: http://127.0.0.1:<port>/?token=<one-time token>` and only a request
* carrying that token is answered with the cookie that authorizes everything
* after it. The token is per process, so it can be neither guessed nor carried
* across restarts — it has to be read out of the boot output.
*
* Scans EVERY `dsh web:` line and returns the first one that is a usable URL
* carrying a token, because dsh also prints diagnostics under the same prefix
* before the banner.
*
* Null for output without one, which is the older-dsh case and stays working.
*
* @param output - captured stdout+stderr so far.
* @returns absolute http(s) URL carrying a `token`, or null.
*/
export function parseLaunchUrl(output: string): string | null {
return firstLaunchBannerUrl(output, true);
}
/**
* Whether a launch URL names the loopback port this supervisor just spawned.
*
* The URL is read from the child's output, but fetching it is a request made by
* the SERVER. A banner naming another host, or another local service's port, must
* not turn that exchange into an SSRF primitive, so the target is required to be
* the exact origin the token was minted for.
*/
export function launchUrlTargetsServer(launchUrl: string, port: number): boolean {
try {
const url = new URL(launchUrl);
const effectivePort = Number(url.port || (url.protocol === 'https:' ? 443 : 80));
return url.hostname === '127.0.0.1' && effectivePort === port;
} catch {
return false;
}
}
/**
* Trade the launch URL for the `dsh-auth-*` cookie the proxy will present.
*
* `redirect: 'manual'` is load-bearing: the 303 is the response that carries
* `Set-Cookie`, and following it would burn the token on a redirect to `./`
* while dropping the only credential the exchange produces.
*
* @param launchUrl - token-bearing URL from {@link parseLaunchUrl}.
* @returns `name=value` pair ready for a Cookie header, or null.
*/
async function exchangeLaunchToken(launchUrl: string): Promise<string | null> {
try {
const response = await fetch(launchUrl, {
redirect: 'manual',
signal: AbortSignal.timeout(TOKEN_EXCHANGE_TIMEOUT_MS),
});
for (const header of response.headers.getSetCookie()) {
const pair = header.split(';', 1)[0]?.trim();
if (pair?.startsWith(DSH_AUTH_COOKIE_PREFIX)) return pair;
}
return null;
} catch {
return null;
}
}
/**
* Wait for the banner, then exchange it.
*
* Never fails startup: a dsh without the gate prints a token-less banner, which
* is answered as "nothing to exchange" immediately rather than after the whole
* wait, and a gate that changes shape must not turn a serving UI into a boot
* failure.
*
* @param running - the just-started server, read for its captured output.
* @returns the cookie to hand the proxy (null when there is none) and whether a
* token was printed but could not be exchanged.
*/
async function captureSessionCookie(running: RunningServer): Promise<{ cookie: string | null; failed: boolean }> {
const deadline = Date.now() + LAUNCH_URL_WAIT_MS;
while (Date.now() < deadline) {
// Only COMPLETE lines: a chunk boundary can cut the token in half, and
// exchanging a truncated one would burn the token on a request that cannot
// authenticate. The next poll picks up the rest of the line.
const banner = running.banner();
const complete = banner.slice(0, banner.lastIndexOf('\n') + 1);
const launchUrl = parseLaunchUrl(complete);
if (launchUrl) {
if (!launchUrlTargetsServer(launchUrl, running.port)) {
console.warn(
'[DeepSeek web] the printed launch URL does not name the loopback port this server was started on; ' +
'not fetching it'
);
return { cookie: null, failed: true };
}
const cookie = await exchangeLaunchToken(launchUrl);
// The URL is a credential: never log it, only the fact that it did not work.
if (!cookie) {
console.warn(
'[DeepSeek web] the launch token was printed but could not be exchanged for a session cookie; ' +
'the next start request will restart `dsh web` so it can retry'
);
return { cookie: null, failed: true };
}
return { cookie, failed: false };
}
// Only a printed http(s) URL settles this: it is the older dsh, which needs
// no cookie. Any other line carrying the prefix (a diagnostic, a truncated
// write) is not a banner, so the wait continues instead of giving up early.
if (firstLaunchBannerUrl(complete)) return { cookie: null, failed: false };
await new Promise((resolve) => setTimeout(resolve, 100));
}
return { cookie: null, failed: false };
}
/**
* Signal the whole process group.
*
@@ -134,6 +334,25 @@ export function getDeepSeekWebStatus(): DeepSeekWebStatus {
};
}
/**
* The cookie this server's launch token bought, for the proxy to present.
*
* Keyed by `port` because the cookie is signed for the authority it was minted
* under (`127.0.0.1:<port>`): handing it to a web tab pointed at some other
* server would neither authenticate nor be that server's to receive. Null also
* covers a dsh old enough to need no cookie at all.
*
* @param port - loopback port the upstream request is bound for.
* @param owner - identity asking for it; must be the user who started the server.
* Both sides are undefined in single-user mode, where there is no owner.
* @returns `name=value` cookie pair, or null.
*/
export function getDeepSeekWebCookie(port: number, owner?: string): string | null {
if (!current || current.port !== port) return null;
if (current.starter !== owner) return null;
return current.cookie;
}
/** Stop the background server, if one is running. Safe to call when none is. */
export async function stopDeepSeekWeb(): Promise<void> {
const running = current;
@@ -174,11 +393,12 @@ let startLock: Promise<unknown> = Promise.resolve();
*
* @param dshDir directory holding the resolved `dsh` binary.
* @param authority browser authority to pass as `--trusted-host`.
* @param starter user whose request is starting it (undefined in single-user).
*/
export function startDeepSeekWeb(dshDir: string, authority: string): Promise<StartResult> {
export function startDeepSeekWeb(dshDir: string, authority: string, starter?: string): Promise<StartResult> {
const run = startLock.then(
() => startDeepSeekWebLocked(dshDir, authority),
() => startDeepSeekWebLocked(dshDir, authority)
() => startDeepSeekWebLocked(dshDir, authority, starter),
() => startDeepSeekWebLocked(dshDir, authority, starter)
);
startLock = run.then(
() => undefined,
@@ -187,13 +407,24 @@ export function startDeepSeekWeb(dshDir: string, authority: string): Promise<Sta
return run;
}
async function startDeepSeekWebLocked(dshDir: string, authority: string): Promise<StartResult> {
async function startDeepSeekWebLocked(
dshDir: string,
authority: string,
starter: string | undefined
): Promise<StartResult> {
// Reuse only when the running server is BOTH healthy and fenced for the
// authority now asking. A server trusting the other origin renders a page
// whose every API call 403s, which looks like a broken dashboard rather than
// a misconfigured one.
// authority now asking, it was started by this identity, and its credential
// works: the launch cookie is per process and per user, so handing a previous
// starter's server to another user would leave that user's tab on dsh's 401
// page, and a server whose token exchange failed would keep answering 401
// forever because reuse never gave anyone a chance to restart it.
if (current) {
if (current.authority === authority && (await answersHttp(current.port))) {
if (
!current.cookieFailed &&
current.authority === authority &&
current.starter === starter &&
(await answersHttp(current.port))
) {
return { ok: true, port: current.port, url: `http://127.0.0.1:${current.port}`, reused: true };
}
await stopDeepSeekWeb();
@@ -223,8 +454,15 @@ async function startDeepSeekWebLocked(dshDir: string, authority: string): Promis
// The pipes must be drained whether or not anyone reads them: a full pipe
// blocks the child. Storage is capped; draining is not.
let output = '';
// Scanned for the launch banner separately from `output`. That cap exists to
// bound the error tail, and a chatty profile can fill it before the banner is
// printed — losing the banner there produces exactly the 401 tab this module
// exists to prevent, so the two buffers must not share a limit.
let banner = '';
const capture = (chunk: Buffer) => {
if (output.length < OUTPUT_CAP) output += chunk.toString('utf-8');
const text = chunk.toString('utf-8');
if (output.length < OUTPUT_CAP) output += text;
if (banner.length < BANNER_SCAN_CAP) banner += text;
};
child.stdout?.on('data', capture);
child.stderr?.on('data', capture);
@@ -241,7 +479,16 @@ async function startDeepSeekWebLocked(dshDir: string, authority: string): Promis
if (current?.child === child) current = null;
});
const running: RunningServer = { child, port, authority, output: () => output };
const running: RunningServer = {
child,
port,
authority,
starter,
output: () => output,
banner: () => banner,
cookie: null,
cookieFailed: false,
};
current = running;
const deadline = Date.now() + READY_TIMEOUT_MS;
@@ -255,6 +502,12 @@ async function startDeepSeekWebLocked(dshDir: string, authority: string): Promis
return { ok: false, error: tail ? `dsh web exited during startup: ${tail}` : 'dsh web exited during startup' };
}
if (await answersHttp(port)) {
// Bought before this call resolves, so the first proxied page load
// already carries a credential — a tab opened a moment earlier would
// otherwise get the 401 this whole module exists to prevent.
const captured = await captureSessionCookie(running);
running.cookie = captured.cookie;
running.cookieFailed = captured.failed;
return { ok: true, port, url: `http://127.0.0.1:${port}`, reused: false };
}
await new Promise((r) => setTimeout(r, READY_POLL_MS));
+8 -1
View File
@@ -4,7 +4,10 @@
* Split like webhook-notify.ts, so the parts that matter are testable without a network:
* - pure: `sanitiseReply`, `threadNameFor`, `buildPost`, `discordConfigProblem`, `maskToken`
* - store: `~/.codeman/discord.json` (bot token, 0600 via tmp+rename) and
* `~/.codeman/discord-bridge.json` (sessionId -> threadId, not secret)
* `~/.codeman/discord-bridge.json` (sessionId -> threadId, not secret) and
* `~/.codeman/discord-reply-dedupe.json` (bounded reply IDs/timestamps, private).
* Allowed replies are claimed before attachments or typing; store failures never cost a reply.
* An unreadable file is never overwritten; invalid readable ID metadata can heal.
* - IO: `DiscordApi` (REST, injected fetch), `DiscordGateway` (inbound WebSocket, injected
* socket factory) and `DiscordBridge` (the rules that tie them to sessions)
*
@@ -27,6 +30,7 @@ import { join } from 'node:path';
import { probePathKind } from './utils/bounded-path-probe.js';
import { DISCORD_RECEIVED_DIR } from './web/paste-image-gc.js';
import WebSocket from 'ws';
import { DiscordReplyDedupe } from './discord-reply-dedupe.js';
import { WEBHOOK_SCOPES, type WebhookUrgency } from './types/push.js';
import {
DISCORD_ON_DELETE,
@@ -824,6 +828,7 @@ export interface DiscordBridgeDeps {
}
export class DiscordBridge {
private readonly replies: DiscordReplyDedupe;
private cfg: DiscordConfig = { ...DEFAULT_DISCORD_CONFIG };
private threads: Record<string, string> = {};
private loaded = false;
@@ -857,6 +862,7 @@ export class DiscordBridge {
constructor(private readonly deps: DiscordBridgeDeps) {
this.now = deps.now ?? Date.now;
this.replies = new DiscordReplyDedupe(deps.configDir, this.now);
this.api = new DiscordApi(() => this.cfg.token, deps.fetchImpl, deps.sleep);
}
@@ -1301,6 +1307,7 @@ export class DiscordBridge {
if (!this.cfg.allowedUserIds.includes(m.author?.id)) return;
const sessionId = Object.keys(this.threads).find((k) => this.threads[k] === m.channel_id);
if (!sessionId) return;
if (!(await this.replies.claim(m.guild_id, m.channel_id, m.id))) return;
const t = this.now();
const prev = this.lastReply.get(sessionId);
if (prev !== undefined && t - prev < REPLY_MIN_INTERVAL_MS) {
+111
View File
@@ -0,0 +1,111 @@
/**
* @fileoverview Best-effort replay protection for Discord replies.
*
* Owns `<data dir>/discord-reply-dedupe.json`: at most 2,048 `guild:channel:message`
* ids with the time each was claimed, kept for 7 days, written 0600 through a temp
* file and a rename. It holds ids only, never message content.
*
* `DiscordBridge.handleMessage()` calls `claim()` once per allowed message, after the
* guild, allowlist and thread gates and before the rate limit, the exited-agent check,
* any download and any typing, so a gateway replay of a message that was refused is
* refused again rather than typed.
*
* Rules a reader has to keep:
* - A store failure never costs a reply: the claim falls back to memory, warns once
* per outage and the reply is still typed.
* - A file that could not be read (an errno failure, a symlink, anything but a regular
* file) is never overwritten.
* - Readable but invalid content (bad JSON, bad rows, oversized) is replaced.
* - Rows read from disk go first, so claims made while the file was unreadable are
* the ones the 2,048 bound keeps.
*/
import fs from 'node:fs/promises';
import { join } from 'node:path';
import { randomUUID } from 'node:crypto';
const LIMIT = 2048;
const RETENTION_MS = 7 * 24 * 60 * 60_000;
export class DiscordReplyDedupe {
private seen = new Map<string, number>();
private loaded = false;
private dirty = false;
private warned = false;
private chain: Promise<unknown> = Promise.resolve();
constructor(
private readonly dir: string,
private readonly now: () => number = Date.now,
private readonly warn: () => void = () =>
console.warn('Discord reply metadata unavailable (discord-reply-dedupe.json); using in-memory deduplication')
) {}
claim(guild: string, channel: string, message: string): Promise<boolean> {
const run = this.chain.then(() => this.take(guild, channel, message));
this.chain = run.catch(() => undefined);
return run;
}
private async take(guild: string, channel: string, message: string): Promise<boolean> {
// Restored legacy configurations and malformed gateway IDs must not poison the store.
if (![guild, channel, message].every((id) => /^\d{15,25}$/.test(id))) return true;
const path = join(this.dir, 'discord-reply-dedupe.json');
const cutoff = this.now() - RETENTION_MS;
if (!this.loaded) {
let contentRead = false;
try {
const st = await fs.lstat(path);
if (!st.isFile() || st.isSymbolicLink()) throw Object.assign(new Error('Unsafe metadata'), { code: 'EINVAL' });
if (st.size > 512 * 1024) {
contentRead = true; // A known oversized regular file is invalid metadata, not an IO failure.
throw new Error('Oversized metadata');
}
const text = await fs.readFile(path, 'utf8');
contentRead = true;
const rows: unknown = JSON.parse(text);
if (!Array.isArray(rows) || rows.length > LIMIT) throw new Error('Invalid metadata');
const recovered = new Map<string, number>();
for (const row of rows) {
if (!Array.isArray(row) || !/^\d{15,25}:\d{15,25}:\d{15,25}$/.test(row[0]) || !Number.isFinite(row[1]))
throw new Error('Invalid metadata');
if (row[1] >= cutoff) recovered.set(row[0], row[1]);
}
// Older disk rows precede newer claims made while reads were unavailable.
this.seen = new Map([...recovered, ...this.seen]);
this.loaded = true;
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'ENOENT') this.loaded = true;
else {
this.report();
// Invalid content is recoverable ID-only metadata; unreadable/unsafe files stay untouched.
if (contentRead && !(err as NodeJS.ErrnoException).code) {
this.loaded = true;
this.dirty = true;
}
}
}
}
for (const [key, at] of this.seen) if (at < cutoff) this.seen.delete(key);
const key = `${guild}:${channel}:${message}`;
const fresh = !this.seen.has(key);
if (fresh) {
this.seen.set(key, this.now());
this.dirty = true;
} // Before awaiting IO or typing, including during an outage.
while (this.seen.size > LIMIT) this.seen.delete(this.seen.keys().next().value!);
if (!this.loaded || !this.dirty) return fresh; // Never overwrite a store file we could not read.
const tmp = `${path}.${randomUUID()}.tmp`;
try {
await fs.mkdir(this.dir, { recursive: true });
await fs.writeFile(tmp, JSON.stringify([...this.seen]), { mode: 0o600, flag: 'wx' });
await fs.rename(tmp, path);
this.warned = false;
this.dirty = false;
} catch {
this.report();
} finally {
await fs.rm(tmp, { force: true }).catch(() => undefined);
}
return fresh;
}
private report(): void {
if (!this.warned) this.warn();
this.warned = true;
}
}
+17
View File
@@ -32,6 +32,23 @@ export const PROC_WALK_MAX_DEPTH = 10;
/** Hard ceiling on collected descendants. A backstop, not an expected limit. */
export const PROC_WALK_MAX_NODES = 500;
/**
* Whether a session kill may signal `pid`, or walk the tree below it: a real process of
* the user's, so an integer above 1.
*
* On 2026-11-25 a kill that got pid 0 took down every process of the account: all of the
* user's sessions, tmux itself and the systemd user manager. The children of pid 0 are
* the whole machine, so the bounds above do not help (500 processes are most of one), and
* `kill(-1)` means every process one may signal while `kill(0)` means one's own group.
*
* tmux answers 0 for a pane with no process (`split-window ''`), and that 0 reaches the
* session record through the pane list read at server start. So 0 is an ordinary answer
* here, not a corrupt one, and it means "nothing to signal".
*/
export function isSignalablePid(pid: number | null | undefined): pid is number {
return typeof pid === 'number' && Number.isInteger(pid) && pid > 1;
}
export interface WalkOptions {
maxDepth?: number;
maxNodes?: number;
+39 -3
View File
@@ -5696,13 +5696,49 @@ export class Session extends EventEmitter {
this._guardedGeometryRevision++;
this._ptyCols = cols;
this._ptyRows = rows;
if (!IS_TEST_MODE && this._mux && this._muxSession) {
this._mux.resizeWindow?.(this._muxSession.muxName, cols, rows);
// ⚠️ A forced resize at an unchanged size is a device asking for the pane
// back (the Redraw button, a closing pop-out window, the split pane). An
// unchanged pty sends tmux no SIGWINCH, so tmux never counts this client
// as the one used last, and while a `codeman tui` attach keeps the window
// on `latest`, its follow hook (TUI_FOLLOW_HOOKS) hands the window back
// to that terminal at its next key. A one-row nudge first makes this
// client the latest one, as a real resize does. Under `manual` with no
// attach the window ignores the client's pty, so the agent sees nothing.
// Only for a tmux-backed session: on a direct PTY the process is the
// agent itself, which would get two height changes for nothing (and
// every height change costs Claude's inline renderer transcript lines).
if (!dimsChanged && rows > 1 && this._useMux && this._muxSession) {
this.nudgeThenResize(cols, rows);
return;
}
this.ptyProcess.resize(cols, rows);
this.applyResize(cols, rows);
}
}
/** How long tmux gets to read the nudged size before the real one. */
static readonly FORCED_RESIZE_NUDGE_MS = 60;
private applyResize(cols: number, rows: number): void {
if (!IS_TEST_MODE && this._mux && this._muxSession) {
this._mux.resizeWindow?.(this._muxSession.muxName, cols, rows);
}
this.ptyProcess?.resize(cols, rows);
}
private nudgeThenResize(cols: number, rows: number): void {
const revision = this._guardedGeometryRevision;
this.ptyProcess?.resize(cols, rows - 1);
const timer = setTimeout(() => {
// A newer resize won: it set its own size, so this one has nothing left to do.
if (revision !== this._guardedGeometryRevision || !this.ptyProcess) return;
// The pane moves a second time, so guarded input read between the two
// must see a new revision too.
this._guardedGeometryRevision++;
this.applyResize(cols, rows);
}, Session.FORCED_RESIZE_NUDGE_MS);
timer.unref?.();
}
// Legacy method for compatibility with session-manager
async start(): Promise<void> {
this._status = 'idle';
+33 -8
View File
@@ -15,7 +15,8 @@ import { join } from 'node:path';
import { watch as chokidarWatch, type FSWatcher as ChokidarWatcher } from 'chokidar';
import type { TeamConfig, TeamTask, InboxMessage } from './types.js';
import { getErrorMessage, type TeamConfig, type TeamTask, type InboxMessage } from './types.js';
import { closeWatcherOnError } from './utils/close-watcher-on-error.js';
import { LRUMap } from './utils/lru-map.js';
import { TEAM_POLL_INTERVAL_MS, MAX_CACHED_TEAMS, MAX_CACHED_TASKS } from './config/team-config.js';
@@ -36,6 +37,8 @@ export class TeamWatcher extends EventEmitter {
private sessionToTeam: Map<string, string> = new Map();
private teamsWatcher: ChokidarWatcher | null = null;
private tasksWatcher: ChokidarWatcher | null = null;
// Watchers stopped by an error and not yet back for a whole poll: one warning per outage.
private watchersDown = new Set<'teams' | 'tasks'>();
constructor(teamsDir?: string, tasksDir?: string) {
super();
@@ -47,11 +50,28 @@ export class TeamWatcher extends EventEmitter {
start(): void {
if (this.pollTimer) return;
this.poll();
this.pollTimer = setInterval(() => this.poll(), TEAM_POLL_INTERVAL_MS);
this.pollTimer = setInterval(() => {
this.setupFsWatchers(); // re-creates a watcher an error stopped
this.poll();
}, TEAM_POLL_INTERVAL_MS);
this.setupFsWatchers();
}
private watcherStopped(name: 'teams' | 'tasks', err: unknown): void {
if (this.watchersDown.has(name)) return;
this.watchersDown.add(name);
console.warn(`[TeamWatcher] ${name} watcher stopped, relying on polling: ${getErrorMessage(err)}`);
}
/** Creates each watcher that is not running; one still running since the last call ends its outage. */
private setupFsWatchers(): void {
if (this.teamsWatcher) this.watchersDown.delete('teams');
else this.setupTeamsWatcher();
if (this.tasksWatcher) this.watchersDown.delete('tasks');
else this.setupTasksWatcher();
}
private setupTeamsWatcher(): void {
try {
this.teamsWatcher = chokidarWatch(this.teamsDir, {
depth: 2,
@@ -66,13 +86,16 @@ export class TeamWatcher extends EventEmitter {
this.teamsWatcher.on('change', teamsHandler);
this.teamsWatcher.on('unlink', teamsHandler);
this.teamsWatcher.on('unlinkDir', teamsHandler);
this.teamsWatcher.on('error', (err) => {
console.warn('[TeamWatcher] chokidar teams watcher error:', err);
closeWatcherOnError(this.teamsWatcher, (err) => {
this.teamsWatcher = null;
this.watcherStopped('teams', err);
});
} catch (err) {
console.warn('[TeamWatcher] Failed to set up teams chokidar watcher, relying on polling:', err);
this.watcherStopped('teams', err);
}
}
private setupTasksWatcher(): void {
try {
this.tasksWatcher = chokidarWatch(this.tasksDir, {
depth: 1,
@@ -84,11 +107,12 @@ export class TeamWatcher extends EventEmitter {
this.tasksWatcher.on('add', () => this.pollTasks().catch(() => {})); // Ignore - poll errors are non-fatal, next poll will retry
this.tasksWatcher.on('change', () => this.pollTasks().catch(() => {})); // Ignore - poll errors are non-fatal, next poll will retry
this.tasksWatcher.on('error', (err) => {
console.warn('[TeamWatcher] chokidar tasks watcher error:', err);
closeWatcherOnError(this.tasksWatcher, (err) => {
this.tasksWatcher = null;
this.watcherStopped('tasks', err);
});
} catch (err) {
console.warn('[TeamWatcher] Failed to set up tasks chokidar watcher, relying on polling:', err);
this.watcherStopped('tasks', err);
}
}
@@ -113,6 +137,7 @@ export class TeamWatcher extends EventEmitter {
this.taskMtimes.clear();
this.inboxMtimes.clear();
this.sessionToTeam.clear();
this.watchersDown.clear();
}
/** Get all discovered teams */
+217 -95
View File
@@ -22,7 +22,7 @@
*/
import { EventEmitter } from 'node:events';
import { collectDescendants, descendantsInPaneGroup } from './proc-tree.js';
import { collectDescendants, descendantsInPaneGroup, isSignalablePid } from './proc-tree.js';
import {
foreignViewSessionName,
buildForeignDockerViewKillCommand,
@@ -277,19 +277,25 @@ const PANE_LIST_SEP = '|';
/**
* Format string for `tmux list-panes -F`. Keep in sync with {@link parsePaneRows}.
*
* The three `pane_dead*` fields carry the agent-exit signal of Ark0N/Codeman#446.
* The four `pane_dead*` fields carry the agent-exit signal of Ark0N/Codeman#446.
* Appending them is backward compatible in both directions. A tmux that does not
* know a variable substitutes the empty string rather than failing, which is how
* tmux 3.2a answers `#{pane_dead_signal}` (added in 3.4), and the parser reads a
* short row as "pid known, deadness unknown" rather than discarding it.
*
* `#{pane_dead_time}` is what tells one exit from the next. tmux 3.8 prints a
* blank `#{pane_pid}` once a pane's program has exited, so the pid cannot do it
* there, and the time is stamped once per exit, so a respawned pane that exits
* again reads as a new exit even with the same status. The stamp is in whole
* seconds, so two exits with the same status in the same second read as one.
*
* `#{pane_current_path}` comes last on purpose: a directory name may contain the
* separator, and only the final field can absorb it without ambiguity.
*/
const PANE_LIST_FORMAT =
`#{session_name}${PANE_LIST_SEP}#{pane_pid}` +
`${PANE_LIST_SEP}#{pane_dead}${PANE_LIST_SEP}#{pane_dead_status}${PANE_LIST_SEP}#{pane_dead_signal}` +
`${PANE_LIST_SEP}#{pane_current_path}`;
`${PANE_LIST_SEP}#{pane_dead_time}${PANE_LIST_SEP}#{pane_current_path}`;
/**
* 构建 pane 启动前的 nofile 修复命令。
@@ -308,31 +314,41 @@ export function buildNofileLimitCommand(targetLimit = CLAUDE_CODE_NOFILE_LIMIT):
export interface PaneRow {
/** tmux session this pane belongs to. Repeats once per pane of a split session. */
sessionName: string;
/** `#{pane_pid}` — the process tmux started in the pane. */
pid: number;
/**
* `#{pane_pid}` — the process tmux started in the pane. Absent only when tmux
* printed it blank: tmux 3.8 does that once the pane's pty has closed, which
* can be seconds before `#{pane_dead}` turns 1.
*/
pid?: number;
/** `#{pane_dead}` — true for 1, false for 0, undefined when tmux said nothing. */
dead?: boolean;
/** `#{pane_dead_status}` — the exit code, absent when tmux reported none. */
exitStatus?: number;
/** `#{pane_dead_signal}` — the killing signal, absent before tmux 3.4 and when unsignalled. */
exitSignal?: number;
/** `#{pane_dead_time}` — when the program exited (epoch seconds), absent while it runs. */
deadTime?: number;
/** `#{pane_current_path}` — the pane's current directory, absent when tmux reported none. */
currentPath?: string;
}
/**
* One pane-exit reading, with the pane pid that produced it.
* One pane-exit reading, with the pane pid and exit time that identify it.
*
* The pid never leaves this module. It is what distinguishes "the same dead
* pane, seen again" from "a second command in the same pane that also exited
* with the same status", so the `at` stamp can hold across the first and must
* not across the second. {@link PaneExit} itself stays free of it: the pid on
* the session record is the attach client's, and a second pid there would
* invite exactly the confusion Ark0N/Codeman#446 is about.
* Neither leaves this module. Together they distinguish "the same dead pane,
* seen again" from "a second command in the same pane that also exited with
* the same status", so the `at` stamp can hold across the first and must not
* across the second. Either may be absent: tmux 3.8 blanks the pid of a dead
* pane, and a tmux that does not know `#{pane_dead_time}` prints it empty.
* {@link PaneExit} itself stays free of both: the pid on the session record is
* the attach client's, and a second pid there would invite exactly the
* confusion Ark0N/Codeman#446 is about.
*/
export interface PaneExitObservation {
/** `#{pane_pid}` of the pane this reading came from. */
panePid: number;
/** `#{pane_pid}` of the pane this reading came from, when tmux reported one. */
panePid?: number;
/** `#{pane_dead_time}` of the exit this reading saw, when tmux reported one. */
deadTime?: number;
/** What to publish on the session record. */
exit: PaneExit;
}
@@ -363,7 +379,13 @@ function paneField(fields: string[], index: number): number | undefined {
* into one row per pane, in tmux's own order. Exported for unit testing.
*
* - Skips empty lines and lines without the separator.
* - Skips entries with a non-numeric pid or empty name.
* - Skips entries with an empty name, and entries where tmux answered neither a
* pid nor `#{pane_dead}`, which is a bad read. tmux 3.8 blanks `#{pane_pid}`
* as soon as the pane's pty closes, while `#{pane_dead}` turns 1 only once
* tmux has collected the exit status. Collecting it took several seconds for
* some exits (measured on tmux 3.4, where the pid itself stays). A row with
* no pid and `pane_dead` 0 is that window, and dropping it would report a
* live session as gone.
* - Leaves every field after the pid undefined when it is blank or absent, so a
* row from an older tmux still yields its pid.
*/
@@ -374,22 +396,56 @@ export function parsePaneRows(output: string): PaneRow[] {
if (!line.includes(PANE_LIST_SEP)) continue;
const fields = line.split(PANE_LIST_SEP);
const sessionName = fields[0];
const pid = parseInt(fields[1] ?? '', 10);
if (!sessionName || Number.isNaN(pid)) continue;
const deadFlag = fields[2];
const dead = deadFlag === '1' ? true : deadFlag === '0' ? false : undefined;
const pid = paneField(fields, 1);
if (!sessionName || (pid === undefined && dead === undefined)) continue;
rows.push({
sessionName,
pid,
dead: deadFlag === '1' ? true : deadFlag === '0' ? false : undefined,
...(pid !== undefined ? { pid } : {}),
dead,
exitStatus: paneField(fields, 3),
exitSignal: paneField(fields, 4),
// Everything after the fifth separator, so a path containing `|` stays whole.
currentPath: fields.slice(5).join(PANE_LIST_SEP) || undefined,
deadTime: paneField(fields, 5),
// Everything after the sixth separator, so a path containing `|` stays whole.
currentPath: fields.slice(6).join(PANE_LIST_SEP) || undefined,
});
}
return rows;
}
/** What {@link TmuxManager.killSession} reads about a pane before it signals anything. */
export interface PaneKillRead {
/**
* The pane's program exited, so no process is left to signal: `#{pane_dead}`
* was 1 AND either the pid was blank or `#{pane_dead_time}` was set.
*/
dead: boolean;
/** `#{pane_pid}`, or null when tmux printed none (tmux 3.8 for a dead pane) or the read failed. */
pid: number | null;
}
/**
* Parse the kill path's `#{pane_dead}|#{pane_pid}|#{pane_dead_time}` read.
* Exported for unit testing.
*
* Only an explicit `1` can be dead, and only with a second sign of an exit.
* Before tmux 3.7 `#{pane_dead}` means only that the pane's pty is closed, so
* a program that closed its tty and ignores SIGHUP reads as dead while it
* still runs, with its pid printed and no exit time. Trusting the flag alone
* would leave that program running after a close that used to kill it. tmux
* 3.8 blanks the pid of an exited program and stamps `#{pane_dead_time}`, so
* either one confirms the exit. Anything else keeps the old behaviour of
* signalling the pid (or the recorded one when tmux printed none).
*/
export function parsePaneKillRead(output: string): PaneKillRead {
const [deadFlag = '', pidField = '', deadTimeField = ''] = output.trim().split(PANE_LIST_SEP);
const parsedPid = parseInt(pidField, 10);
const pid = Number.isNaN(parsedPid) ? null : parsedPid;
const exited = pid === null || !Number.isNaN(parseInt(deadTimeField, 10));
return { dead: deadFlag === '1' && exited, pid };
}
/**
* Decide, from every pane tmux listed, which tmux sessions have an exited agent.
* Exported for unit testing. Returns one entry per session with a known answer;
@@ -420,7 +476,8 @@ export function derivePaneExits(rows: PaneRow[], now: number): Map<string, PaneE
if (panesPerSession.get(row.sessionName) !== 1) continue;
if (row.dead !== true) continue;
exits.set(row.sessionName, {
panePid: row.pid,
...(row.pid !== undefined ? { panePid: row.pid } : {}),
...(row.deadTime !== undefined ? { deadTime: row.deadTime } : {}),
exit: {
...(row.exitStatus !== undefined ? { status: row.exitStatus } : {}),
...(row.exitSignal !== undefined ? { signal: row.exitSignal } : {}),
@@ -2868,24 +2925,26 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
}
/**
* {@link getPanePid} without blocking the event loop, for the kill path: a close
* must not stall every other session's I/O while tmux answers.
* The kill path's pane read: the pane pid and whether the pane is dead, in one
* `display-message`, without blocking the event loop (a close must not stall
* every other session's I/O while tmux answers). A failed read answers
* `{ dead: false, pid: null }`, so the caller falls back to the recorded pid
* exactly as before.
*/
private async getPanePidAsync(muxName: string): Promise<number | null> {
if (IS_TEST_MODE) return 99999;
private async readPaneForKill(muxName: string): Promise<PaneKillRead> {
if (IS_TEST_MODE) return { dead: false, pid: 99999 };
if (!isValidMuxName(muxName)) {
console.error('[TmuxManager] Invalid session name in getPanePidAsync:', muxName);
return null;
console.error('[TmuxManager] Invalid session name in readPaneForKill:', muxName);
return { dead: false, pid: null };
}
try {
const { stdout } = await execAsync(`${this.tmux()} display-message -t "${muxName}" -p '#{pane_pid}'`, {
encoding: 'utf-8',
timeout: EXEC_TIMEOUT_MS,
});
const pid = parseInt(stdout.trim(), 10);
return Number.isNaN(pid) ? null : pid;
const { stdout } = await execAsync(
`${this.tmux()} display-message -t "${muxName}" -p '#{pane_dead}${PANE_LIST_SEP}#{pane_pid}${PANE_LIST_SEP}#{pane_dead_time}'`,
{ encoding: 'utf-8', timeout: EXEC_TIMEOUT_MS }
);
return parsePaneKillRead(stdout);
} catch {
return null;
return { dead: false, pid: null };
}
}
@@ -3148,6 +3207,8 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
* its process-group and tmux fallbacks.
*/
private async getChildPidsFresh(pid: number): Promise<number[]> {
// The children of pid 0 or 1 are the whole machine (see isSignalablePid).
if (!isSignalablePid(pid)) return [];
let byParent: ReadonlyMap<number, readonly number[]>;
try {
byParent = await Promise.race([
@@ -3205,6 +3266,19 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
}
}
/**
* The one way this class signals a process. Refuses what is not a session's process
* (see {@link isSignalablePid}); a negative `pid` is the process group, so it is judged
* by its absolute value and `-1` (everything) and `-0` (our own group) are refused too.
*/
private signalProcess(pid: number, signal: 'SIGTERM' | 'SIGKILL'): void {
if (!isSignalablePid(Math.abs(pid))) {
console.error(`[TmuxManager] Refusing to send ${signal} to pid ${pid}`);
return;
}
process.kill(pid, signal);
}
// Check if a process is still alive. Signal decisions only: an unreaped zombie
// counts here, so its process group still gets the SIGKILL below. The WAITS use
// waitForProcessesExit(), which counts a zombie as exited.
@@ -3226,6 +3300,62 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
return stillAlive.length === 0;
}
/**
* Strategies 1 and 2 of {@link killSession}: SIGTERM then SIGKILL the pane
* process's killable descendants, then its process group. Every pid it
* targets is appended to `allPids` for the final verify. Only ever called
* with the pid of a LIVE pane.
*/
private async killPaneProcessTree(mode: SessionMode, panePid: number, allPids: number[]): Promise<void> {
allPids.push(panePid);
// Strategy 1: Kill all child processes recursively (but never a shared daemon the
// pane's CLI started for every session of that CLI: see killableDescendants)
let childPids = await this.killableDescendants(mode, panePid, await this.getChildPidsFresh(panePid));
if (childPids.length > 0) {
console.log(`[TmuxManager] Found ${childPids.length} child processes to kill`);
allPids.push(...childPids);
for (const childPid of [...childPids].reverse()) {
if (this.isProcessAlive(childPid)) {
try {
this.signalProcess(childPid, 'SIGTERM');
} catch {
// Process may already be dead
}
}
}
// Most children are gone within a few ms; the re-scan below still runs, to
// catch anything spawned since the first one.
await waitForProcessesExit(childPids, { timeoutMs: TMUX_KILL_WAIT_MS });
childPids = await this.killableDescendants(mode, panePid, await this.getChildPidsFresh(panePid));
for (const childPid of childPids) {
if (this.isProcessAlive(childPid)) {
try {
this.signalProcess(childPid, 'SIGKILL');
} catch {
// Process already terminated
}
}
}
}
// Strategy 2: Kill the entire process group
if (this.isProcessAlive(panePid)) {
try {
this.signalProcess(-panePid, 'SIGTERM');
await waitForProcessesExit([panePid], { timeoutMs: GRACEFUL_SHUTDOWN_WAIT_MS });
if (this.isProcessAlive(panePid)) {
this.signalProcess(-panePid, 'SIGKILL');
}
} catch {
// Process group may not exist or already terminated
}
}
}
/**
* Kill a tmux session and all its child processes.
* Uses a 4-strategy approach (children → process group → tmux kill → SIGKILL).
@@ -3346,58 +3476,34 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
return true;
}
// Get current PID (may have changed)
const currentPid = (await this.getPanePidAsync(session.muxName)) || session.pid;
// Get current PID (may have changed). A dead pane has no process left to
// signal, and the pid on the record is the one that exited, which the OS may
// since have handed to an unrelated process: walking its tree or signalling
// it could kill that. tmux 3.8 prints no pid for a dead pane, so without this
// check the fallback below would pick that stale pid every time. Only the
// kill-session below runs for it. A blank pid with `#{pane_dead}` still 0
// (tmux 3.8, pty closed, exit not collected yet) keeps the fallback: tmux
// has not reaped the pane's process yet. That holds when the recorded pid is
// the one the pane was started with; a hand-run `respawn-pane` breaks it.
// A pid of 0 is no pid either: tmux prints it for an empty active pane
// (`split-window ''`) before 3.8, beside a session's running agent, so
// `||` falls back to the recorded pid as master always did. Nothing is
// ever signalled for 0 or 1 (isSignalablePid): then only tmux is asked to
// close the session.
const pane = await this.readPaneForKill(session.muxName);
const candidatePid = pane.dead ? null : pane.pid || session.pid;
const currentPid = candidatePid !== null && isSignalablePid(candidatePid) ? candidatePid : null;
console.log(`[TmuxManager] Killing session ${session.muxName} (PID ${currentPid})`);
console.log(
currentPid !== null
? `[TmuxManager] Killing session ${session.muxName} (PID ${currentPid})`
: pane.dead
? `[TmuxManager] Killing session ${session.muxName} (pane dead, PID ${session.pid} not signalled)`
: `[TmuxManager] Killing session ${session.muxName} (no usable pid, recorded ${session.pid}, nothing signalled)`
);
const allPids: number[] = [currentPid];
// Strategy 1: Kill all child processes recursively (but never a shared daemon the
// pane's CLI started for every session of that CLI: see killableDescendants)
let childPids = await this.killableDescendants(session.mode, currentPid, await this.getChildPidsFresh(currentPid));
if (childPids.length > 0) {
console.log(`[TmuxManager] Found ${childPids.length} child processes to kill`);
allPids.push(...childPids);
for (const childPid of [...childPids].reverse()) {
if (this.isProcessAlive(childPid)) {
try {
process.kill(childPid, 'SIGTERM');
} catch {
// Process may already be dead
}
}
}
// Most children are gone within a few ms; the re-scan below still runs, to
// catch anything spawned since the first one.
await waitForProcessesExit(childPids, { timeoutMs: TMUX_KILL_WAIT_MS });
childPids = await this.killableDescendants(session.mode, currentPid, await this.getChildPidsFresh(currentPid));
for (const childPid of childPids) {
if (this.isProcessAlive(childPid)) {
try {
process.kill(childPid, 'SIGKILL');
} catch {
// Process already terminated
}
}
}
}
// Strategy 2: Kill the entire process group
if (this.isProcessAlive(currentPid)) {
try {
process.kill(-currentPid, 'SIGTERM');
await waitForProcessesExit([currentPid], { timeoutMs: GRACEFUL_SHUTDOWN_WAIT_MS });
if (this.isProcessAlive(currentPid)) {
process.kill(-currentPid, 'SIGKILL');
}
} catch {
// Process group may not exist or already terminated
}
}
const allPids: number[] = [];
if (currentPid !== null) await this.killPaneProcessTree(session.mode, currentPid, allPids);
// Strategy 3: Kill tmux session by name (guard the name before it reaches the shell).
// Async: tmux takes tens of ms to tear a session down, and execSync held the
@@ -3439,9 +3545,9 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
}
// Strategy 4: Direct kill by PID as final fallback
if (this.isProcessAlive(currentPid)) {
if (currentPid !== null && this.isProcessAlive(currentPid)) {
try {
process.kill(currentPid, 'SIGKILL');
this.signalProcess(currentPid, 'SIGKILL');
} catch {
// Already dead
}
@@ -3502,7 +3608,10 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
// socket a session's location is a constant, so there is no per-session
// socket tag to reconcile and no cross-socket ambiguity that could mark a
// live session dead (the root cause of vanished/duplicate tabs).
let active: Map<string, number>;
// Every tmux session on the socket, with its pane pid when tmux printed one.
// A session whose only pane is dead or closing is still listed, with no pid (tmux 3.8
// blanks it): the session exists, so it must not be reported as gone.
let active: Map<string, number | undefined>;
const paneDirs = new Map<string, string>();
try {
const output = execSync(`${this.tmux()} list-panes -a -F '${PANE_LIST_FORMAT}' 2>/dev/null || true`, {
@@ -3512,7 +3621,10 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
// Not trimmed: the directory is the last field, so trimming would cut a
// trailing space off the last row's path. parsePaneRows skips empty lines.
const rows = parsePaneRows(output);
active = new Map(rows.map((row) => [row.sessionName, row.pid]));
active = new Map();
for (const row of rows) {
if (row.pid !== undefined || !active.has(row.sessionName)) active.set(row.sessionName, row.pid);
}
// A discovered session's directory, from its first pane with a usable path.
// The path is admitted only if it passes the same check createSession and
// respawnPane apply, since it was set by whoever owns the pane, not by us.
@@ -3547,10 +3659,13 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
// Check tracked sessions against the live pane list.
for (const [sessionId, session] of this.sessions) {
const pid = active.get(session.muxName);
if (pid !== undefined) {
if (active.has(session.muxName)) {
alive.push(sessionId);
if (pid !== session.pid) session.pid = pid;
// No pid is a dead or closing pane (tmux 3.8 blanks it once the pty
// closes): keep the last one known, which is what tmux itself reported
// for such a pane before 3.8.
const pid = active.get(session.muxName);
if (pid !== undefined && pid !== session.pid) session.pid = pid;
} else {
dead.push(sessionId);
this.sessions.delete(sessionId);
@@ -3570,6 +3685,9 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
for (const [sessionName, pid] of active) {
if (!sessionName.startsWith('codeman-') && !sessionName.startsWith('claudeman-')) continue;
// A session with no live pane has no pid to record, and a made-up one would
// reach killSession()'s process-tree walk. Left undiscovered, as before.
if (pid === undefined) continue;
// Only admit names that pass the safe-name pattern. A foreign process on the
// shared `tmux -L codeman` socket could create a `codeman-…` session whose name
// contains shell metacharacters; rejecting it here keeps it out of this.sessions
@@ -3890,9 +4008,12 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
*
* An entry keeps the `at` of the FIRST read that saw that exit, so the stamp
* says when the agent was found gone rather than when the last poll ran. A
* changed status, a changed signal, or a different pane pid all start a new
* observation — the pid is what catches a second command in the same pane
* that happened to exit the same way.
* changed status, a changed signal, a different pane pid or a different exit
* time all start a new observation — the pid and the time are what catch a
* second command in the same pane that happened to exit the same way (the
* time alone on tmux 3.8, which blanks a dead pane's pid). `#{pane_dead_time}`
* is stamped to the second, so two exits with the same status in the same
* second read as one there.
*
* The same rule decides the read count: a repeat of the stored exit adds one,
* and anything that starts a new observation starts the count again at 1.
@@ -3906,6 +4027,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
const sameExit =
prev !== undefined &&
prev.panePid === next.panePid &&
prev.deadTime === next.deadTime &&
prev.exit.status === next.exit.status &&
prev.exit.signal === next.exit.signal;
this.paneExits.set(muxName, sameExit ? { ...prev, reads: prev.reads + 1 } : { ...next, reads: 1 });
+10
View File
@@ -153,6 +153,16 @@ export function restrictTmuxPrefixTable(tmux: string, run: TmuxRunner = defaultR
let listing: string | null;
try {
listing = run(`${tmux} list-keys -T prefix`);
// ⚠️ tmux 3.7 through 3.7c (fixed in 3.8) print NOTHING on stdout for
// `list-keys -T prefix` when the table holds exactly one binding (the line goes
// to a status message instead), which is the shape this function leaves behind: read blank as "ask the full listing" and keep
// only its prefix-table lines, or every call would reset an already-reduced table.
if (!listing.trim()) {
listing = run(`${tmux} list-keys`)
.split('\n')
.filter((line) => PREFIX_LINE.test(line.trim()))
.join('\n');
}
} catch {
listing = null; // an empty table makes list-keys fail on some tmux builds
}
+91 -14
View File
@@ -1,6 +1,6 @@
/**
* @fileoverview `codeman tui`: the full-screen dashboard plus the two
* non-interactive fast paths (`--list`, `<n>`).
* non-interactive fast paths (`--list`, `<n|name>`).
*
* This is the IO half of `src/tui/`: it owns the terminal, the timers, stdin
* and the tmux handoff. Every decision it makes that can be stated as a
@@ -638,10 +638,15 @@ export async function beginAttachHandoff(
const banner = bannerFor(muxName, label);
const dressed: Array<{ muxName: string; options: TuiSessionOptions }> = [];
const resized: Array<{ muxName: string; sizing: TuiWindowSizing }> = [];
const followTyping: string[] = [];
const targets = new Map<string, string>([[muxName, label]]);
for (const tab of tabs.slice(0, 9)) {
if (tab.muxName && !targets.has(tab.muxName)) targets.set(tab.muxName, tab.label);
}
// A follow hook a killed TUI left behind would undo the presize below, so
// leaks go first. The dashboard also sweeps at startup; this covers
// `codeman tui <n>`, which has no dashboard.
await client.clearLeakedFollowTyping().catch(() => 0);
for (const [target, targetLabel] of targets) {
const snapshot = await client.readSessionOptions(target, Object.keys(banner));
if (snapshot) dressed.push({ muxName: target, options: snapshot });
@@ -659,6 +664,16 @@ export async function beginAttachHandoff(
// let the session we are actually opening follow the terminal live.
if (cols && rows && rows > 1) await client.presizeWindow(target, cols, rows - 1);
if (target === muxName) await client.followAttachingClient(target);
// ⚠️ `latest` does not hold for the whole attach. A browser that opens or
// resizes this session mid-attach goes through Codeman's `resize-window`,
// which puts the window back on `manual` at the BROWSER's size: a phone
// opening it left the terminal showing a phone-sized pane, and typing or
// pasting here changed nothing until a detach and a fresh attach. The
// follow hook (TUI_FOLLOW_HOOKS) puts `latest` back when this terminal is
// used again, so the window follows whichever client was used last. It
// needs the tty to name its owner, like the switch keys, so without one
// the attach keeps the old behaviour.
if (guarded && (await client.armFollowTyping(target, tty as string))) followTyping.push(target);
}
// ⚠️ Armed LAST, as the final tmux call before the caller's `spawnSync`. The
// hook is one-shot for this tty, so a TUI killed between arming and attaching
@@ -676,6 +691,9 @@ export async function beginAttachHandoff(
if (tty && isTuiClientTty(tty)) await client.disarmTuiSwitchGuard(tty);
if (oneKey) await client.unbindDetachKey(ONE_KEY_DETACH, 'root');
if (claimed && alias) await client.unbindDetachKey(alias);
// The follow hook before the size, so nothing of this attach acts on
// the window once the restore below has re-pinned the browser's size.
for (const target of followTyping) await client.disarmFollowTyping(target, tty as string);
// Options first, then the size: dropping the status bar gives its row
// back to the pane, and the resize is what re-pins the browser's
// authority over the window.
@@ -1265,6 +1283,7 @@ class TuiApp {
// Fire and forget: a bar stranded by a previous run is cosmetic, so it must
// never delay the first frame or fail a start.
void this.client.clearLeakedAttachBanners().catch(() => undefined);
void this.client.clearLeakedFollowTyping().catch(() => undefined);
return new Promise<number>((resolve) => {
this.resolveExit = resolve;
@@ -2643,7 +2662,7 @@ export async function runTui(options: TuiRunOptions = {}): Promise<number> {
if (!stdout.isTTY || !stdin.isTTY) {
process.stderr.write(
`${palette.err('codeman tui needs an interactive terminal.')}\n` +
`Use ${palette.info('codeman tui --list')} for a plain list, or ${palette.info('codeman tui <n>')} to attach.\n`
`Use ${palette.info('codeman tui --list')} for a plain list, or ${palette.info('codeman tui <n|name>')} to attach.\n`
);
return 1;
}
@@ -2689,17 +2708,72 @@ export async function runTuiList(options: TuiRunOptions = {}): Promise<number> {
}
}
/** What `codeman tui <session>` points at, resolved against one snapshot of the list. */
export type TuiAttachTarget =
| { kind: 'row'; row: TuiRow }
/** A number with no row, or a name nothing in the list carries. */
| { kind: 'none' }
/** Several LIVE sessions carry the name; `positions` are their `--list` numbers. */
| { kind: 'ambiguous'; positions: number[] }
/** Only a finished (RECENT) row carries the name: nothing to attach to. */
| { kind: 'finished' };
/**
* `codeman tui <n>`: attach straight to the nth row of `--list`. No screen setup
* at all, so it is as fast as the API call it makes.
* Resolve `codeman tui <session>` against the rows `--list` prints.
*
* Digits only is a position, exactly as before names were accepted. Anything else
* is a session name, matched exactly (case-sensitive) and only against the
* session's name, never its folder or a prompt. Session names are not unique in
* Codeman, so more than one LIVE match refuses rather than guessing; a RECENT row
* is history with no pane, so it never counts as a live match.
*/
export async function runTuiAttach(position: number, options: TuiRunOptions = {}): Promise<number> {
export function resolveAttachTarget(rows: readonly TuiRow[], target: number | string): TuiAttachTarget {
if (typeof target === 'number' || /^\d+$/.test(target)) {
const row = rows[Math.trunc(Number(target)) - 1];
return row ? { kind: 'row', row } : { kind: 'none' };
}
const positions: number[] = [];
let finished = false;
rows.forEach((row, index) => {
if (row.session.name !== target) return;
if (row.group === 'recent') finished = true;
else positions.push(index + 1);
});
if (positions.length === 1) return { kind: 'row', row: rows[positions[0] - 1] };
if (positions.length > 1) return { kind: 'ambiguous', positions };
return finished ? { kind: 'finished' } : { kind: 'none' };
}
/** The stderr text for a target that resolved to no row, ending in a newline. */
export function attachTargetError(
resolved: Exclude<TuiAttachTarget, { kind: 'row' }>,
target: number | string
): string {
const list = palette.info('codeman tui --list');
switch (resolved.kind) {
case 'ambiguous':
return (
`${palette.err(`${resolved.positions.length} live sessions are named ${target} (${resolved.positions.join(', ')} in the list)`)}\n` +
`Attach by number instead: ${palette.info(`codeman tui ${resolved.positions[0]}`)}, or run ${list}.\n`
);
case 'finished':
return `${palette.err(`there is no live session named ${target}, only a finished one`)}\nRun ${list} to see the live ones.\n`;
case 'none':
return typeof target === 'number' || /^\d+$/.test(target)
? `${palette.err(`there is no session ${target}`)}\nRun ${list} to see the numbers.\n`
: `${palette.err(`there is no session named ${target}`)}\nNames match exactly. Run ${list} and attach by number instead.\n`;
}
}
/**
* `codeman tui <session>`: attach straight to a row of `--list`, by its number or
* by its session name. No screen setup at all, so it is as fast as the API call
* it makes. The target is resolved before the terminal check, so a script learns
* that a name does not exist (or is ambiguous) without needing a TTY.
*/
export async function runTuiAttach(target: number | string, options: TuiRunOptions = {}): Promise<number> {
const stdin = options.stdin ?? process.stdin;
const stdout = options.stdout ?? process.stdout;
if (!stdout.isTTY || !stdin.isTTY) {
process.stderr.write(`${palette.err('attaching needs an interactive terminal.')}\n`);
return 1;
}
const env = options.env ?? process.env;
const client = options.client ?? new TuiClient();
try {
@@ -2712,11 +2786,14 @@ export async function runTuiAttach(position: number, options: TuiRunOptions = {}
process.stderr.write(authHint());
return 1;
}
const row = state.rows[Math.trunc(position) - 1];
if (!row) {
process.stderr.write(
`${palette.err(`there is no session ${position}`)}\nRun ${palette.info('codeman tui --list')} to see the numbers.\n`
);
const resolved = resolveAttachTarget(state.rows, target);
if (resolved.kind !== 'row') {
process.stderr.write(attachTargetError(resolved, target));
return 1;
}
const row = resolved.row;
if (!stdout.isTTY || !stdin.isTTY) {
process.stderr.write(`${palette.err('attaching needs an interactive terminal.')}\n`);
return 1;
}
const plan = planAttach(row.session.muxName, {
+327 -4
View File
@@ -507,6 +507,113 @@ export function tuiSwitchAttachHook(tty: string): string {
);
}
/**
* Session option naming the tty of the `codeman tui` attach that owns the
* window size of this session. The follow hook below reads it, so a hook whose
* owner is gone does nothing.
*/
export const TUI_FOLLOW_OWNER = '@codeman-tui-follow';
/**
* Session option holding the pid of the `codeman tui` process that set
* `TUI_FOLLOW_OWNER`. The startup sweep reads it to tell a leak from a live
* attach. A tty cannot do that: Linux hands out the lowest free pty, so a new
* terminal (or a browser tab's attach client) usually gets the number of the
* one that just closed.
*/
export const TUI_FOLLOW_PID = '@codeman-tui-follow-pid';
/** The event `TUI_FOLLOW_HOOKS` hooks, without its index. */
const FOLLOW_HOOK_EVENT = 'client-active';
/**
* The session hook that keeps a window following the attach's terminal, the
* way plain tmux follows whichever client was used last.
*
* Why it is needed: the attach sets `window-size latest`, but Codeman's web
* resize (`resizeWindow()` in tmux-manager.ts) runs `resize-window`, and
* Codeman's own attach (`setManualWindowSize()`) sets `manual`. Either puts
* the window back on `manual` at the browser's size. A phone opening the
* session mid-attach therefore pinned the window to the phone, and typing or
* pasting in the terminal changed nothing until a detach and a fresh attach.
*
* `client-active[91]` puts `latest` back when the TUI's own client becomes the
* latest one again: typing, pasting or resizing the terminal after another
* client was used (measured on tmux 3.8). A browser resize makes the tab's
* client the latest one, because Codeman resizes that client's pty first. A
* forced resize at an unchanged size (the browser's Redraw, a closing pop-out
* window, the split pane) would not, so `Session.resize()` nudges the pty
* there; see its comment. The window then stays on `manual` at the browser's
* size until the terminal is used again.
*
* Cost: the first browser resize after the terminal was used changes the
* agent's height twice where master changes it once. The window is on
* `latest` then, so the tab's pty resize moves it (one row short, for the
* attach's status bar), and `resize-window` moves it again. Later resizes
* from the same tab find the window on `manual` and cost one change, as
* without an attach. Height changes cost Claude's inline renderer transcript
* lines (#672). A second hook on `after-resize-window` used to keep the
* window on `latest` through every browser resize, which cost three.
*
* Indexed so it does not replace a user's own hook, next to the switch
* guard's `[90]`, and set per session (`set-hook -t`), never globally.
*
* ⚠️ Constant string: the tty is read from `TUI_FOLLOW_OWNER` when the hook
* runs, never interpolated. And no `-t` on `set-window-option`: tmux parses a
* hook's command when the hook is set, and an unquoted `#{session_name}`
* there starts a comment (measured: "-t expects an argument"). Without `-t`
* the command targets the window the hook fired for.
*/
export const TUI_FOLLOW_HOOKS: Readonly<Record<string, string>> = {
[`${FOLLOW_HOOK_EVENT}[91]`]: `if-shell -F "#{==:#{client_tty},#{${TUI_FOLLOW_OWNER}}}" "set-window-option window-size latest"`,
};
/** What `show-hooks` lists for one follow hook. */
export interface FollowHookState {
/** Our index: `ours`, `theirs` (a hook of the user's), or absent. */
slot?: 'ours' | 'theirs';
/** Entries at any other index of the same event. */
others: number;
}
/**
* For each follow hook name, what a `show-hooks` listing holds for its event:
* our index and how many other entries there are.
*/
export function parseFollowHooks(stdout: string): Record<string, FollowHookState> {
const found: Record<string, FollowHookState> = {};
for (const name of Object.keys(TUI_FOLLOW_HOOKS)) found[name] = { others: 0 };
for (const line of stdout.split('\n')) {
const text = line.trim();
for (const name of Object.keys(TUI_FOLLOW_HOOKS)) {
const event = name.slice(0, name.indexOf('['));
if (text.startsWith(`${name} `)) {
found[name].slot = text.includes(`#{${TUI_FOLLOW_OWNER}}`) ? 'ours' : 'theirs';
} else if (text.startsWith(`${event}[`)) {
found[name].others += 1;
}
}
}
return found;
}
/** Between the global and the session listing in one `show-hooks` read. */
const FOLLOW_READ_SPLIT = '@@codeman-follow-split@@';
/** Sessions this process armed, by socket: the sweep never takes them for a leak. */
const armedHere = new Set<string>();
/** True when `pid` is a process of this user other than this one. */
function isOtherLiveProcess(pid: number): boolean {
if (!Number.isInteger(pid) || pid <= 1 || pid === process.pid) return false;
try {
process.kill(pid, 0);
return true;
} catch (err) {
return (err as NodeJS.ErrnoException).code === 'EPERM';
}
}
const LEGACY_TUI_SWITCH = /^switch-client -t (\S+?)(?: \\; set-window-option -t \1 window-size latest)?$/;
/**
@@ -991,6 +1098,19 @@ export class TuiClient {
return null;
}
/**
* One key table as `list-keys` prints it. ⚠️ tmux 3.7 through 3.7c (fixed in 3.8)
* print NOTHING on stdout for `list-keys -T <table>` when the table holds exactly
* one binding (the line goes to a status message instead), which is the shape Codeman reduces the prefix table to. So a
* blank answer is retried as the full listing: every line there names its table,
* and both parsers already filter on it.
*/
private async listKeyTable(table: TuiKeyTable): Promise<string> {
const { stdout } = await this.exec('tmux', ['-L', this.socket, 'list-keys', '-T', table]);
if (stdout.trim()) return stdout;
return (await this.exec('tmux', ['-L', this.socket, 'list-keys'])).stdout;
}
/**
* The key that detaches, straight from tmux's own key table. Key tables are
* server-global, so unlike the prefix this takes no session. A failure is
@@ -998,8 +1118,7 @@ export class TuiClient {
*/
async readDetachKey(): Promise<string | null> {
try {
const { stdout } = await this.exec('tmux', ['-L', this.socket, 'list-keys', '-T', 'prefix']);
return parseDetachKey(stdout);
return parseDetachKey(await this.listKeyTable('prefix'));
} catch {
return null;
}
@@ -1012,8 +1131,7 @@ export class TuiClient {
*/
async readPrefixBinding(key: string, table: TuiKeyTable = 'prefix'): Promise<string | null> {
try {
const { stdout } = await this.exec('tmux', ['-L', this.socket, 'list-keys', '-T', table]);
return parsePrefixBinding(stdout, key, table);
return parsePrefixBinding(await this.listKeyTable(table), key, table);
} catch {
return null;
}
@@ -1161,6 +1279,211 @@ export class TuiClient {
}
}
/**
* Make one session's window follow this terminal for the attach: record the
* tty and this process as the owner, then install `TUI_FOLLOW_HOOKS`. Best
* effort, like the rest of the attach dressing: false leaves the attach as it
* was before the hook existed (the window follows the terminal until the web
* UI resizes it).
*
* Nothing is installed when the user has a hook of their own at our index,
* or a GLOBAL hook on the same event: a session-level array hides the global
* one for that session (measured: a global hook stopped firing during the
* attach). An owner already recorded is replaced: it is a TUI killed before
* its restore, or a second TUI on the same session, and the newest attach is
* the one in front of the user.
*
* One tmux call reads, one writes, so nine tabs stay quick to attach.
*
* ⚠️ A half-done arm is undone before answering false, because `restore()`
* only disarms what armed. tmux before 3.3 has no `client-active` hook, so
* there the owner is set and the hook is refused; left alone, the owner
* would stay on the session for good.
*/
async armFollowTyping(muxName: string, clientTty: string): Promise<boolean> {
if (!MUX_NAME_PATTERN.test(muxName) || !isTuiClientTty(clientTty)) return false;
try {
const { global, session } = await this.readFollowHooks(muxName);
for (const name of Object.keys(TUI_FOLLOW_HOOKS)) {
if (session[name].slot === 'theirs') return false;
if (global[name].slot !== undefined || global[name].others > 0) return false;
}
} catch {
return false;
}
// Recorded before the first write, so a sweep running concurrently (it is
// fire-and-forget at startup) never takes this arm for a leak.
armedHere.add(this.armedKey(muxName));
const args = [
'set-option',
'-t',
muxName,
TUI_FOLLOW_OWNER,
clientTty,
';',
'set-option',
'-t',
muxName,
TUI_FOLLOW_PID,
String(process.pid),
];
for (const [name, command] of Object.entries(TUI_FOLLOW_HOOKS)) {
args.push(';', 'set-hook', '-t', muxName, name, command);
}
try {
await this.exec('tmux', ['-L', this.socket, ...args]);
return true;
} catch {
armedHere.delete(this.armedKey(muxName));
try {
await this.dropFollowTyping(muxName);
} catch {
/* the session is gone, or tmux is: nothing is left to undo then */
}
return false;
}
}
/**
* Undo `armFollowTyping`, but only while this tty is still the owner: a
* second TUI that attached later owns the session now.
*/
async disarmFollowTyping(muxName: string, clientTty: string): Promise<void> {
if (!MUX_NAME_PATTERN.test(muxName) || !isTuiClientTty(clientTty)) return;
try {
const { stdout } = await this.exec('tmux', [
'-L',
this.socket,
'show-options',
'-t',
muxName,
';',
'show-hooks',
'-t',
muxName,
]);
// Hook lines never start with `@`, so the option parse ignores them.
if (parseSessionOptions(stdout, [TUI_FOLLOW_OWNER])[TUI_FOLLOW_OWNER] !== clientTty) return;
await this.dropFollowTyping(muxName, parseFollowHooks(stdout));
} catch {
/* the session may be gone (the user exited the agent from inside the attach) */
} finally {
armedHere.delete(this.armedKey(muxName));
}
}
/**
* Remove follow hooks a previous TUI never got to take down.
*
* Same leak as the banners: a terminal that dies while attached (a closed
* window, a dropped SSH) never reaches `restore()`, and its owner stays
* recorded, so the window followed whatever client a pty reusing that
* number belonged to. Left alone the hook also undoes `presizeWindow()` on
* the next attach.
*
* A session is left alone when this process armed it, or when the pid
* recorded with the owner is another live process (a second TUI mid-attach).
* Everything else with an owner is a leak, whatever its tty: Linux reuses
* pty numbers, so a tty proves nothing.
*
* Runs at TUI startup and again before each attach dresses its sessions, so
* `codeman tui <n>` gets it too. One tmux call lists every owner.
*/
async clearLeakedFollowTyping(): Promise<number> {
let rows: string[];
try {
const { stdout } = await this.exec('tmux', [
'-L',
this.socket,
'list-sessions',
'-F',
`#{session_name}\t#{${TUI_FOLLOW_OWNER}}\t#{${TUI_FOLLOW_PID}}`,
]);
rows = stdout.split('\n');
} catch {
return 0;
}
let cleared = 0;
for (const row of rows) {
const [name = '', owner = '', pid = ''] = row.trim().split('\t');
if (!MUX_NAME_PATTERN.test(name) || !owner) continue;
if (armedHere.has(this.armedKey(name))) continue;
if (isOtherLiveProcess(Number(pid))) continue;
try {
await this.dropFollowTyping(name);
cleared += 1;
} catch {
/* the session went away mid-sweep */
}
}
return cleared;
}
private armedKey(muxName: string): string {
return `${this.socket}\0${muxName}`;
}
/** The global and the session hook listings, in one tmux call. */
private async readFollowHooks(
muxName: string
): Promise<{ global: Record<string, FollowHookState>; session: Record<string, FollowHookState> }> {
const { stdout } = await this.exec('tmux', [
'-L',
this.socket,
'show-hooks',
'-g',
';',
'display-message',
'-p',
'-t',
muxName,
FOLLOW_READ_SPLIT,
';',
'show-hooks',
'-t',
muxName,
]);
const split = stdout.indexOf(FOLLOW_READ_SPLIT);
if (split === -1) throw new Error('unexpected show-hooks output');
return {
global: parseFollowHooks(stdout.slice(0, split)),
session: parseFollowHooks(stdout.slice(split + FOLLOW_READ_SPLIT.length)),
};
}
/**
* Owner first (the hook is inert from then on), then our hook, in one call.
*
* ⚠️ When ours is the only entry of the event, the whole session array is
* unset, not just our index: `set-hook -u` on one index leaves an empty
* session-level array, which keeps hiding the user's global hook for that
* event (measured on tmux 3.8). `restoreSessionOptions()` documents the
* same trap for `status-format[0]`.
*/
private async dropFollowTyping(muxName: string, known?: Record<string, FollowHookState>): Promise<void> {
const hooks = known ?? (await this.readFollowHooks(muxName)).session;
const args = [
'set-option',
'-u',
'-t',
muxName,
TUI_FOLLOW_OWNER,
';',
'set-option',
'-u',
'-t',
muxName,
TUI_FOLLOW_PID,
];
for (const name of Object.keys(TUI_FOLLOW_HOOKS)) {
const state = hooks[name];
if (state.slot !== 'ours') continue;
const event = name.slice(0, name.indexOf('['));
args.push(';', 'set-hook', '-u', '-t', muxName, state.others === 0 ? event : name);
}
await this.exec('tmux', ['-L', this.socket, ...args]);
}
/**
* Give back a switch key, but only while it is still one of ours.
*
+18
View File
@@ -99,6 +99,24 @@ export interface FilesystemBrowseData {
truncated: boolean;
}
/** One page of immediate children for GET /sessions/:id/files?lazy=1. */
export interface LazyFileListingData {
root: string;
worktree?: { name: string; path: string; outside?: true };
lazy: true;
tree: Array<{
name: string;
path: string;
type: 'file' | 'directory';
size?: number;
extension?: string;
}>;
totalFiles: number;
totalDirectories: number;
truncated: boolean;
nextCursor?: string;
}
/** Response payload for `PUT /api/sessions/:id/file-content` (File Viewer edit mode). */
export interface FileWriteData {
/** Workspace-relative path as submitted */
+39
View File
@@ -0,0 +1,39 @@
/**
* @fileoverview Close a chokidar watcher on its first error, safely.
*
* chokidar 3 with `persistent: false` has no guard for an `fs.watch` that
* throws (EMFILE once the inotify instance limit is used up, ENOSPC once the
* watch limit is): it emits the error, then a TypeError from closing the
* watcher it never got, then retries on the parent directory, one level per
* pass, and re-adds `/` forever, since the parent of `/` is `/`. Only a closed
* watcher ends that loop, so a watcher whose `'error'` handler just logs logs
* forever.
*
* Closing from the handler is not enough on its own:
* - `close()` removes every listener, and the TypeError of the same pass is
* emitted after it. With no `'error'` listener EventEmitter throws it, and it
* reaches the process as an unhandled rejection. So a no-op listener stays
* on the closed watcher.
* - callbacks chokidar already has in flight can still call `add()` (a deleted
* file's `_remove()` re-adds the file when chokidar thinks it was the only
* watched path), and `add()` sets `closed = false`, which starts the climb
* again, silently now. So `add()` becomes a no-op on the closed watcher.
*
* @module utils/close-watcher-on-error
*/
import type { FSWatcher } from 'chokidar';
/**
* Close `watcher` on its first `'error'` and pass that error to `onClosed`,
* once. The caller's polling has to cover what the watcher watched and create it
* again later: chokidar 3 reports a one-off ENOENT race through the same error.
*/
export function closeWatcherOnError(watcher: FSWatcher, onClosed: (err: unknown) => void): void {
watcher.once('error', (err: unknown) => {
watcher.close().catch(() => {}); // best-effort, like the stop() paths
watcher.on('error', () => {}); // see the fileoverview
watcher.add = () => watcher; // likewise
onClosed(err);
});
}
+10 -6
View File
@@ -10,7 +10,7 @@
**Session lineage lines** (tab → tab it spawned, `sessionLineageLines`, per-device, desktop default ON): a create request may name its spawner via a `parentSessionId` body field or the `X-Codeman-Parent-Session` header; `resolveParentSessionId()` (route-helpers.ts) resolves it (exact id or unique ≥8-char prefix, live, visible, same owner) and ⚠️ anything unresolvable is DROPPED, never a 400. Rides `toState()`, no new SSE event. ⚠️ Rendering is a LAYER on the existing SVG pass (`_appendLineageConnectionLines` at the tail of `_updateConnectionLinesImmediate()`) and draws EVERY family, emphasizing the selected tab's (what it spawned, and the family it was spawned into: `lineage-family--focus`, thicker, opaque, drawn last; lanes stay in strip order), so a selection change must redraw (`_updateActiveTabImmediate`, gated on `_lineageTotalEdges`), and again on the strip's size `transitionend` (the active tab widens for ~150ms after the redraw). Geometry is pure in `computeLineageTree()`: one rounded orthogonal tree per spawning tab, every route starting at the PARENT (siblings share the trunk exactly), routed ONLY through the gaps between tab rows plus a spine left of every row, so it never crosses a tab or the terminal. ⚠️ That room is reserved in CSS by `.session-tabs.lineage-tree` (`_syncLineageGutter()`, called before the wrap is measured), keyed on whether ANY family exists, never on the selection, or every tab switch would resize the header and the PTY. Colors are keyed on the SPAWNING tab, claimed in strip order for every family, and memoized (never by draw index or selection order). ⚠️ Desktop only (z-index vs the fixed mobile header). ⚠️ Paths must keep `data-agent-id="lineage:<childId>"` (the entrance animation queries it); skip endpoints scrolled out of the strip. → [architecture-invariants#session-lineage-lines-tab--tab-it-spawned](../../docs/architecture-invariants.md#session-lineage-lines-tab--tab-it-spawned)
**Split-pane sessions** (`showSplitButton`, header button, default OFF, desktop-only at 1180px (width alone, so a wide Android tablet clears it), per-device): a second live session ("Pane B") beside the active one, in a `TerminalTile` (terminal-tile.js; the picker, divider and auto-collapse stay in terminal-split.js) with its own xterm + WebSocket, resizable via a draggable divider. Pane B reconnects after a drop, sends input through the exactly-once queue over its own socket (`_registerInputSocket`), has clickable paths and image paste, and owns its geometry (no 40x10 floor, `zc` columns adopted, font changes call `tile.fit()`). ⚠️ Only typed input enters that persisted queue: xterm's query replies are dropped and focus/mouse reports go out ephemeral. ⚠️ App-level terminal actions find their pane through `_focusedPane()` (the terminal focused last), never `this.terminal`. Still plainer than the primary pane (no local-echo overlay, CJK IME textarea or touch handlers), though it wires the same keyCode-229 soft-keyboard controller (Android autocorrect, #441/#541), and NOT persisted across reloads. The tile grid (below) reuses `TerminalTile`, and the two are never open together. → [architecture-invariants#split-pane-sessions](../../docs/architecture-invariants.md#split-pane-sessions)
**Split-pane sessions** (`showSplitButton`, header button, default OFF, desktop-only at 1180px (width alone, so a wide Android tablet clears it), per-device): a second live session ("Pane B") beside the active one, in a `TerminalTile` (terminal-tile.js; the picker, divider and auto-collapse stay in terminal-split.js) with its own xterm + WebSocket, resizable via a draggable divider. Pane B reconnects after a drop, sends input through the exactly-once queue over its own socket (`_registerInputSocket`), has clickable paths and image paste, and owns its geometry (no 40x10 floor, `zc` columns adopted, font changes call `tile.fit()`). ⚠️ Only typed input enters that persisted queue: xterm's query replies are dropped and focus/mouse reports go out ephemeral. ⚠️ App-level terminal actions find their pane through `_focusedPane()` (the terminal focused last), never `this.terminal`. Still plainer than the primary pane (no local-echo overlay, CJK IME textarea or touch handlers), though it wires the same soft-keyboard input as the main pane: the iOS native-input owner (`_iosNativeInput`, #830) on iOS WebKit touch, otherwise the keyCode-229 controller (Android autocorrect, #441/#541), and NOT persisted across reloads. The tile grid (below) reuses `TerminalTile`, and the two are never open together. → [architecture-invariants#split-pane-sessions](../../docs/architecture-invariants.md#split-pane-sessions)
**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
@@ -32,13 +32,15 @@
Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. Load order is the `<script>` order in `index.html` (each module's `@loadorder` tag mirrors it). `i18n.js` translates static + newly inserted application DOM while skipping terminal/response/file/user-name surfaces; `input-cjk.js` handles CJK IME composition via an always-visible textarea below the terminal (`window.cjkActive` blocks xterm's onData). `terminal-keycode229-recovery.js` forwards a committed `input` event that xterm's `_inputEvent` guard drops (Chrome-on-Android soft keyboards send `composed: true` after a keydown), and only when xterm emitted no canonical data for that keystroke. ⚠️ **That decision is settled at the NEXT keydown as well as on its own zero-delay timer** (#441): the drain runs from xterm's custom key handler, which fires BEFORE xterm processes that key, so a soft keyboard that commits the last character and sends Enter in one InputConnection transaction puts the character on the wire ahead of the `\r`. On the timer alone that character is not merely late, it is LOST: xterm emits the `\r` first and bumps the canonical counter past the candidate's snapshot, so the candidate stands down (measured, `hell\r` where the user typed `hello`). The edit-based diff described below is settled first at that keydown, so the drain decides with the evidence the timer had and Enter's textarea clear cannot turn the pending line into DELs. Ordering is pinned by `test/terminal-keycode229-recovery.browser.test.ts`, which the CI gate does NOT run. The same module replaces xterm's `_handleAnyTextareaChanges` (an append-only `newValue.replace(oldValue, '')` diff) with an edit-based one, so an Android autocorrect on space (delete + insert) reaches the PTY once instead of duplicating the line; ⚠️ that diff is settled at the NEXT keydown, before xterm handles that key, because xterm clears the textarea for Enter and a pending diff would then send one DEL per character ahead of the submitted line (except a composition xterm finalizes synchronously at that key, which stays xterm's). ⚠️ Every xterm that takes keyboard input wires its OWN controller from this module (`create()` returns null unless `matchMedia('(pointer: coarse)')` matches or the user agent is Android, so a desktop dead key is not forwarded twice, #716, while an Android device whose mouse, trackpad cover or stylus Chromium reports as the fine primary pointer keeps the soft-keyboard recovery): the primary pane (terminal-ui.js `initTerminal()`) and each `TerminalTile` (terminal-tile.js `_createKeyCode229Recovery()`, so every grid tile and the split's Pane B, which a wide Android tablet reaches), each on its own textarea, composition helper and session; in both, `handleKeyEvent` must run ABOVE the custom key handler's keyCode-229 early return, and `notifyCanonicalData` sits in the onData lambda, never in the send path the recovered bytes also take. `mobile-ime-preview.js` (iOS WebKit only) paints the text an IME is composing: an iOS IME commit is routed into the local-echo overlay through the ordinary printable/paste branch and then `_transferMobileImeCommitToLocalEcho`, and without local echo the preview clears only on output parsed AFTER the commit (or its 2 s fallback). ⚠️ It watches keydown in the capture phase on `terminal.element`, never on the textarea, because xterm finalizes the composition and emits the commit in its own capture listener on the textarea.
**iOS native input ownership (#830)**: `terminal-ios-native-input.js` loads after `mobile-ime-preview.js` and before the terminal hosts. `MobileImePreview.isIosWebKitTouch` is the shared gate: supported main panes and tiles install `_iosNativeInput`, never `_keyCode229Recovery`. The owner retains the native textarea line, reconciles replacements/deletions as one transaction, and projects trackpad selection through `.ios-native-caret` without sending arrows. The main marker uses the local-echo layout anchor while the overlay owns the line; missing overlay geometry hides it. External producers call `_prepareExternalInput(pane, reason)` before sending. Toolbar Enter uses `submitFromToolbar()`, capturing the focused pane once; text, the 80ms gap and CR reserve that session's FIFO even across a switch. Browser regressions: `test/ios-native-input.browser.test.ts`; run `node scripts/prepare-test-vendor.mjs` first. → [ios-native-input](../../docs/ios-native-input.md)
**Entrance animations** (`entrance-animations.js`, all OFF by default): opt-in animations for tabs, terminal, windows, connection lines and tile-grid tiles, chosen via `data-tab-anim` / `data-term-anim` / `data-win-anim` / `data-line-anim` / `data-tile-anim` on `<html>`; the default `legacy` theme short-circuits every hook (tiles keep the grid's own `settle`). ⚠️ Tabs and lines are destroyed mid-animation on re-render, so re-apply to the fresh element by id with a negative `animation-delay` (resume, never restart). ⚠️ Terminal-pane styles may animate only transform / opacity / clip-path (anything else resizes the PTY via FitAddon); `blur` is the ONE sanctioned `filter` exception, do not generalise it. ⚠️ Line glow lives in `--line-glow` so blur keyframes interpolate. Every animation setting lives in App Settings → **Animations** (`#settings-animations`); put new ones there. ⚠️ Tiles are OFF by default (Animations → Tile Animations, default `settle` = the grid's own fade, no screen beat); a theme only presets it. A tile's FRAME animates transform/opacity only (six at once, no filter) with `tile-enter*`/`tile-leave*` keyframe names (what the mount and the still copy listen for); its SCREEN replays the pane style on `.tile-body.term-enter`; a reload's restore always settles. Persisted per-device in `codeman:*Anim` localStorage keys, never in `SettingsUpdateSchema`; lab at `?animlab=1`. Test: `test/entrance-animations.test.ts`. → [architecture-invariants#entrance-animations](../../docs/architecture-invariants.md#entrance-animations)
**Mobile tab strip scrolling** (issue #257): under 768px the tab strip scrolls horizontally, so the active tab must be kept reachable. `_updateActiveTabImmediate()` reveals it via `computeTabScrollLeft()` (constants.js, rect math on the strip's own `scrollLeft`, never `scrollIntoView()`, which scrolls the document under the fixed header); `_fullRenderSessionTabs()` must restore `scrollLeft` across rebuilds and re-reveal only when the active tab changed (`_lastRenderedActiveTabId`) or, grouped by state, the ACTIVE tab moved to another state band (`_noteActiveTabBand()`, both render paths, scrolling row only; another tab's move never scrolls). ⚠️ The phone-block `min-width` on `.session-tab.active .tab-name` keeps the tab's centre off the gear/close icons, sized for numberless tabs 10+ (floor 40px); do not shrink it. With the opt-in tab "+" on (`showTabNewButton`, `html.tabs-show-new`) a third icon joins them and the reserve grows to 68px, still under the 80px `max-width`. ⚠️ Never reintroduce hoisting the active session to the front of the strip. Tests: `test/mobile-tab-tap-zones.test.ts`, `test/tab-triage.test.ts`. → [architecture-invariants#mobile-tab-strip-scrolling](../../docs/architecture-invariants.md#mobile-tab-strip-scrolling)
**Session list layout: header strip or left sidebar** (`sessionListLayout`, default `header`; per-device via `displayKeys`, also in `SettingsUpdateSchema`): the list can move into a collapsible `<aside>` (Alt+B, `toggleSessionSidebar`) or, via `tabOrientation`, a resizable vertical `#tabRail` (desktop/tablet only). ⚠️ There is ONE `#sessionTabs`, MOVED between hosts, never a second list: `applySessionListLayout()` runs first, then `applyTabOrientation()`, both BEFORE `applyTabWrapSettings()`, and both arm/disarm `_startSidebarRichClock()`. ⚠️ Axis decisions use `_isVerticalTabList()`, never `isSessionSidebarActive()` alone. ⚠️ Rich rows share one gate, `isRichTabRows()`; rich CSS pairs sidebar+rail with comma-grouped selectors, never `:is()`, and card rules stay rail-scoped. ⚠️ Rail sort (`tabRailSort`, default `activity`) is the flex `order` property only, never a DOM reorder; the arrow-key walk and the phone swipe follow computed `order`. ⚠️ Leaving sidebar mode clears `_sidebarFilter`; the handheld overlay drawer is `inert` when closed, the docked rail never. ⚠️ The rail's **Search sessions** box (`setTabRailSearch`, in memory only) and the sidebar filter share ONE row filter, `_applyTabListFilter()` over the pure `CodemanTabSearch` (constants.js): classes only, never a reorder or layout write; the rail matches the name, the sidebar name + folder. ⚠️ A session row with a tab alert (`tabAlerts`, red or yellow) is never hidden by either box: it goes in as `keep: true`, counts toward its group (which stays on screen) but not toward `matchCount`. ⚠️ Escape in the rail box is claimed by the global capture-phase Escape branch (the box's own `onkeydown` runs after it, too late to stop `closeAllPanels()`), and a filter change that shows or hides anything redraws the connector lines, since a keystroke re-renders nothing; a floating window finds its parent tab only through `_paintedSessionTab()` (a hidden row's rect is all zero but truthy, which drew connectors from the viewport's corner). While it runs `_projectTabGroups()` projects every group open (a collapsed group's rows are not in the DOM) and `toggleTabGroupCollapsed()` refuses, leaving the stored collapse untouched; drag stays on during a search (owner decision), a drop landing between the visible neighbours; `applyTabOrientation()` clears it off the rail. Tests: `test/tab-rail-search.test.ts`, `test/tab-rail-search.browser.test.ts`. → [architecture-invariants#session-list-layout-header-strip-vs-left-sidebar](../../docs/architecture-invariants.md#session-list-layout-header-strip-vs-left-sidebar)
**Tab layouts** (`tabArrangement`, per-device, default `classic`; `state`/`case`/`ledger` are opt-in; Discussion #426): `state` (option C) splits the list into needs you / waiting / working / idle (idle is `quiet`: its heading stays as the row's anchor but draws no label; `tabStateOrder: 'urgent-last'` flips the order, needs you at the bottom): rows in the desktop header strip with left-aligned labels in a measured column (the brand sits over the strip's corner, so the rows after the first start under "Codeman"), sections in the flat rail and the sidebar, inline dividers on the tablet strip, group order with no headings on phones. `case` (option A) wraps each case's tabs in one `.tab-cluster` box and hides the `-<case>` of a generated name (`.tab-name-case`). `ledger` (option B) is a CSS-only grid on the desktop header strip. `classic` is the old strip; once it wraps on desktop it is L-shaped via `_syncTabStripCorner()` (the toolbar sits over its top-right corner and later rows run the full width under it, a strip already past its max-height keeps the plain wrap): ⚠️ `.tabs-corner` comes off before the wrap is measured, and the strip is `display: block` in that state, so flex-only rules do not apply to it there (`test/tab-strip-corner.browser.test.ts`). Pure cores: `CodemanTabTriage` and `CodemanTabClusters` (constants.js). ⚠️ `state` is the flex `order` property plus `aria-hidden` heading/break elements reconciled in place by `_syncTabTriageChrome()` after BOTH render paths, never a DOM reorder (a state change is an incremental pass). ⚠️ `case` boxes ARE a DOM grouping, so the incremental path rebuilds whenever `_tabClusterLayout().key` changes; membership follows `_mobileOverviewCaseFor()` like the home screens. ⚠️ Drag only reorders within a group or box (`_isTabDropAcrossGroups()`). ⚠️ Named groups in the vertical rail win over both groupings. ⚠️ `classic` must leave no trace (no headings, no inline order, no boxes, no name split), and the ledger must not change the markup. ⚠️ Grouping is a render layer: `sessionOrder`, Alt+[ / Alt+], Ctrl+Tab and Alt+1..9 keep the canonical order, and only the phone swipe walks the drawn order (`nextSession({ visual: true })` through `_stripSessionOrder()`, the same `_visibleTabRows()` walk the strip's arrow keys use); an active session the list does not draw steps in at the first or last row, and an empty drawn list goes nowhere rather than falling back to a hidden session (`test/session-swipe-gesture.test.ts`). Tests: `test/tab-triage.test.ts`, `test/tab-clusters.test.ts`. → [architecture-invariants#tab-layouts-by-state-by-case-ledger](../../docs/architecture-invariants.md#tab-layouts-by-state-by-case-ledger)
**Tab layouts** (`tabArrangement`, per-device, default `classic`; `state`/`case`/`ledger` are opt-in; Discussion #426): `state` (option C) splits the list into needs you / waiting / working / idle (idle is `quiet`: its heading stays as the row's anchor but draws no label; `tabStateOrder: 'urgent-last'` flips the order, needs you at the bottom): rows in the desktop header strip with left-aligned labels in a measured column (the brand sits over the strip's corner, so the rows after the first start under "Codeman"), sections in the flat rail and the sidebar, inline dividers on the tablet strip, group order with no headings on phones. `case` (option A) wraps each case's tabs in one `.tab-cluster` box and hides the `-<case>` of a generated name (`.tab-name-case`). `ledger` (option B) is a CSS-only grid on the desktop header strip; its bar replaces the dot everywhere except a working cell, which keeps the dot and its spinning ring (the bar alone is green for idle and working alike). `classic` is the old strip; once it wraps on desktop it is L-shaped via `_syncTabStripCorner()` (the toolbar sits over its top-right corner and later rows run the full width under it, a strip already past its max-height keeps the plain wrap): ⚠️ `.tabs-corner` comes off before the wrap is measured, and the strip is `display: block` in that state, so flex-only rules do not apply to it there (`test/tab-strip-corner.browser.test.ts`). Pure cores: `CodemanTabTriage` and `CodemanTabClusters` (constants.js). ⚠️ `state` is the flex `order` property plus `aria-hidden` heading/break elements reconciled in place by `_syncTabTriageChrome()` after BOTH render paths, never a DOM reorder (a state change is an incremental pass). ⚠️ `case` boxes ARE a DOM grouping, so the incremental path rebuilds whenever `_tabClusterLayout().key` changes; membership follows `_mobileOverviewCaseFor()` like the home screens. ⚠️ Drag only reorders within a group or box (`_isTabDropAcrossGroups()`). ⚠️ Named groups in the vertical rail win over both groupings. ⚠️ `classic` must leave no trace (no headings, no inline order, no boxes, no name split), and the ledger must not change the markup. ⚠️ Grouping is a render layer: `sessionOrder`, Alt+[ / Alt+], Ctrl+Tab and Alt+1..9 keep the canonical order, and only the phone swipe walks the drawn order (`nextSession({ visual: true })` through `_stripSessionOrder()`, the same `_visibleTabRows()` walk the strip's arrow keys use); an active session the list does not draw steps in at the first or last row, and an empty drawn list goes nowhere rather than falling back to a hidden session (`test/session-swipe-gesture.test.ts`). Tests: `test/tab-triage.test.ts`, `test/tab-clusters.test.ts`. → [architecture-invariants#tab-layouts-by-state-by-case-ledger](../../docs/architecture-invariants.md#tab-layouts-by-state-by-case-ledger)
**Header stats styles** (`headerStatsStyle`, per-device, desktop only, default `compact`; Discussion #426 option G): `tiles` / `compact` (two pills, a ring beside every value) / `classic` (as before), keyed on `data-header-stats` (pre-paint + `applyHeaderStatsStyle()`), forced to `classic` below 768px and in a solo window. ⚠️ The clustered styles MOVE `#connectionIndicator` into `#headerSystemStats` and `#planUsageChip` right after it; `classic` moves them back to comment anchors. ⚠️ WS joins the pill only while System Stats is shown. ⚠️ The extra parts (stat rings, tile words, plan rings, meters) are always rendered and hidden by default in CSS, which is what keeps `classic` unchanged; tile words are derived beside the connection descriptor, never added to it (`test/connection-indicator.test.ts` pins its shape). ⚠️ A tile is a three-row grid (label, value, bar) with pixel line-heights and the bundled JetBrains Mono; never lay the bar over a fixed-height tile (a taller system mono put the value on top of it). The WS tile's grid lives on the inner `.connection-tile`, because JS writes the indicator's `display` inline. Tests: `test/header-stats-style.test.ts`. → [architecture-invariants#header-stats-styles](../../docs/architecture-invariants.md#header-stats-styles)
@@ -56,7 +58,9 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
**Command palette + shortcut registry**: `Ctrl/Cmd/Alt+K` opens the session palette; shortcuts live in a rebindable registry (`DEFAULT_SHORTCUTS`/`getShortcutRegistry()`/`matchesShortcutEvent()` in app.js, overrides in `settings.shortcutOverrides`). ⚠️ Palette-chord keys must ALSO be swallowed in `attachCustomKeyEventHandler` (terminal-ui.js) or xterm writes the control byte into the PTY. ⚠️ The global Escape handler (app.js) calls EVERY close method on every Escape, in the capture phase, so a close method that does more than hide (the palette and Session Manager restore focus) must return early when its overlay is not open. ⚠️ `saveAppSettings()` rebuilds settings from the DOM, so keys edited elsewhere (`shortcutOverrides`, `showTokenCount`, `showCost`) need explicit `_prev` carry-over. ⚠️ **Smart copy (`Ctrl+C`)**: with no selection it must `return true` without `preventDefault()` or the interrupt is lost; keep `copyTerminalSelection` out of `SHORTCUT_ACTIONS`. The gate tests the CLEANED selection (`CodemanCopySelection.clean`: trailing padding, plus a LEADING margin only up to the width the CLI declares in `capabilities.transcriptGutter`, never one derived from the pane); the strip is not idempotent, so clean once and pass the RAW selection on, and leave Alt+drag column selections untouched. → [architecture-invariants#command-palette-and-shortcut-registry](../../docs/architecture-invariants.md#command-palette-and-shortcut-registry)
**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`, or `extendedKeyboardBar`, 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.
**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.
**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)
@@ -76,17 +80,17 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
**Shell keyboard accessory bar + one-shot Ctrl** (`keyboard-accessory.js`): a shell-mode session swaps the mobile accessory bar for terminal controls; `setMode()` records `extendedKeyboardBar` as the base layout and `refreshForActiveSession()` resolves base-vs-shell. ⚠️ Ctrl is a one-shot modifier applied in `terminal.onData` (after `shouldSuppressTerminalQueryResponse`, before every send path), and must skip `isTerminalFocusOrMouseReport()` chunks. ⚠️ It must disarm on use, second tap, any other accessory key, session switch, keyboard dismissal and layout swap. ⚠️ `_handleCjkInput()` must apply it too (the CJK textarea bypasses onData). Mapping: `ctrlByteFor()`. ⚠️ mobile.css's light-skin repaint must keep excluding `.accessory-btn:not(.armed)` or the armed state is invisible. → [architecture-invariants#shell-keyboard-accessory-bar-and-one-shot-ctrl](../../docs/architecture-invariants.md#shell-keyboard-accessory-bar-and-one-shot-ctrl)
**Mobile prompt composer** (`keyboard-accessory.js`): the agent bars' Paste key is **Compose**, a native multiline dialog where only **Send** submits (the shell bar keeps plain Paste). Opening it adopts the whole terminal prompt (`_takePendingLocalEcho`), erasing the flushed prefix with backspaces counted in code points. ⚠️ Drafts are per-session and in memory only (`_composerDrafts`), never persisted (prompts carry secrets). ⚠️ Delivery is a hand-built bracketed-paste frame via `_sendInputAsync` WITHOUT `useMux`, then a separate delayed Enter WITH it; never `terminal.paste()`, and the frame must never take the mux fallback (`TmuxManager.sendInput()` strips every `\r`, the frame's line separator, so the lines weld into one inside a second pair of markers and get submitted). ⚠️ `_composerMaxLength` must stay derived from `MAX_INPUT_LENGTH` minus the markers, or an oversized frame wedges the durable queue. ⚠️ The composer overlay needs its own gutter restatement after the fold rules. The textarea carries `dir="auto"`, so a prompt written in Persian, Arabic or Hebrew lays out right to left from its first letter (#715). Test: `test/mobile-prompt-composer.test.ts`. → [architecture-invariants#mobile-prompt-composer](../../docs/architecture-invariants.md#mobile-prompt-composer)
**Mobile prompt composer** (`keyboard-accessory.js`): the agent bars' Paste key is **Compose**, a native multiline dialog where only **Send** submits (the shell bar keeps plain Paste). Opening it adopts the whole terminal prompt (`_takePendingLocalEcho`), erasing the flushed prefix with backspaces counted in code points. ⚠️ Drafts are per-session and in memory only (`_composerDrafts`), never persisted (prompts carry secrets). ⚠️ Delivery is a hand-built bracketed-paste frame enqueued on the session FIFO (`_enqueueInput`, `_sendBracketedPaste()`) WITHOUT `useMux`, then a `gap` and a separate Enter WITH it; never `terminal.paste()`, and the frame must never take the mux fallback (`TmuxManager.sendInput()` strips every `\r`, the frame's line separator, so the lines weld into one inside a second pair of markers and get submitted). ⚠️ `_composerMaxLength` must stay derived from `MAX_INPUT_LENGTH` minus the markers, or an oversized frame wedges the durable queue. ⚠️ The composer overlay needs its own gutter restatement after the fold rules. The textarea carries `dir="auto"`, so a prompt written in Persian, Arabic or Hebrew lays out right to left from its first letter (#715). Test: `test/mobile-prompt-composer.test.ts`. → [architecture-invariants#mobile-prompt-composer](../../docs/architecture-invariants.md#mobile-prompt-composer)
**Terminal resilience**: a replay clear is the queued in-stream `\x1bc` in `_resetTerminalForReplay()`, never `reset()`/`clear()` (queued bytes fuse into the snapshot); the renderer watchdog `_kickRenderer()` reads xterm privates, pinned by `test/xterm-private-api.test.ts` against the resolved lockfile version; every terminal capture fetch has a deadline that covers the BODY (`_fetchTerminalCapture`). → [architecture-invariants#terminal-resilience-replay-clears-renderer-liveness-fetch-deadlines](../../docs/architecture-invariants.md#terminal-resilience-replay-clears-renderer-liveness-fetch-deadlines)
**WebSocket output-gap reconcile** (`_wsOutputGapSession`, app.js): output frames carry no sequence number, so an unintentional WS close while SSE stays up marks the session and the next open reconciles. ⚠️ The marker is cleared only once a repaint actually happened (`_markTerminalBufferReconciled()`, never in a `finally`). → [architecture-invariants#websocket-output-gap-reconcile](../../docs/architecture-invariants.md#websocket-output-gap-reconcile)
**Dismissing the on-screen keyboard** (`terminal-ui.js`): two gestures blur the terminal's hidden textarea. (1) `_installMobileKeyboardDismiss()`, a document `touchend` that must never fire inside `#terminalContainer` or on a control (`MOBILE_KEYBOARD_DISMISS_EXEMPT_SELECTOR`, via `closest()`; roving-tabindex items sit at `tabindex=-1`, so the grouped rail's are listed as `[role="treeitem"]`). (2) In `_handleMobileTerminalTap`, a second tap on inert `content` blurs; the prompt row keeps focus-then-position. ⚠️ A scroll also ends in `touchend`: both classifiers must share one threshold (`TAP_THRESHOLD` reads `MOBILE_KEYBOARD_DISMISS_TAP_SLOP`), and multi-touch is never a tap. ⚠️ An accessory key that keeps the keyboard up (`ACCESSORY_REFOCUS_ACTIONS`, keyboard-accessory.js) cancels its `mousedown` default, so the press does not blur the terminal; the click-time `terminal.focus()` stays as the fallback. Letting the tap blur and refocusing afterwards made every such key start a dismissal, a blur/focus pair per tap. A first tap on clear/compact only arms the confirm and is treated the same (`test/accessory-keeps-terminal-focus.test.ts`). ⚠️ CI cannot see the only test for (1): run `npm run test:mobile -- test/mobile/keyboard.test.ts` by hand and diff the FAIL list against master. → [architecture-invariants#dismissing-the-on-screen-keyboard](../../docs/architecture-invariants.md#dismissing-the-on-screen-keyboard)
**Dismissing the on-screen keyboard** (`terminal-ui.js`): two gestures blur the terminal's hidden textarea. (1) `_installMobileKeyboardDismiss()`, a document `touchend` that must never fire inside `#terminalContainer` or on a control (`MOBILE_KEYBOARD_DISMISS_EXEMPT_SELECTOR`, via `closest()`; roving-tabindex items sit at `tabindex=-1`, so the grouped rail's are listed as `[role="treeitem"]`). (2) In `_handleMobileTerminalTap`, a second tap on inert `content` blurs; the prompt row keeps focus-then-position. ⚠️ A scroll also ends in `touchend`: both classifiers must share one threshold (`TAP_THRESHOLD` reads `MOBILE_KEYBOARD_DISMISS_TAP_SLOP`), and multi-touch is never a tap. ⚠️ An accessory key that keeps the keyboard up (`ACCESSORY_REFOCUS_ACTIONS`, keyboard-accessory.js) cancels its `mousedown` default, so the press does not blur the terminal; the click-time `terminal.focus()` stays as the fallback. Letting the tap blur and refocusing afterwards made every such key start a dismissal, a blur/focus pair per tap. A first tap on clear/compact only arms the confirm and is treated the same (`test/accessory-keeps-terminal-focus.test.ts`). ⚠️ The content touchstart blur skips the visible `#cjkInput` (`_contentTouchStartBlurs()`), or every swipe on the live screen closed its keyboard; a tap still closes it (inert content, a link, a long press). On phones `updateLayoutForKeyboard()` also moves `.app` by `visualViewport.offsetTop` while the keyboard is up, and lifts the fixed bars inside it from `.app`'s bottom (architecture-invariants, Folding devices section). ⚠️ CI cannot see the only test for (1): run `npm run test:mobile -- test/mobile/keyboard.test.ts` by hand and diff the FAIL list against master. → [architecture-invariants#dismissing-the-on-screen-keyboard](../../docs/architecture-invariants.md#dismissing-the-on-screen-keyboard)
**Phone toolbar: Enter replaces Shell** (post-1.8.0): inside `@media (max-width: 599px)` `btn-shell` is `display:none` and `btn-enter` takes its slot (`order: 4`); starting a shell moved into the Run dropdown (`Terminal / Shell` → `setRunMode('shell')` → `run()` → `runShell()`, button label "Run SH"). `runMode` is `z.string().max(20)` server-side, so new modes need no schema change. Desktop and tablet keep the green Run Shell button unchanged.
⚠️ **`sendEnterKey()` MUST go through `terminal._core.coreService.triggerDataEvent('\r', true)`** — not `sendInput()`, and never a raw POST to `/api/sessions/:id/input`. `localEchoEnabled` defaults to `MobileDetection.isTouchDevice()`, so on every phone the characters you type are buffered in the `LocalEchoOverlay` and have **never reached the PTY**; the `onData` Enter branch in terminal-ui.js is what flushes `pendingText` first and only then sends `\r` (after an 80ms delay so text lands first). Sending a bare `\r` submits an empty line and strands the typed text on screen, so the button looks dead. Replaying the keypress reuses the overlay flush, the flushed-offset cleanup and the ordering instead of reimplementing them. `KeyboardAccessory.sendKey()` is for escape sequences (arrows/Esc) and is the WRONG template to copy for input.
**`sendEnterKey()` must call `submitFromToolbar()`**, never a raw input POST. The semantic submit captures the focused pane once and calls `_prepareExternalInput` to settle/reset native ownership. For the main pane, it reuses local-echo Enter handling: pending text, the 80ms gap and the CR are reserved atomically in the captured session's FIFO. For a tile, the CR goes to the tile's session. A session switch cannot redirect the delayed CR, and a missing pane must not fall back to another session. The one deliberate exception: while the CJK field is visible (`#cjkInput.cjk-input-visible`), `onData` drops everything under `window.cjkActive`, so `sendEnterKey()` calls `CjkInput.submit()` instead, which sends what the field holds (a Send on Enter answer, or live text not yet flushed) then Enter, on the session `CjkInput` captured for that text (`_sendCjkPrompt` reserves the text, 120 ms gap and Enter on that session's FIFO).
⚠️ **Skin overrides outrank plain class rules.** `styles.css` nests its skin block inside `html:not([data-skin="og"]) { … }`, so a bare `.btn-toolbar` rule in there resolves to specificity **(0,2,1)** and beats a `.btn-toolbar.btn-x` rule **(0,2,0)** in `mobile.css` regardless of load order. Toolbar-button colors set from mobile.css therefore need `!important`: that is why mobile.css leans on it so heavily. Symptom: only your `!important` properties land and everything else silently renders in generic toolbar grey. Press feedback on the phone bars sidesteps this: the `:active` rules for `.btn-toolbar`, the mobile icon buttons and `.accessory-btn` (mobile.css) use `transform` and `filter` only, which nothing on these buttons sets at a higher specificity, so one rule reads the same on every skin; a background `:active` lost to the skin block on all but og, and an inset `box-shadow` lost to the skin hover rules, which is why neither is used. The light skins darken instead of brightening, and `prefers-reduced-motion` drops the scale.
+34 -10
View File
@@ -66,6 +66,12 @@ function sendAuthRateLimit(reply: FastifyReply, failures: StaleExpirationMap<str
reply.code(429).send('Too Many Requests — try again later');
}
/** 401 with a Basic challenge, so a browser shows its login dialog. */
function challengeBasicAuth(reply: FastifyReply): void {
reply.header('WWW-Authenticate', 'Basic realm="Codeman"');
reply.code(401).send('Unauthorized');
}
/** Parse a `Basic base64(user:pass)` header into its parts, or null if malformed. */
function parseBasicAuth(header?: string): { username: string; password: string } | null {
if (!header || !header.startsWith('Basic ')) return null;
@@ -357,9 +363,11 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean, bas
// Separate hook-secret failure counter (COD-54). MUST NOT share authFailures:
// legacy (pre-secret) hook configs fire constantly from 127.0.0.1, and counting
// their 401s against the shared bucket would 429 every cookie-less request from
// loopback — locking out the Basic-Auth login path (and, through a tunnel, every
// client, since tunneled traffic also arrives as 127.0.0.1).
// their 401s against the shared bucket would fill it for loopback: every wrong or
// malformed login from there would get a 429 (and in multi-user mode a correct
// password too, once the pre-verify gate is full), locking out the Basic-Auth login
// path and, through a tunnel, every client, since tunneled traffic also arrives as
// 127.0.0.1. A request with no Authorization header is never counted or refused.
state.hookSecretFailures = new StaleExpirationMap<string, number>({
ttlMs: AUTH_FAILURE_WINDOW_MS,
refreshOnGet: false,
@@ -485,6 +493,16 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean, bas
return;
}
// No credentials at all is not a guess: challenge it without counting or limiting.
// Counting it locked users out after every server restart (cookie sessions live in
// memory): an open tab's background requests carry only the dead cookie, ten of them
// filled the bucket within seconds, and the 429 that followed never re-prompted the
// browser for a password, so reloading could not recover until the window expired.
if (!auth) {
challengeBasicAuth(reply);
return;
}
// Rate limit only requests that failed to authenticate on this attempt.
const failures = authFailures.get(clientIp) ?? 0;
if (failures >= AUTH_FAILURE_MAX) {
@@ -495,8 +513,7 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean, bas
// Auth failed — track failure count
authFailures.set(clientIp, failures + 1);
reply.header('WWW-Authenticate', 'Basic realm="Codeman"');
reply.code(401).send('Unauthorized');
challengeBasicAuth(reply);
});
return state;
@@ -622,8 +639,7 @@ function registerMultiUserAuthHook(
sendAuthRateLimit(reply, userFailures, normUser);
return;
}
reply.header('WWW-Authenticate', 'Basic realm="Codeman"');
reply.code(401).send('Unauthorized');
challengeBasicAuth(reply);
};
app.addHook('onRequest', async (req, reply) => {
@@ -703,6 +719,15 @@ function registerMultiUserAuthHook(
// which is every reload after a restart: cookie sessions live in memory, so the
// browser replays its cached Basic header on many parallel requests at once. A
// request with no verify in flight for its credentials is gated as normal.
//
// No Authorization header at all is not a guess and runs no scrypt: challenge it
// before the gates, without counting. Counting it let an open tab's background
// requests after a restart (cookie sessions live in memory) fill the per-IP bucket,
// which then refused even the correct password, and a 429 never re-prompts a browser.
if (!req.headers.authorization) {
challengeBasicAuth(reply);
return;
}
const creds = parseBasicAuth(req.headers.authorization);
const normUser = creds ? creds.username.trim().toLowerCase() : '';
const flightKey = creds ? verifyFlightKey(clientIp, normUser, creds.password) : '';
@@ -746,10 +771,9 @@ function registerMultiUserAuthHook(
return;
}
// No credentials presented: count against the per-IP bucket and challenge.
// A malformed Authorization header: count against the per-IP bucket and challenge.
authFailures.set(clientIp, ipFail + 1);
reply.header('WWW-Authenticate', 'Basic realm="Codeman"');
reply.code(401).send('Unauthorized');
challengeBasicAuth(reply);
});
}
+377 -49
View File
@@ -801,9 +801,13 @@ class CodemanApp {
// the small `full=1` capture instead of the 1 MiB byte tail: see
// _notePaneHistory and selectSession.
this._paneHistoryLines = new Map(); // Map<sessionId, number>
// Cooldown per session for the scroll-to-top "load more history" re-pull.
// Per-session cooldown for top-of-buffer pulls; manual actions bypass it.
this._fullHistoryRepullAt = new Map(); // Map<sessionId, timestamp>
this._fullHistoryRepullInFlight = false;
this._liveOutputSinceFullPull = new Set(); // Set<sessionId>
this._historyReloadDismissed = new Set(); // Until the next successful full mux replay
this._liveOutputGen = new Map(); // Map<sessionId, number>
this._earlyReplayTravel = null; // { sessionId, moves: number[] } during a content-anchored replay
// Sessions whose last re-pull came back THINNER than the live buffer (a
// repaint-mode CLI pane, where tmux keeps no history of its own). The pull is
// refused for those and retried far more slowly — see _maybeRefetchFullHistory.
@@ -2596,13 +2600,41 @@ class CodemanApp {
* @param {number} [queuedBytes] - render-queue bytes at the drop, for the crash trail
*/
_scheduleDroppedOutputRecovery(sessionId, attempt = 0, queuedBytes) {
if (!sessionId || this._clientDropRecoveryTimer) return;
if (!sessionId) return;
// Nothing of the main terminal's to recover while the tile grid owns it.
if (this._tilesOwnTerminal?.()) return;
// A slow capture owns the live-output gate. Keep the recovery owed until
// it releases instead of spending every retry against the same open load.
if (this._isLoadingBuffer) {
if (sessionId === this.activeSessionId) {
if (this._pendingDroppedOutputRecovery?.sessionId !== sessionId && Number.isFinite(queuedBytes)) {
_crashDiag.log(`TERMINAL DROP: ${(queuedBytes / 1024).toFixed(0)}KB queued (recovery deferred)`);
}
const pending = this._pendingDroppedOutputRecovery;
this._pendingDroppedOutputRecovery = {
sessionId,
attempt: pending?.sessionId === sessionId ? Math.max(pending.attempt, attempt) : attempt,
};
}
return;
}
if (this._clientDropRecoveryTimer) return;
// Behind the debounce guard: one line per window, not per dropped frame.
if (Number.isFinite(queuedBytes)) _crashDiag.log(`TERMINAL DROP: ${(queuedBytes / 1024).toFixed(0)}KB queued`);
this._clientDropRecoveryTimer = setTimeout(async () => {
this._clientDropRecoveryTimer = null;
// A load may have opened after this timer was armed. Defer without
// advancing the attempt; _finishBufferLoad resumes only the active tab.
if (this._isLoadingBuffer) {
if (sessionId === this.activeSessionId) {
const pending = this._pendingDroppedOutputRecovery;
this._pendingDroppedOutputRecovery = {
sessionId,
attempt: pending?.sessionId === sessionId ? Math.max(pending.attempt, attempt) : attempt,
};
}
return;
}
let repainted = false;
let timedOut = false;
try {
@@ -3465,6 +3497,9 @@ class CodemanApp {
if (this._terminalRefreshOwner?.sessionId === sessionId) return false;
const refreshOwner = { sessionId };
this._terminalRefreshOwner = refreshOwner;
// Reload history stands aside for the length of this refresh (see
// _historyReloadActionEligible); take it off an already-painted bar now.
this._syncHistoryReloadAction?.();
try {
// A shell can retain a multi-megabyte/100k-line tmux history. Automatic
// recovery stays bounded just like normal shell selection (tmux's rendered
@@ -3473,6 +3508,8 @@ class CodemanApp {
// TUI modes still recover the whole picture, with the downgrade guard for
// repaint-mode panes whose tmux capture can be smaller than xterm's buffer.
const useFullHistory = this.sessions.get(sessionId)?.mode !== 'shell';
// Keep live output received during the capture marked for another full-history pull.
const liveOutputGen = this._liveOutputGen?.get(sessionId) || 0;
let capture = await this._fetchTerminalCapture(
useFullHistory
? `/api/sessions/${sessionId}/terminal?full=1`
@@ -3481,7 +3518,13 @@ class CodemanApp {
);
let headersReceivedAt = capture.headersAt;
let data = capture.json?.data ?? {};
// The full capture would shrink the buffer: tmux holds less than the browser,
// the signal `_maybeRefetchFullHistory` retires Reload history on. Record it
// and apply it past the ownership guard below, so the next tap does not run
// another forced full capture only to be refused.
let refusedFullCapture = false;
if (useFullHistory && data.terminalBuffer && this._replayWouldShrinkBuffer(data.terminalBuffer)) {
refusedFullCapture = true;
capture = await this._fetchTerminalCapture(`/api/sessions/${sessionId}/terminal?tail=${TERMINAL_TAIL_SIZE}`);
headersReceivedAt = capture.headersAt;
data = capture.json?.data ?? {};
@@ -3495,6 +3538,10 @@ class CodemanApp {
// pane), and an error envelope is not a capture at all.
if (this.activeSessionId !== sessionId || this._terminalRefreshOwner !== refreshOwner) return false;
if (capture.json?.success !== false) this._notePaneHistory?.(sessionId, data);
if (refusedFullCapture) {
(this._historyReloadDismissed ||= new Set()).add(sessionId);
this._syncHistoryReloadAction?.();
}
if (data.terminalBuffer) {
// This refresh is SERVER-triggered, so a user quietly reading scrollback
// did not ask for it and must not be dragged to the bottom by it (#259).
@@ -3507,12 +3554,23 @@ class CodemanApp {
// after them and fuse into the buffer written below. See
// _resetTerminalForReplay.
this._resetTerminalForReplay();
await this.chunkedTerminalWrite(
const { completed } = await this.chunkedTerminalWrite(
data.terminalBuffer,
TERMINAL_CHUNK_SIZE,
undefined,
this._bufferLoadFinishOpts(data, headersReceivedAt)
);
if (
completed &&
this.activeSessionId === sessionId &&
this._terminalRefreshOwner === refreshOwner &&
data.source === 'mux-full-history' &&
(this._liveOutputGen?.get(sessionId) || 0) === liveOutputGen
) {
this._liveOutputSinceFullPull?.delete(sessionId);
this._historyReloadDismissed?.delete(sessionId);
this._syncHistoryReloadAction?.();
}
// A tail fetch can be partial, and the banner would otherwise keep
// describing the pre-refresh buffer (#258).
this._setHistoryTruncation(sessionId, data);
@@ -3549,7 +3607,11 @@ class CodemanApp {
console.error('needsRefresh reload failed:', err);
return err?.name === 'AbortError' ? 'deadline' : false;
} finally {
if (this._terminalRefreshOwner === refreshOwner) this._terminalRefreshOwner = null;
if (this._terminalRefreshOwner === refreshOwner) {
this._terminalRefreshOwner = null;
// Reload history stands aside while this refresh fetches; offer it again.
this._syncHistoryReloadAction?.();
}
}
}
@@ -4134,15 +4196,85 @@ class CodemanApp {
}
}
// Session-owned reservations survive pane switches and terminal replacement.
_inputFifo(sessionId) {
if (!this._inputFifos) this._inputFifos = new Map();
if (!this._inputFifos.has(sessionId)) this._inputFifos.set(sessionId, { ops: [], timer: null, draining: false });
return this._inputFifos.get(sessionId);
}
_enqueueInput(sessionId, ops) {
if (!sessionId || (this.sessions && !this.sessions.has(sessionId))) return;
const fifo = this._inputFifo(sessionId);
fifo.ops.push(...ops);
this._drainInputFifo(sessionId, fifo);
}
_drainInputFifo(sessionId, fifo) {
if (fifo.timer !== null || fifo.draining) return;
fifo.draining = true;
try {
while (fifo.ops.length && this._inputFifos.get(sessionId) === fifo) {
const op = fifo.ops.shift();
if (op.gap !== undefined) {
fifo.timer = setTimeout(() => {
fifo.timer = null;
if (this._inputFifos.get(sessionId) === fifo) this._drainInputFifo(sessionId, fifo);
}, op.gap);
break;
}
if (op.key) {
fetch(`/api/sessions/${sessionId}/send-key`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: op.key }),
}).catch(() => {});
} else if (op.write) {
this._enqueueReliableInput(sessionId, op.write, { useMux: op.useMux });
}
}
} finally {
fifo.draining = false;
}
}
_sealPendingInput(sessionId) {
const timer = this._inputFlushTimeout?.get(sessionId);
clearTimeout(timer);
this._inputFlushTimeout?.delete(sessionId);
const text = this._pendingInput?.get(sessionId);
this._pendingInput?.delete(sessionId);
if (text) this._enqueueInput(sessionId, [{ write: text }]);
}
_settleMainInput(reason) {
const sessionId = this.activeSessionId;
this._iosNativeInput?.settle?.();
this._sealPendingInput(sessionId);
if (sessionId) this._flushLocalEchoTo(sessionId);
this._iosNativeInput?.reset?.(reason);
this._mobileImePreview?.reset?.();
this._mobileImeCommitOutputSeq = null;
this._localEchoOverlay?.clear();
}
/**
* Public input entry point — name/signature kept for all call sites.
* Records the input durably, then delivers it reliably (exactly-once). Never
* blocks the keystroke flush; never silently drops on a half-open socket.
* Seals the session's batched keystrokes, then enqueues the input on that
* session's FIFO, which hands it to the durable exactly-once layer
* (_enqueueReliableInput). It can wait behind an earlier `gap` (a delayed
* Enter); it never silently drops on a half-open socket.
* @param {string} sessionId
* @param {string} input
* @param {{useMux?: boolean}} [opts] - useMux only affects the POST fallback.
*/
_sendInputAsync(sessionId, input, opts) {
this._sealPendingInput(sessionId);
this._enqueueInput(sessionId, [{ write: input, ...opts }]);
}
// Durable delivery starts here; FIFO gaps order enqueueing, not ACK completion.
_enqueueReliableInput(sessionId, input, opts) {
if (!sessionId || !input) return;
const useMux = opts?.useMux === true;
// Both transports refuse a frame over the server's limit (issue #484), and a
@@ -4929,6 +5061,11 @@ class CodemanApp {
document.body.classList.toggle('cjk-input-visible', !!showCjk);
cjkEl.style.display = showCjk ? 'block' : 'none';
cjkEl.setAttribute('aria-hidden', showCjk ? 'false' : 'true');
if (typeof CjkInput !== 'undefined') {
CjkInput.setHoldUntilEnter?.(
!!(settings.cjkInputHoldUntilEnter ?? defaults.cjkInputHoldUntilEnter ?? false)
);
}
if (!showCjk) window.cjkActive = false;
if (typeof KeyboardHandler !== 'undefined') KeyboardHandler.updateLayoutForKeyboard();
}
@@ -4964,6 +5101,9 @@ class CodemanApp {
// Clear pending terminal writes
this._clearTimer('syncWaitTimeout');
this._clearTimer('_clientDropRecoveryTimer');
// A recovery deferred behind a load would otherwise resume once the next
// load (the reconnect's own refresh) finishes, and run a second full capture.
this._pendingDroppedOutputRecovery = null;
this.pendingWrites = [];
this.writeFrameScheduled = false;
// Release the one-chunk-in-flight gate with the rest of the write queue.
@@ -6668,6 +6808,7 @@ class CodemanApp {
if (state && state.generation !== selectGen) return;
this.terminalLoadStates.delete(sessionId);
this._updateTerminalLoadTab(sessionId);
if (state) this._syncHistoryReloadAction?.();
}
_updateTerminalLoadTab(sessionId) {
@@ -9379,7 +9520,25 @@ class CodemanApp {
// `skipSnapshot`: the tile grid opening on the session it parks
// (tile-grid.js openTileGrid), whose snapshot closing the grid discards.
_cleanupPreviousSession(newSessionId, { skipSnapshot = false } = {}) {
_cleanupPreviousSession(newSessionId, { skipSnapshot = false, keepCjkDraft = false } = {}) {
// Clear CJK input to prevent sending stale text to the wrong session.
// Must go through CjkInput.clear() — a raw value wipe leaves the module's
// pending flush timers armed and drops the phantom char it relies on.
// A held Send on Enter draft survives a reload of the same session: nothing
// switched, and the answer would be gone. On a real switch it is stashed for
// the session being left (selectSession restores it on the way back), so a
// stray swipe does not lose it. Live mode still clears, since a pending
// debounced flush could fire mid-reconnect.
if (typeof CjkInput !== 'undefined') {
if (!(keepCjkDraft && CjkInput.holdUntilEnter)) {
if (this.activeSessionId) CjkInput.stashDraft?.(this.activeSessionId);
CjkInput.clear();
}
} else {
const cjkEl = document.getElementById('cjkInput');
if (cjkEl) cjkEl.value = '';
}
this._settleMainInput('session');
// Snapshot the OUTGOING session's xterm rendered state (viewport + scrollback +
// colors/attrs) before the terminal gets cleared/reset. Lets us restore the
// exact view on switch-back rather than replaying codex's byte stream, which
@@ -9429,16 +9588,6 @@ class CodemanApp {
// Close WebSocket for previous session (new one opens after buffer load)
this._disconnectWs();
// Clear CJK input to prevent sending stale text to the wrong session.
// Must go through CjkInput.clear() — a raw value wipe leaves the module's
// pending flush timers armed and drops the phantom char it relies on.
if (typeof CjkInput !== 'undefined') {
CjkInput.clear();
} else {
const cjkEl = document.getElementById('cjkInput');
if (cjkEl) cjkEl.value = '';
}
// Clean up flicker filter state when switching sessions
this._clearTimer('flickerFilterTimeout');
this.flickerFilterBuffer = '';
@@ -9450,6 +9599,7 @@ class CodemanApp {
this._tabCompletionBaseText = null;
this._clearTimer('_tabCompletionFallback');
this._clearTimer('_clientDropRecoveryTimer');
this._pendingDroppedOutputRecovery = null;
this._terminalRefreshOwner = null;
// Clean up pending terminal writes to prevent old session data from appearing in new session
@@ -9484,7 +9634,6 @@ class CodemanApp {
if (ta) ta.dispatchEvent(new CompositionEvent('compositionend', { data: '' }));
}
} catch {}
this._flushLocalEchoTo(this.activeSessionId);
this._localEchoOverlay?.clear();
// Predictions are ephemeral + already sent: nothing to save/restore
// across a tab switch (unlike the buffer overlay's setFlushed machinery)
@@ -9580,8 +9729,8 @@ class CodemanApp {
}
/**
* "Load more history": re-pull the whole tmux scrollback when the user scrolls up
* while already at the top of what the browser has.
* Re-pull tmux history automatically at the top, or explicitly from the
* history banner's Load full history / Reload history actions.
*
* xterm's buffer is only ever a WINDOW onto tmux's real history, and two things
* shrink it. tmux repaints the pane rectangle instead of emitting linefeeds
@@ -9592,9 +9741,11 @@ class CodemanApp {
* everything (history-limit 100k by default), so the fix is to go ask for it with
* the same `?full=1` capture a page reload uses (issue #205).
*
* On demand rather than automatic because that capture is unbounded-ish work: at
* the default history limit it can be megabytes, which is fine to pay when the
* user is explicitly reaching for history and not fine on every tab switch.
* Automatic pulls are top-only and cooldown/latch guarded: a synchronous
* capture can cost about 1 s at 100k lines (1,068 ms median for 12.1 MB of
* 120-character lines, `capture-pane -p -e -J -S -100000`) and blocks the server event loop.
* The manual Reload history action uses a content anchor to hold the reader's
* place even when new history fills a gap below them.
*
* NEVER a downgrade: for a repaint-mode CLI pane tmux keeps no history of its
* own, so the capture can be THINNER than what xterm already holds and the
@@ -9603,9 +9754,13 @@ class CodemanApp {
* gets a much longer cooldown so a hollow pane stops re-fetching megabytes on
* every scroll-up (issue #205, round 2).
*/
async _maybeRefetchFullHistory({ force = false } = {}) {
async _maybeRefetchFullHistory({ force = false, anchor = 'top' } = {}) {
const sessionId = this.activeSessionId;
if (!sessionId || this._fullHistoryRepullInFlight || this._isLoadingBuffer) return;
// A drop-recovery refresh owns this session until its replay ends: a second
// capture would run back to back with it, and its load would replace this
// pull's queue, losing the output that arrived during the download.
if (this._terminalRefreshOwner?.sessionId === sessionId) return;
if (this.detachedSessions?.has(sessionId)) return;
// The parked main terminal has no history to pull while tiles own the screen.
if (this._tilesOwnTerminal?.()) return;
@@ -9637,11 +9792,16 @@ class CodemanApp {
if (!force && now - (this._fullHistoryRepullAt.get(sessionId) || 0) < cooldown) return;
this._fullHistoryRepullAt.set(sessionId, now);
this._fullHistoryRepullInFlight = true;
const loadOwner = this._beginBufferLoad();
let replayed = false;
// The session-id check below cannot see a tab switch that came BACK during
// the fetch (A -> B -> A): the id matches again while `selectSession` is
// replaying its own capture, and the reset below would land in the middle
// of that write. The select generation moves on every switch, so it can.
const selectGen = this._selectGeneration;
// Queued output replayed after this load may mark the session again. Never
// clear that newer generation along with the capture's original mark.
const liveOutputGen = this._liveOutputGen?.get(sessionId) || 0;
try {
const requestStartedAt = performance.now();
const capture = await this._fetchTerminalCapture(
@@ -9660,6 +9820,22 @@ class CodemanApp {
// recording its empty data would forget the count and hand the next
// gesture back to the paging fallback, the bug this pull exists to avoid.
if (selectGen === this._selectGeneration && capture.json?.success !== false) this._notePaneHistory?.(sessionId, payload);
// A manual reload answered by anything but a full mux capture (an empty
// response, or the byte-history fallback the route returns when the pane
// capture is blank or failed) cannot fill the gap, and only a mux replay
// clears the mark: offering it again would repeat the forced capture on
// every tap. Retire it until the next `mux-full-history` replay. Only for
// the request still current: a slow answer from before an A -> B -> A
// switch must not retire the action a newer capture of A already cleared.
if (
anchor === 'content' &&
this.activeSessionId === sessionId &&
selectGen === this._selectGeneration &&
capture.json?.success !== false &&
payload.source !== 'mux-full-history'
) {
(this._historyReloadDismissed ||= new Set()).add(sessionId);
}
const buffer = payload.terminalBuffer;
const timing = {
trigger: force ? 'full-history-button' : 'full-history-scroll',
@@ -9720,6 +9896,7 @@ class CodemanApp {
timing.totalMs = performance.now() - requestStartedAt;
this._recordTerminalLoadTiming(timing);
(this._fullHistoryRepullUseless ||= new Set()).add(sessionId);
(this._historyReloadDismissed ||= new Set()).add(sessionId);
this._logScrollRouting?.('repull-refused-downgrade');
// The browser already holds more than tmux can give back, so there is
// nothing further to offer and the indicator must stop promising it.
@@ -9737,6 +9914,9 @@ class CodemanApp {
this._fullHistoryRepullUseless?.delete(sessionId);
const rowsBefore = this.terminal.buffer.active.length;
const replayStartedAt = performance.now();
const viewportAnchor = anchor === 'content' ? this._captureViewportAnchor() : null;
// Ordered, not summed: each move clamps at the buffer edge as it would live.
if (anchor === 'content') this._earlyReplayTravel = { sessionId, moves: [] };
this._resetTerminalForReplay();
const {
parsedAt,
@@ -9745,11 +9925,17 @@ class CodemanApp {
} = await this.chunkedTerminalWrite(
buffer,
TERMINAL_CHUNK_SIZE,
sessionId,
loadOwner,
this._bufferLoadFinishOpts(payload, headersReceivedAt)
);
replayed = true; // chunkedTerminalWrite finished this load with the capture cutoff.
timing.resetAndParseMs = parsedAt - replayStartedAt;
if (!completed || this.activeSessionId !== sessionId || selectGen !== this._selectGeneration) return;
if (payload.source === 'mux-full-history' && (this._liveOutputGen?.get(sessionId) || 0) === liveOutputGen) {
this._liveOutputSinceFullPull?.delete(sessionId);
this._historyReloadDismissed?.delete(sessionId);
this._syncHistoryReloadAction?.();
}
// Keep shell tab restores bounded too. A user-triggered full-history pull
// may be tens of MB; caching it would replay that whole payload again on
// the next tab switch before the normal 1MB tail fetch replaces it.
@@ -9762,9 +9948,26 @@ class CodemanApp {
// UPWARD, so what used to be row 0 (what they were looking at) is now `delta`
// rows down; scrolling there reveals the recovered history above it instead
// of teleporting them to the bottom the way a normal buffer load does.
const delta = parsedBufferLength - rowsBefore;
if (delta > 0) this.terminal.scrollToLine(delta);
else this.terminal.scrollToTop();
if (anchor === 'content') {
const baseY = this.terminal.buffer.active.baseY;
const clamp = (row) => Math.max(0, Math.min(baseY, row));
let row = this._restoreViewportAnchor(viewportAnchor);
// Replay travel bypassed the live scroll handler's notice update, so
// decide it per move as that handler would: an upward move that reaches
// row 0 reveals the notice, a downward move back at live output retires it.
let reveal = null;
for (const move of this._earlyReplayTravel.moves) {
row = clamp(row + move);
if (move < 0 && row === 0) reveal = true;
else if (move > 0 && row >= baseY - 2) reveal = false;
}
this.terminal.scrollToLine(row);
if (reveal !== null) this._setHistoryNoticeRevealed?.(reveal ? sessionId : null);
} else {
const delta = parsedBufferLength - rowsBefore;
if (delta > 0) this.terminal.scrollToLine(delta);
else this.terminal.scrollToTop();
}
// The load's own replay sampled the sticky-scroll baseline while the
// terminal sat at the bottom of a just-rewritten buffer, so the next
// flush would scroll back down and undo the restore above. This path is
@@ -9780,7 +9983,10 @@ class CodemanApp {
} catch {
// Transient (offline, 5xx) — the next scroll-up past the cooldown retries.
} finally {
if (!replayed) this._finishBufferLoad(loadOwner, { flushQueued: true, since: 0 });
if (anchor === 'content') this._earlyReplayTravel = null;
this._fullHistoryRepullInFlight = false;
this._syncHistoryReloadAction?.();
}
}
@@ -9856,6 +10062,44 @@ class CodemanApp {
this._renderHistoryTruncationBanner();
}
/** Whether the active session can offer a manual, content-anchored repair. */
_historyReloadActionEligible() {
const sessionId = this.activeSessionId;
const session = this.sessions.get(sessionId);
// Cheap state checks first: the terminal is read only for a marked session.
// `_paneHistoryLines` is deliberately not consulted: it is recorded at the last
// load, so a session first opened empty keeps 0 after the very burst that
// opens the gap (#814). A pane that really holds no history (fullscreen
// Claude) captures one screen, `_replayWouldShrinkBuffer` refuses it, and the
// refusal dismisses the action until the next `mux-full-history` replay.
// Docker and adopted sessions are left out: their local pane hosts a nested
// tmux client in the alternate screen, so `?full=1` returns one screen that
// the downgrade guard always refuses (the exclusions `paneKeepsNoHistory`
// uses in selectSession). Remote sessions stay eligible, since the route
// splices the remote scrollback into their capture.
return !!(this.loadAppSettingsFromStorage?.()?.historyReloadAction !== false &&
session && session.mode !== 'shell' && !session.docker && !session.adopt &&
this._liveOutputSinceFullPull?.has(sessionId) &&
!this._isLoadingBuffer &&
!this.terminalLoadStates?.has(sessionId) && // Tab switches set this before the buffer load opens.
this._terminalRefreshOwner?.sessionId !== sessionId && // A drop-recovery refresh is fetching.
!this._fullHistoryRepullInFlight && !this.detachedSessions?.has(sessionId) &&
!this._historyReloadDismissed?.has(sessionId) && !this._tilesOwnTerminal?.() &&
!this.isTerminalAtBottom());
}
/** Only eligibility/session/loading transitions may rebuild the banner. */
_syncHistoryReloadAction() {
const sessionId = this.activeSessionId;
const eligible = this._historyReloadActionEligible();
const loading = !!sessionId && this._historyReloadActionLoadingFor === sessionId &&
!this._historyReloadDismissed?.has(sessionId);
const last = this._historyReloadActionState;
if (last && last.sessionId === sessionId && last.eligible === eligible && last.loading === loading) return;
this._historyReloadActionState = { sessionId, eligible, loading };
this._renderHistoryTruncationBanner();
}
/**
* Paint the partial-history banner for the active session.
*
@@ -9863,12 +10107,12 @@ class CodemanApp {
* is gone forever" are not the same message and the old single boolean could
* not tell them apart:
* - recoverable → offer to load the rest
* - exhausted → say so plainly, offer nothing
* - exhausted → say so plainly
* - at the limit → the full capture ITSELF hit the byte ceiling
*
* Shown only while revealed (`_setHistoryNoticeRevealed`: the user scrolled
* to the top of this tab's buffer) and never again for a session whose notice
* the user dismissed on this page.
* Notices wait for a scroll to the top and respect their page-long dismissal.
* Independently, eligible marked sessions offer Reload history while reading;
* the same bar carries it without duplicating a Load full history control.
*/
_renderHistoryTruncationBanner() {
const bar = document.getElementById('historyTruncationBar');
@@ -9876,47 +10120,96 @@ class CodemanApp {
const sessionId = this.activeSessionId;
const state = sessionId ? this._historyTruncation?.get(sessionId) : null;
const notice = computeHistoryTruncationNotice(state || {});
if (
!notice.visible ||
this._historyNoticeRevealedFor !== sessionId ||
this._historyNoticeDismissed?.has(sessionId)
) {
const showNotice = notice.visible && this._historyNoticeRevealedFor === sessionId &&
!this._historyNoticeDismissed?.has(sessionId);
const eligible = this._historyReloadActionEligible?.() ?? false;
const loading = !!sessionId && this._historyReloadActionLoadingFor === sessionId &&
!this._historyReloadDismissed?.has(sessionId);
this._historyReloadActionState = { sessionId, eligible, loading };
if (!showNotice && !eligible && !loading) {
bar.hidden = true;
return;
}
// `#historyTruncationBar` is a polite live region. Only the truncation
// notice is news worth announcing; a reload-only bar re-renders on every
// eligible scroll-up in a busy tab, so it stays silent and is reached by Tab.
// Set before the rewrite below, so the new content is judged by it.
bar.setAttribute('aria-live', showNotice ? 'polite' : 'off');
bar.textContent = '';
const label = document.createElement('span');
label.className = 'history-trunc-text';
label.textContent = notice.message;
label.textContent = showNotice ? notice.message : 'Recent output may be missing from this view.';
bar.appendChild(label);
if (notice.canLoadMore) {
if (showNotice && notice.canLoadMore) {
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'history-trunc-load';
btn.textContent = 'Load full history';
// A content-anchored pull from here stands in for Reload history, so it
// shares Reload's loading state: the pull flips Reload eligibility, and the
// re-render that follows must not bring the button back enabled mid-pull.
btn.disabled = loading;
btn.textContent = loading ? 'Loading…' : 'Load full history';
btn.onclick = () => {
btn.disabled = true;
btn.textContent = 'Loading…';
// Forced: the cooldown exists to throttle scroll gestures, not choices.
this._maybeRefetchFullHistory({ force: true }).finally(() => {
// When Reload history is eligible, this button is shown in its place
// (one load control per bar), so it must keep the reader's line the same
// way. Checked at click time, not render time: the bar only re-renders on
// eligibility transitions, and the reader may have scrolled since.
const anchor = this._historyReloadActionEligible() ? 'content' : 'top';
// The top anchor keeps no loading state: it would hold the bar up after
// a scroll back to live output, where it hides today.
if (anchor === 'content') {
this._historyReloadActionLoadingFor = sessionId;
this._syncHistoryReloadAction();
}
return this._maybeRefetchFullHistory({ force: true, anchor }).finally(() => {
if (anchor === 'content' && this._historyReloadActionLoadingFor === sessionId) {
this._historyReloadActionLoadingFor = null;
}
this._renderHistoryTruncationBanner();
});
};
bar.appendChild(btn);
} else if (eligible || loading) {
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'history-trunc-load';
btn.disabled = loading;
btn.textContent = loading ? 'Loading…' : 'Reload history';
btn.onclick = () => {
if (!this._historyReloadActionEligible()) {
this._syncHistoryReloadAction();
return;
}
btn.disabled = true;
btn.textContent = 'Loading…';
this._historyReloadActionLoadingFor = sessionId;
this._syncHistoryReloadAction();
return this._maybeRefetchFullHistory({ force: true, anchor: 'content' }).finally(() => {
if (this._historyReloadActionLoadingFor === sessionId) this._historyReloadActionLoadingFor = null;
this._syncHistoryReloadAction();
});
};
bar.appendChild(btn);
}
const dismiss = document.createElement('button');
dismiss.type = 'button';
dismiss.className = 'history-trunc-dismiss';
dismiss.setAttribute('aria-label', 'Dismiss history notice');
// Name what the × actually dismisses: a reload-only bar has no notice.
dismiss.setAttribute('aria-label', showNotice ? 'Dismiss history notice' : 'Dismiss Reload history');
dismiss.textContent = '×';
dismiss.onclick = () => {
// Sticky for this session until the page reloads: a dismissed notice used
// to come straight back on the next tab switch.
(this._historyNoticeDismissed ||= new Set()).add(sessionId);
bar.hidden = true;
// One × dismisses everything this bar carried. A notice dismissal sticks
// for the lifetime of this page; a reload dismissal lasts until a
// successful full mux replay clears the session's mark.
if (showNotice) (this._historyNoticeDismissed ||= new Set()).add(sessionId);
if (eligible || loading) (this._historyReloadDismissed ||= new Set()).add(sessionId);
this._renderHistoryTruncationBanner();
};
bar.appendChild(dismiss);
@@ -9973,11 +10266,19 @@ class CodemanApp {
if (this._tileGrid.has(sessionId)) return this._selectTiledSession(sessionId, options);
if (options?.auto === true && !options?.leaveTiles) return;
this.closeTileGrid({ keepStored: true, reselect: false });
// The focused tile's Send on Enter draft: the null below hides that
// session from _cleanupPreviousSession, which would clear it unstashed.
if (typeof CjkInput !== 'undefined' && this.activeSessionId) CjkInput.stashDraft?.(this.activeSessionId);
// The parked terminal still holds what it showed before the grid opened;
// with no active id, the switch below snapshots none of it.
this.activeSessionId = null;
}
// A reload of the session already shown (tapping its own tab, the geometry
// retry) is not a switch: _cleanupPreviousSession keeps a Send on Enter
// draft for it, which it cannot tell on its own once activeSessionId is null.
let reloadingSameSession = false;
if (this.activeSessionId === sessionId && forceReload) {
reloadingSameSession = true;
this.terminalBufferCache?.delete(sessionId);
this._xtermSnapshots?.delete(sessionId);
try { localStorage.removeItem(`codeman-xs-${sessionId}`); } catch {}
@@ -9996,7 +10297,7 @@ class CodemanApp {
// hides this one from it. Flush first or the characters are cleared
// unread. The geometry replay re-enters here with no gesture behind it,
// so on a touch device this fires while the user is still typing.
this._flushLocalEchoTo(sessionId);
this._settleMainInput('session');
this.activeSessionId = null;
}
// Focus terminal SYNCHRONOUSLY before any await — iOS Safari only honors
@@ -10024,9 +10325,11 @@ class CodemanApp {
// A session tab takes the stage back from any active web tab.
this._hideWebviewLayer?.();
this._cleanupPreviousSession(sessionId);
this._cleanupPreviousSession(sessionId, { keepCjkDraft: reloadingSameSession });
this.activeSessionId = sessionId;
this._activateFileBrowserSession?.(sessionId);
if (typeof CjkInput !== 'undefined') CjkInput.restoreDraft?.(sessionId);
this._syncHistoryReloadAction?.();
// A keyboard row hold belongs to the session it was taken for: release it here
// if this one resizes instead (the geometry work below then fits it).
this._reconcileKeyboardHold?.({ resize: false });
@@ -10330,9 +10633,12 @@ class CodemanApp {
!session?.remote && !session?.docker && !session?.adopt && this._paneHistoryLines?.get(sessionId) === 0;
const useFullHistory = !shellSession && (paneKeepsNoHistory || !this._fullHistoryLoaded.has(sessionId));
if (useFullHistory) this._fullHistoryLoaded.add(sessionId);
// Sample before fetching, as other replays do, so output during download keeps the session marked.
const liveOutputGen = this._liveOutputGen?.get(sessionId) || 0;
const fetchStartedAt = performance.now();
const tailUrl = `/api/sessions/${sessionId}/terminal?tail=${TERMINAL_TAIL_SIZE}`;
let capture;
let fullHistoryReplay = useFullHistory;
try {
capture = await this._fetchTerminalCapture(
useFullHistory
@@ -10353,6 +10659,7 @@ class CodemanApp {
_crashDiag.log('FULL CAPTURE ABORTED → tail');
// It never loaded, so the next select must be allowed to try again.
this._fullHistoryLoaded.delete(sessionId);
fullHistoryReplay = false;
capture = await this._fetchTerminalCapture(tailUrl);
}
const headersReceivedAt = capture.headersAt;
@@ -10398,7 +10705,7 @@ class CodemanApp {
// cannot be actioned, and is indistinguishable from real CLI output.
this._setHistoryTruncation(sessionId, data);
// Use chunked write for large buffers to avoid UI jank
const { parsedAt: freshParsedAt } = await this.chunkedTerminalWrite(
const { parsedAt: freshParsedAt, completed } = await this.chunkedTerminalWrite(
data.terminalBuffer,
TERMINAL_CHUNK_SIZE,
bufferLoadOwner,
@@ -10409,6 +10716,11 @@ class CodemanApp {
this._clearTerminalLoadState(sessionId, selectGen);
return;
}
if (fullHistoryReplay && data.source === 'mux-full-history' && completed && (this._liveOutputGen?.get(sessionId) || 0) === liveOutputGen) {
this._liveOutputSinceFullPull?.delete(sessionId);
this._historyReloadDismissed?.delete(sessionId);
this._syncHistoryReloadAction?.();
}
// Ensure terminal is scrolled to bottom after buffer load
this.terminal.scrollToBottom();
}
@@ -10808,6 +11120,14 @@ class CodemanApp {
this._activeRename.cancel();
}
this.sessions.delete(sessionId);
const fifo = this._inputFifos?.get(sessionId);
clearTimeout(fifo?.timer);
this._inputFifos?.delete(sessionId);
const inputTimer = this._inputFlushTimeout?.get(sessionId);
clearTimeout(inputTimer);
this._inputFlushTimeout?.delete(sessionId);
this._pendingInput?.delete(sessionId);
this._lastKeystrokeTime?.delete(sessionId);
// Remove from tab order
const orderIndex = this.sessionOrder.indexOf(sessionId);
if (orderIndex !== -1) {
@@ -10816,6 +11136,10 @@ class CodemanApp {
}
this.terminalBuffers.delete(sessionId);
this.terminalBufferCache.delete(sessionId);
this._liveOutputSinceFullPull?.delete(sessionId);
this._historyReloadDismissed?.delete(sessionId);
this._syncHistoryReloadAction?.();
this._liveOutputGen?.delete(sessionId);
this._clearHistoryTruncation(sessionId);
this._xtermSnapshots?.delete(sessionId);
try { localStorage.removeItem(`codeman-xs-${sessionId}`); } catch {}
@@ -10823,6 +11147,7 @@ class CodemanApp {
this._flushedOffsets?.delete(sessionId);
this._flushedTexts?.delete(sessionId);
if (typeof KeyboardAccessoryBar !== 'undefined') KeyboardAccessoryBar.discardComposerDraft?.(sessionId);
if (typeof CjkInput !== 'undefined') CjkInput.discardDraft?.(sessionId);
// Drop any durably-queued input for a session that's actually gone (deleted/
// exited). Not a lost prompt — the target no longer exists. Only reached on
// real session removal, never on a tab switch.
@@ -11104,6 +11429,9 @@ class CodemanApp {
this._retireUrlSession();
// Home is a choice to leave the grid too; it is remembered for Tiles.
this.closeTileGrid?.({ keepStored: true, reselect: false });
// A Send on Enter draft goes with its session: the null below hides that
// session from the next _cleanupPreviousSession, which would clear it unstashed.
if (typeof CjkInput !== 'undefined' && this.activeSessionId) CjkInput.stashDraft?.(this.activeSessionId);
// Deselect active session and show welcome screen
this.activeSessionId = null;
try { localStorage.removeItem('codeman-active-session'); } catch {}
+2 -2
View File
@@ -112,7 +112,7 @@ const MOBILE_RESIZE_RETRY_MS = 30000; // Small-viewport resize re-send whi
const AUTO_CLOSE_NOTIFICATION_MS = 8000; // Auto-close browser notifications
const DEFAULT_TOAST_DURATION_MS = 3000; // How long a corner toast stays by default
const MIN_NOTIFICATION_DURATION_MS = 1000; // Shortest configurable toast / browser-notification time
const MAX_NOTIFICATION_DURATION_MS = 300000; // General UI throttle delay
const MAX_NOTIFICATION_DURATION_MS = 300000; // Longest configurable toast / browser-notification time
const TERMINAL_CHUNK_SIZE = 32 * 1024; // 32KB chunks for terminal buffer loading
const TERMINAL_TAIL_SIZE = 1024 * 1024; // 1MB tail for initial load (more scrollback on tab switch)
// A shell's automatic loads (tab select, drop recovery, a tile's load) read
@@ -130,7 +130,7 @@ const TERMINAL_TAIL_SIZE = 1024 * 1024; // 1MB tail for initial load (more s
const SHELL_LOAD_HISTORY_LINES = 10000;
const SHELL_LOAD_BASE_QUERY = `full=1&tail=${TERMINAL_TAIL_SIZE}&alt=recording`;
const SHELL_LOAD_QUERY = `${SHELL_LOAD_BASE_QUERY}&lines=${SHELL_LOAD_HISTORY_LINES}`;
const SYNC_WAIT_TIMEOUT_MS = 50; // System stats polling
const SYNC_WAIT_TIMEOUT_MS = 50; // Wait timeout for terminal sync
const TUI_REDRAW_SETTLE_MS = 400; // Grace for a TUI to redraw after a real resize, before fetching its buffer
// Z-index base values for layered floating windows
+30
View File
@@ -743,9 +743,21 @@
"For local Claude sessions, opening the on-screen keyboard keeps the session's size and scrolls the view instead, so Claude does not reprint its screen and lose transcript lines. Full-screen interfaces (Codex, Claude's fullscreen mode) are resized as before.":
'对于本地 Claude 会话,打开屏幕键盘时会保持会话尺寸并改为滚动视图,这样 Claude 不会重绘屏幕而丢失对话记录行。全屏界面(Codex、Claude 的全屏模式)仍像以前一样调整尺寸。',
'CJK Input': '中日韩输入',
'Input Field: Send on Enter': '输入框:按 Enter 发送',
'CJK input (Enter = send, Esc = clear)': '中日韩输入(Enter 发送,Esc 清除)',
'Type, Enter to send (Shift+Enter: new line, Esc: clear)': '输入文字,按 Enter 发送(Shift+Enter 换行,Esc 清除)',
'With CJK Input on, keep typed text in the field until Enter instead of sending it as you type, so you can scroll the terminal and edit before sending. Autocorrect is on in this mode.':
'开启中日韩输入后,输入的文字会保留在输入框中,直到按下 Enter 才发送,而不是边输入边发送,这样可以先滚动终端、编辑后再发送。此模式下会开启自动更正。',
'Extended Keyboard Bar': '扩展键盘栏',
'Gesture Control (beta)': '手势控制(测试版)',
'Wheel Scrolls Local History': '滚轮滚动本地历史',
'History Reload Button': '历史重新加载按钮',
'When scrolled up after new output, offer a Reload history action that re-reads the full tmux history (a full capture on the server).':
'有新输出后向上滚动时,提供“重新加载历史”操作,重新读取完整的 tmux 历史(在服务器上完整捕获)。',
'Recent output may be missing from this view.': '此视图可能缺少最近的输出。',
'Reload history': '重新加载历史',
'Load full history': '加载完整历史',
'Dismiss Reload history': '忽略“重新加载历史”',
'Auto Copy Selection': '自动复制选中内容',
'Selection & clipboard': '选中与剪贴板',
'Auto Copy: selection copied': '自动复制:已复制选中内容',
@@ -1154,6 +1166,16 @@
'Filter by date range': '按日期范围筛选',
'Filter by session status': '按会话状态筛选',
'Filter files...': '筛选文件…',
'Filter loaded files · Enter to search workspace': '筛选已加载的文件 · 按 Enter 搜索工作区',
'Loading folder...': '正在加载文件夹…',
'Incomplete folder': '文件夹内容不完整',
'Load more': '加载更多',
'Retry loading': '重试加载',
'No files in this folder': '此文件夹中没有文件',
'Folder unavailable': '文件夹不可用',
'Workspace changed; refresh files': '工作区已更改,请刷新文件列表',
'No matches in loaded folders · Enter to search workspace': '已加载的文件夹中没有匹配项 · 按 Enter 搜索工作区',
'Search incomplete; no matches in scanned files': '搜索未完成;已扫描的文件中没有匹配项',
Worktree: '工作树',
'Session folder': '会话文件夹',
'Back to worktree': '返回工作树',
@@ -1697,6 +1719,14 @@
function translateDynamic(source) {
const patterns = [
[
/^(\d+) match(?:es)? in loaded folders · Enter to search workspace$/,
(_m, n) => `已加载的文件夹中有 ${n} 个匹配项 · 按 Enter 搜索工作区`,
],
[
/^(\d+) files, (\d+) dirs · loaded folders( · hidden shown)?$/,
(_m, files, dirs, hidden) => `${files} 个文件,${dirs} 个文件夹 · 已加载${hidden ? ' · 已显示隐藏项' : ''}`,
],
[/^(\d+) tokens?$/, (_m, count) => `${count} 个 Token`],
[/^(\d+) sessions?$/, (_m, count) => `${count} 个会话`],
[/^(\d+) tasks?$/, (_m, count) => `${count} 个任务`],
+9 -5
View File
@@ -7,7 +7,7 @@
*
* For drag-and-drop: listens on the terminal container for file drops.
*
* @dependency app.js (uses global `app` for sendInput, activeSessionId, showToast)
* @dependency app.js (uses global `app` for _sendInputAsync, _prepareExternalInput, activeSessionId, showToast)
* @dependency panels-ui.js (provides showToast)
*/
@@ -142,6 +142,8 @@ Object.assign(CodemanApp.prototype, {
return;
}
const pane = this._paneForSession?.(sessionId);
if (pane) this._prepareExternalInput?.(pane, 'toolbar-attachment');
const stillActive = this.activeSessionId === sessionId;
// The overlay holds the prompt only while local echo actually owns it. A
// session handed back to plain PTY echo by a composer nav key (echo
@@ -152,6 +154,7 @@ Object.assign(CodemanApp.prototype, {
// goes to the PTY like any other background write.
const overlayOwnsPrompt =
stillActive &&
(!pane || (pane.isPrimary && pane.sessionId === sessionId)) &&
!this._tilesOwnTerminal?.() &&
this._localEchoEnabled &&
this._localEchoOverlay &&
@@ -394,10 +397,11 @@ Object.assign(CodemanApp.prototype, {
const paths = results.filter(Boolean);
if (paths.length > 0 && options.insert !== false) {
// Insert all paths in one shot, space-separated, in selection order, into
// the session the batch was uploaded TO. Not sendInput(): it re-reads
// activeSessionId, and after the awaits above that is whatever tab the
// user switched to mid-upload, so the paths landed in the wrong session.
// Same delivery sendInput() uses (durable queue, useMux for the POST path).
// the session the batch was uploaded to, captured before the awaits above,
// not the active tab the user may have switched to mid-upload.
// Delivery uses the durable session-bound path, with useMux for the POST fallback.
const pane = this._paneForSession?.(sessionId);
if (pane) this._prepareExternalInput?.(pane, 'upload-insert', { flushEcho: true });
this._sendInputAsync(sessionId, paths.join(' '), { useMux: true });
}
+18 -2
View File
@@ -13,7 +13,8 @@
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<link rel="apple-touch-icon" href="icon-192.png">
<link rel="manifest" href="manifest.json">
<!-- use-credentials: the manifest fetch otherwise omits the session cookie, so a password-protected install answers 401 and the browser refuses to install the app. -->
<link rel="manifest" href="manifest.json" crossorigin="use-credentials">
<title>Codeman</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Cdefs%3E%3ClinearGradient id='g' x1='0%25' y1='0%25' x2='100%25' y2='100%25'%3E%3Cstop offset='0%25' stop-color='%2360a5fa'/%3E%3Cstop offset='100%25' stop-color='%233b82f6'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect width='32' height='32' rx='6' fill='%230a0a0a'/%3E%3Cpath d='M18 4L8 18h6l-2 10 10-14h-6z' fill='url(%23g)'/%3E%3C/svg%3E">
<link rel="stylesheet" href="styles.css">
@@ -639,7 +640,7 @@
<button type="button" class="file-browser-root-switch" id="fileBrowserRootSwitch" onclick="app.toggleFileBrowserRoot()">Session folder</button>
</div>
<div class="file-browser-search">
<input type="text" id="fileBrowserSearch" placeholder="Filter files..." oninput="app.filterFileBrowser(this.value)">
<input type="text" id="fileBrowserSearch" enterkeyhint="search" placeholder="Filter loaded files · Enter to search workspace" oninput="app.filterFileBrowser(this.value)" onkeydown="if (event.key === 'Enter' && !event.isComposing) { event.preventDefault(); app.searchFileBrowser(this.value); }">
</div>
<div class="file-browser-body" id="fileBrowserTree">
<div class="file-browser-empty">Select a session to view files</div>
@@ -2064,6 +2065,13 @@
</div>
<label class="switch switch-sm"><input type="checkbox" id="appSettingsCjkInput"><span class="slider"></span></label>
</div>
<div class="set-row" data-search="cjk input send on enter hold draft pinned prompt field phone">
<div class="set-row-text">
<span class="set-row-label">Input Field: Send on Enter</span>
<span class="set-row-desc">With CJK Input on, keep typed text in the field until Enter instead of sending it as you type, so you can scroll the terminal and edit before sending. Autocorrect is on in this mode.</span>
</div>
<label class="switch switch-sm"><input type="checkbox" id="appSettingsCjkHoldUntilEnter"><span class="slider"></span></label>
</div>
<div class="set-row" data-search="extended keyboard bar tab esc arrows phone">
<div class="set-row-text">
<span class="set-row-label">Extended Keyboard Bar <span class="set-tag">phone</span></span>
@@ -2153,6 +2161,13 @@
</div>
<label class="switch switch-sm"><input type="checkbox" id="appSettingsTerminalWheelLocal"><span class="slider"></span></label>
</div>
<div class="set-row" data-search="history reload button repair scrollback">
<div class="set-row-text">
<span class="set-row-label">History Reload Button <span class="set-scope">device</span></span>
<span class="set-row-desc">When scrolled up after new output, offer a Reload history action that re-reads the full tmux history (a full capture on the server).</span>
</div>
<label class="switch switch-sm"><input type="checkbox" id="appSettingsHistoryReloadAction"><span class="slider"></span></label>
</div>
<div class="set-row" id="appSettingsWebglRendererItem" data-search="webgl renderer gpu terminal">
<div class="set-row-text">
<span class="set-row-label">WebGL Renderer <span class="set-tag">desktop</span> <span class="set-scope">device</span></span>
@@ -4539,6 +4554,7 @@
<script defer src="mobile-ime-preview.js"></script>
<!-- Forwards committed input events that xterm drops on Android/GBoard soft keyboards. Must precede terminal-ui.js. -->
<script defer src="terminal-keycode229-recovery.js"></script>
<script defer src="terminal-ios-native-input.js"></script>
<!-- Hardened markdown HTML sanitizer (wires DOMPurify). Must precede app.js. -->
<script defer src="sanitize-html.js"></script>
<!-- Owner tab layout projection (grouped vertical rail); pure, read by app.js. -->
+374 -19
View File
@@ -7,6 +7,21 @@
* While this textarea has focus, window.cjkActive = true blocks xterm's onData.
* Arrow keys and function keys are forwarded to PTY directly.
*
* ## Send on Enter (setting cjkInputHoldUntilEnter)
*
* The live mode above streams typed text to the PTY after a short debounce.
* With Send on Enter on, the field is a chat box instead: _flush() holds the
* text, and only Enter sends it, through the sendPrompt callback
* (terminal-ui.js _sendCjkPrompt: a single character is typed, anything longer
* goes as the composer's bracketed paste, Enter is always its own later write,
* and a lone digit at a pending dialog goes without it). Shift+Enter is a
* newline, Esc clears, Backspace and the arrows reach the PTY only from an
* empty field, and so do the Ctrl shortcuts. Autocorrect is on. A held draft
* belongs to one session: a captured target takes precedence over _owner when
* clear() stashes it, and restoreDraft() brings it back when that session is
* shown again, except a clear({ discard: true }) (the keyboard bar's clear-line
* key), which throws it away.
*
* ## Android IME challenge
*
* Android virtual keyboards (WeChat, Sogou, Gboard in Chinese mode) use
@@ -50,6 +65,9 @@
const CjkInput = (() => {
let _textarea = null;
let _send = null;
let _captureTarget = null;
let _target;
let _hasTarget = false;
let _initialized = false;
let _composing = false;
let _flushTimer = null;
@@ -57,6 +75,27 @@ const CjkInput = (() => {
let _dictationActive = false;
let _dictationDecayTimer = null;
let _printableKeydownAt = null;
// Send-on-Enter mode (setting cjkInputHoldUntilEnter): typed text stays in the
// field until Enter, like a chat box, instead of streaming to the PTY as it is
// typed. Lets a phone user scroll the terminal and edit an answer before sending.
let _hold = false;
// Send-on-Enter: the held text as of the last settled input event (phantom
// stripped). Tells a deletion that emptied the field from a Backspace on a field
// that was already empty, and finds the one character an armed Ctrl applies to.
let _heldBase = '';
// Send-on-Enter: delivers a held answer, text first and Enter as a separate
// delayed write, to the session it was typed for (terminal-ui.js).
let _sendPrompt = null;
// Send-on-Enter: whether setHoldUntilEnter() has applied the current mode to
// the field yet, so a repeat call with the same mode leaves the field alone.
let _holdApplied = false;
// Send-on-Enter: held drafts of the sessions switched away from, by session id.
const _drafts = new Map();
// Send-on-Enter: the session last shown, set by restoreDraft. A captured
// target takes precedence; otherwise clear() stashes a held draft under this
// owner, so paths that drop the active session before the next cleanup
// (goHome, _replaceTileGrid and _onTileAdoptedElsewhere) keep the answer.
let _owner = null;
const _listeners = {};
const PHANTOM = '​';
@@ -159,7 +198,21 @@ const CjkInput = (() => {
return str.replace(/​/g, '');
}
function _holdTarget() {
if (!_hasTarget) {
_target = _captureTarget?.();
_hasTarget = true;
}
}
function _targetForSend() {
return _hasTarget ? _target : _captureTarget?.();
}
function _resetToPhantom() {
_heldBase = '';
_target = undefined;
_hasTarget = false;
// Skip redundant writes: every programmatic value/selection mutation can
// desync an Android IME's input session (InputConnection) — after which
// the keyboard composes in its own UI but NO events ever reach the page.
@@ -189,14 +242,156 @@ const CjkInput = (() => {
_t('flush SKIP composing');
return;
}
// Send-on-Enter: nothing leaves the field until Enter (keydown handler).
if (_hold) {
_t('flush SKIP hold');
_holdSettle();
_autoGrow();
return;
}
const val = _strip(_textarea.value);
_t(`flush ${val ? 'send len=' + val.length : 'empty'}`);
if (val) {
_send(val);
_send(val, _targetForSend());
}
_resetToPhantom();
}
/** Send-on-Enter: grow the field with its content (up to the CSS max-height)
* and let the keyboard layout re-read its height. */
function _autoGrow() {
if (!_textarea) return;
// A hidden field (no session shown yet) measures 0: leave the CSS height,
// or it stays a sliver until the next keystroke.
if (_textarea.getClientRects && !_textarea.getClientRects().length) {
_textarea.style.height = '';
return;
}
// Only a touch device grows the field: there it is position: fixed above the
// keyboard. On a desktop it sits in the flex column under the terminal, so
// every line it gained would shrink the terminal box, refit and resize the
// session's PTY (a CLI repaint each time). It stays one line there and
// scrolls inside instead.
if (!document.body?.classList?.contains('touch-device')) {
_textarea.style.height = '';
return;
}
const before = _textarea.style.height;
_textarea.style.height = 'auto';
// border-box: scrollHeight leaves the borders out, offsetHeight - clientHeight adds them back.
_textarea.style.height = `${_textarea.scrollHeight + _textarea.offsetHeight - _textarea.clientHeight}px`;
if (_textarea.style.height !== before && typeof KeyboardHandler !== 'undefined') {
KeyboardHandler.updateLayoutForKeyboard?.();
}
}
/** Send-on-Enter: deliver the held text, then Enter, through `_sendPrompt`
* (terminal-ui.js _sendCjkPrompt). Enter is never part of the text's write:
* Codex takes characters arriving in one burst as a paste and folds an Enter
* inside it into the paste, and Claude Code does the same for a long burst, so
* even `1\r` in one write sits unsent. Returns false when the text is refused
* (too long, no session), so the field keeps it. `sessionId` is the target
* captured when the text started (see _targetForSend). */
function _sendHeld(val, sessionId) {
if (!_sendPrompt) {
_t('hold send DROP no-prompt-path');
return false;
}
return _sendPrompt(val, sessionId) !== false;
}
/** Enter: send what the field holds (or a bare Enter when it is empty) and
* reset it. Returns false when a held answer was refused, which keeps it. */
function _submit() {
_composing = false;
_cancelDebouncedFlush();
clearTimeout(_compositionFlushTimer);
_compositionFlushTimer = null;
let val = _strip(_textarea.value);
// Only blank lines held (Shift+Enter, then Enter): a bare Enter, not a
// newline typed into the CLI.
if (_hold && !val.trim()) val = '';
if (_hold && val) {
// Refused (too long, no session): keep the text so nothing is lost.
if (!_sendHeld(val, _targetForSend())) return false;
} else if (val) {
_send(val + '\r', _targetForSend());
} else {
_send('\r', _targetForSend());
}
_resetToPhantom();
if (_hold) _autoGrow();
return true;
}
function _ctrlArmed() {
return typeof KeyboardAccessoryBar !== 'undefined' && KeyboardAccessoryBar.isCtrlArmed?.() === true;
}
/** Index of the one character `after` adds to `before`, or -1 when the change
* is anything else (several characters, a deletion, a rewrite). */
function _singleInsertionAt(before, after) {
if (after.length !== before.length + 1) return -1;
let i = 0;
while (i < before.length && before[i] === after[i]) i++;
return after.slice(i + 1) === before.slice(i) ? i : -1;
}
/** Send-on-Enter: settle the field after an input event. With the shell bar's
* one-shot Ctrl armed, a single typed character is not held: it leaves the
* field and goes to the PTY, where _handleCjkInput turns it into the control
* byte (`c` → Ctrl+C). Any other change spends the modifier, the same rule
* live mode follows for a multi-character chunk. */
function _holdSettle() {
const before = _heldBase;
const now = _strip(_textarea.value);
_heldBase = now;
if (now === before || !_ctrlArmed()) return;
const at = _singleInsertionAt(before, now);
if (at < 0 || now[at] === '\n') {
KeyboardAccessoryBar.clearCtrl?.();
return;
}
_t('hold ctrl key');
// The control key goes to the session this field's text was captured for;
// with no draft left, the next answer captures its own destination.
const target = _targetForSend();
if (!before) {
_resetToPhantom();
} else {
_textarea.value = PHANTOM + before;
_textarea.setSelectionRange(1 + at, 1 + at);
_heldBase = before;
}
_send(now[at], target);
}
/** Send-on-Enter input handling: nothing is flushed, the field only settles.
* A deletion forwards Backspace to the PTY only when the field was ALREADY
* empty, i.e. the phantom itself was deleted. Deleting the last held
* character (or select-all + delete) must not also delete a character from
* the CLI's own composer, which Attach, image paste, Path and the mic fill. */
function _holdInput(e) {
if (_composing) return; // composed text settles at compositionend (_flush)
if (e.inputType === 'deleteContentBackward' || e.inputType === 'deleteWordBackward') {
const wasEmpty = !_heldBase;
_heldBase = _strip(_textarea.value);
if (!_heldBase) {
if (wasEmpty) _send('\x7f', _targetForSend());
_resetToPhantom();
} else if (!_textarea.value.startsWith(PHANTOM)) {
// Backspace at the very start of the text deleted the phantom: put it
// back with the caret where it was, at the start of the text.
_textarea.value = PHANTOM + _textarea.value;
_textarea.setSelectionRange(1, 1);
}
_autoGrow();
return;
}
_holdSettle();
_autoGrow();
}
/** Cancel any pending debounced flush */
function _cancelDebouncedFlush() {
if (_flushTimer) {
@@ -226,14 +421,17 @@ const CjkInput = (() => {
}
return {
init({ send }) {
init({ send, sendPrompt = null, captureTarget }) {
if (_initialized) this.destroy();
_send = send;
_sendPrompt = sendPrompt;
_captureTarget = captureTarget;
_composing = false;
_printableKeydownAt = null;
_flushTimer = null;
_textarea = document.getElementById('cjkInput');
_holdApplied = false; // a new field has not had the mode applied
if (!_textarea) return this;
_resetToPhantom();
@@ -288,6 +486,7 @@ const CjkInput = (() => {
// ── Composition tracking (keyboard IME — works for CJK typing) ──
_listeners.compositionstart = () => {
_t(`compstart ${_vdesc(_textarea.value)}`);
_holdTarget();
_composing = true;
_printableKeydownAt = null;
_cancelDebouncedFlush();
@@ -316,16 +515,14 @@ const CjkInput = (() => {
_t(`keydown ${_kdesc(e.key)} kc=${e.keyCode} ic=${e.isComposing} c=${_composing}`);
_printableKeydownAt = null;
if (e.key === 'Enter') {
e.preventDefault();
_composing = false;
_cancelDebouncedFlush();
const val = _strip(_textarea.value);
if (val) {
_send(val + '\r');
} else {
_send('\r');
// Send-on-Enter: Shift+Enter (or an IME still composing) is a newline
// in the field, never a send.
if (_hold && (e.shiftKey || e.isComposing || e.keyCode === 229)) {
setTimeout(_autoGrow, 0);
return;
}
_resetToPhantom();
e.preventDefault();
_submit();
return;
}
@@ -334,12 +531,17 @@ const CjkInput = (() => {
_composing = false;
_cancelDebouncedFlush();
_resetToPhantom();
if (_hold) _autoGrow();
return;
}
if (e.ctrlKey && CTRL_KEYS[e.key]) {
// Send-on-Enter with a draft in the field: Ctrl shortcuts are the
// field's (Ctrl+Z undo, Ctrl+A select all, Ctrl+C copy a selection), so
// they reach the CLI only while the field is empty, the rule Backspace
// and the arrows already follow.
if (e.ctrlKey && CTRL_KEYS[e.key] && (!_hold || _isEffectivelyEmpty())) {
e.preventDefault();
_send(CTRL_KEYS[e.key]);
_send(CTRL_KEYS[e.key], _targetForSend());
return;
}
@@ -351,7 +553,7 @@ const CjkInput = (() => {
// Backspace: forward to PTY when no real text in textarea
if (e.key === 'Backspace' && _isEffectivelyEmpty()) {
e.preventDefault();
_send('\x7f');
_send('\x7f', _targetForSend());
_resetToPhantom();
return;
}
@@ -363,14 +565,14 @@ const CjkInput = (() => {
const modNav = _modifiedNavSequence(e);
if (modNav) {
e.preventDefault();
_send(modNav);
_send(modNav, _targetForSend());
return;
}
// Arrow/function keys: forward to PTY when no real text
if (PASSTHROUGH_KEYS[e.key] && _isEffectivelyEmpty()) {
e.preventDefault();
_send(PASSTHROUGH_KEYS[e.key]);
_send(PASSTHROUGH_KEYS[e.key], _targetForSend());
return;
}
@@ -378,6 +580,7 @@ const CjkInput = (() => {
// the committed text. Let the browser/IME produce the input event so
// full-width punctuation and other layout transforms are preserved.
if (e.key.length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey && _isEffectivelyEmpty()) {
_holdTarget();
_printableKeydownAt = performance.now();
return;
}
@@ -389,6 +592,7 @@ const CjkInput = (() => {
_t(`input ${e.inputType || '?'} ic=${e.isComposing} c=${_composing} ${_vdesc(_textarea.value)}`);
const printableKeydownAt = _printableKeydownAt;
_printableKeydownAt = null;
if (!_isEffectivelyEmpty()) _holdTarget();
// ── Stuck-composition recovery ──
// Some IMEs (WeChat/Sogou keyboards) fire compositionstart without a
// matching compositionend. A stale _composing=true blocks every flush
@@ -405,12 +609,17 @@ const CjkInput = (() => {
_composing = false;
}
if (_hold) {
_holdInput(e);
return;
}
// ── Backspace / delete detection ──
if (e.inputType === 'deleteContentBackward' || e.inputType === 'deleteWordBackward') {
if (_composing) return;
if (_isEffectivelyEmpty()) {
_cancelDebouncedFlush();
_send('\x7f');
_send('\x7f', _targetForSend());
_resetToPhantom();
return;
}
@@ -459,14 +668,40 @@ const CjkInput = (() => {
return this;
},
/** Commit settled text before pane ownership changes; never send composition. */
flushNow() {
if (!_initialized || !_textarea) return;
_cancelDebouncedFlush();
clearTimeout(_compositionFlushTimer);
_compositionFlushTimer = null;
_flush();
},
/**
* Discard pending text and timers (e.g. on session switch, so stale text
* can't flush into the wrong session). Restores the phantom so backspace
* forwarding keeps working — unlike a raw `textarea.value = ''`.
*/
clear() {
clear({ discard = false } = {}) {
if (!_initialized || !_textarea) return;
_t('clear (external)');
_t(`clear (external)${discard ? ' discard' : ''}`);
if (discard) {
// The user threw the text away (the keyboard bar's clear-line key):
// nothing is stashed, any older stash of this session goes too, and the
// field keeps its owner, since the session shown has not changed.
if (_owner) _drafts.delete(_owner);
if (_hasTarget && _target) _drafts.delete(_target);
} else {
// Send-on-Enter: a held draft is stashed for the session it was typed
// for, whichever path got here. discardDraft() drops the owner of a
// removed session, so its text is not stashed again.
const sessionId = _hasTarget && _target ? _target : _owner;
if (_hold && sessionId) {
const draft = _strip(_textarea.value);
if (draft.trim()) _drafts.set(sessionId, draft);
}
_owner = null;
}
_cancelDebouncedFlush();
clearTimeout(_compositionFlushTimer);
_compositionFlushTimer = null;
@@ -475,6 +710,123 @@ const CjkInput = (() => {
_resetToPhantom();
},
/**
* Send-on-Enter mode on or off (setting cjkInputHoldUntilEnter). On: text
* stays in the field until Enter and the browser's autocorrect is allowed,
* since nothing typed has reached the PTY yet. Off: the original live mode.
*/
setHoldUntilEnter(on) {
// The placeholder first, before the early return: App Settings applies a
// language switch live and then calls this with the mode unchanged. It is
// written only when the text differs, so a field mid-composition is not
// touched. i18n.js skips <textarea> subtrees (what is typed there is user
// content), so it is translated here, like the prompt composer's.
if (_textarea) {
const source = !!on
? 'Type, Enter to send (Shift+Enter: new line, Esc: clear)'
: 'CJK input (Enter = send, Esc = clear)';
const i18n = typeof window !== 'undefined' ? window.CodemanI18n : undefined;
const placeholder = typeof i18n?.t === 'function' ? i18n.t(source) : source;
if (_textarea.placeholder !== placeholder) _textarea.placeholder = placeholder;
}
// Called on every session select and SSE reconnect: with the mode
// unchanged, leave the rest of the field alone, since rewriting its
// attributes while it has focus can disturb a composition in progress.
if (_holdApplied && _textarea && _hold === !!on) return;
const wasHolding = _hold;
_hold = !!on;
if (!_textarea) return;
_holdApplied = true;
// Turning the mode off: live mode's next flush would send everything in
// the field, a held multi-line draft included (its newline runs the first
// line in a shell), and stashed drafts would come back if the mode is
// switched on again. Drop them all.
if (wasHolding && !_hold) {
_drafts.clear();
_resetToPhantom();
}
_heldBase = _strip(_textarea.value);
const v = _hold ? 'on' : 'off';
_textarea.setAttribute('autocorrect', v);
_textarea.setAttribute('autocapitalize', _hold ? 'sentences' : 'off');
_textarea.setAttribute('spellcheck', _hold ? 'true' : 'false');
if (_hold) {
_cancelDebouncedFlush();
_autoGrow();
} else {
_textarea.style.height = '';
}
_t(`hold ${v}`);
},
get holdUntilEnter() { return _hold; },
/**
* Enter from outside the field (the phone toolbar's Enter button, which
* xterm's onData would swallow while the field is visible). Same as Enter
* in the field. Returns false when nothing was done (not initialized) or a
* held answer was refused.
*/
submit() {
if (!_initialized || !_textarea) return false;
_t(`submit (external) c=${_composing}`);
if (_composing) {
// An IME still composing (Gboard holds the current word, iOS the
// unconverted pinyin): reading and resetting the field under it can
// desync the keyboard. Blur commits the composition, focus keeps the
// keyboard up (still inside the tap's gesture), then send what landed.
_textarea.blur();
_textarea.focus();
}
return _submit();
},
/**
* Send-on-Enter: keep the held draft of the session being left, so a
* switch (a stray sideways swipe) does not lose an answer. Call before
* clear(); restoreDraft() puts it back when that session is shown again.
*/
stashDraft(sessionId) {
if (_hasTarget && _target) sessionId = _target;
if (!_initialized || !_textarea || !_hold || !sessionId) return;
// An empty field leaves any stash alone: a draft only sits in the map
// while its session is not shown (restoreDraft takes it out), and the
// tile grid may stash an id whose draft is already put away.
const draft = _strip(_textarea.value);
if (draft.trim()) _drafts.set(sessionId, draft);
},
/** Send-on-Enter: show the draft stashed for this session, if any, unless
* the field already holds text. */
restoreDraft(sessionId) {
if (!_initialized || !_textarea) return;
// The field now belongs to this session, draft or not (see _owner),
// unless it still holds another session's text (no clear() in between).
if (!_owner || !_strip(_textarea.value)) _owner = sessionId || null;
if (!_hold || !_drafts.has(sessionId)) return;
if (_strip(_textarea.value)) return;
const draft = _drafts.get(sessionId);
_drafts.delete(sessionId);
_t(`restore draft len=${draft.length}`);
_textarea.value = PHANTOM + draft;
_textarea.setSelectionRange(_textarea.value.length, _textarea.value.length);
_heldBase = draft;
// The restored text belongs to this session: Enter after a focus move to
// another pane must still send it here (see _targetForSend).
_target = sessionId;
_hasTarget = true;
_autoGrow();
},
/** Forget a stashed draft when its session no longer exists. */
discardDraft(sessionId) {
_drafts.delete(sessionId);
if (_owner === sessionId) _owner = null;
},
/** Diagnostic/test: the session the field's text belongs to. */
get draftOwner() { return _owner; },
/** Diagnostic: recent IME event trace (ring buffer). */
getTrace() {
return _trace.slice();
@@ -494,6 +846,9 @@ const CjkInput = (() => {
window.cjkActive = false;
_composing = false;
_printableKeydownAt = null;
_target = undefined;
_hasTarget = false;
_captureTarget = null;
for (const key of Object.keys(_listeners)) delete _listeners[key];
_initialized = false;
},
+197 -61
View File
@@ -27,13 +27,15 @@
*
* - FocusTrap (class) — Traps Tab/Shift+Tab keyboard focus within a modal element.
* Saves and restores previously focused element on deactivate. Used by the modal dialogs.
* A dialog opened by a mouse press goes back to the field the user was typing in when
* the press began (FocusTrap.focusToReturn), not to the pressed control.
*
* @globals {object} KeyboardAccessoryBar
* @globals {object} PathPicker
* @globals {class} FocusTrap
*
* @dependency mobile-handlers.js (MobileDetection.isTouchDevice)
* @dependency app.js (uses global `app` for sendInput, activeSessionId, terminal)
* @dependency app.js (uses global `app` for _enqueueInput, _sendInputAsync, _prepareExternalInput, activeSessionId, terminal)
* @loadorder 5 of 15 — loaded after notification-manager.js, before app.js
*/
@@ -1189,7 +1191,7 @@ const KeyboardAccessoryBar = {
/** Handle accessory button actions */
handleAction(action, btn) {
if (typeof app === 'undefined' || !app.activeSessionId) return;
if (typeof app === 'undefined') return;
// Any key other than Ctrl itself spends the modifier. It is a one-shot for
// the next TYPED character, so an accessory key tapped in between (Esc, an
@@ -1228,10 +1230,12 @@ const KeyboardAccessoryBar = {
// Tab means "complete what I just typed", but with local echo the typed
// text is still buffered in the overlay and has never reached the PTY —
// a bare \t would ask the CLI to complete an empty composer.
this.flushPendingThen(() => this.sendKey('\t'));
this.flushPendingThen('\t');
break;
case 'shift-tab':
this.sendKey('\x1b[Z');
// Cycles a mode, never edits the composer: leave the unsent draft in the
// overlay, as a typed Shift+Tab does.
this.sendKey('\x1b[Z', { keepDraft: true });
break;
case 'ctrl-o':
this.sendKey('\x0f');
@@ -1268,6 +1272,7 @@ const KeyboardAccessoryBar = {
this.pickPath();
break;
case 'clear-input':
this._prepareInput(undefined, 'accessory-clear');
app.clearTerminalInput?.();
break;
case 'dismiss':
@@ -1331,38 +1336,53 @@ const KeyboardAccessoryBar = {
this.element.classList.toggle('codex-enabled', this._isCodexSession());
},
/** Capture the destination before settling native input; background drafts
* must never reset a different pane's owner. */
_prepareInput(sessionId, reason, opts) {
const target = sessionId || (typeof app._focusedPane === 'function' ? app._focusedPane()?.sessionId : app.activeSessionId);
const pane = app._paneForSession?.(target);
if (pane) {
if (opts) app._prepareExternalInput?.(pane, reason, opts);
else app._prepareExternalInput?.(pane, reason);
}
return target;
},
/** Send a slash command to the active session.
* Sends text and Enter separately so Ink processes them as distinct events. */
* Sends text and Enter separately so Ink processes them as distinct events.
* The unsent local-echo draft stays in the overlay: flushing it would submit `draft/command`. */
sendCommand(command) {
if (!app.activeSessionId) return;
// Send command text first (without Enter)
app.sendInput(command);
// Send Enter separately after a brief delay so Ink has time to process the text.
setTimeout(() => app.sendInput('\r'), 120);
const sessionId = this._prepareInput(undefined, 'accessory-command');
if (!sessionId) return;
app._enqueueInput(sessionId, [{ write: command, useMux: true }, { gap: 120 }, { write: '\r', useMux: true }]);
},
/**
* Flush whatever the local-echo overlay is still holding, THEN run `after()`.
*
* On a phone the characters you type sit in the overlay and have never
* reached the PTY, so any key that acts on "what I just typed" has to push
* that text out first or the CLI acts on an empty composer. Mirrors the
* flush the typed path performs in terminal-ui.js's onData; the 120ms is the
* same settle delay sendCommand uses, so the text lands before the key.
* Flush local echo and reserve the following key atomically in the session
* FIFO, so switching panes during the settle gap cannot redirect the key.
*/
flushPendingThen(after) {
const overlay = app._localEchoOverlay;
flushPendingThen(sequence, reason = 'accessory-key', passthrough = false) {
const pane = app._focusedPane?.();
const sessionId = typeof app._focusedPane === 'function' ? pane?.sessionId : app.activeSessionId;
if (!sessionId) return;
if (pane) app._prepareExternalInput?.(pane, reason);
const overlay = !pane || pane.isPrimary ? app._localEchoOverlay : null;
const pending = (app._localEchoEnabled && overlay?.pendingText) || '';
if (!pending) {
after();
return;
if (passthrough) {
if (!app._echoPassthroughSessions) app._echoPassthroughSessions = new Set();
app._echoPassthroughSessions.add(sessionId);
}
overlay.clear();
overlay.suppressBufferDetection?.();
app._flushedOffsets?.delete(app.activeSessionId);
app._flushedTexts?.delete(app.activeSessionId);
app.sendInput(pending);
setTimeout(after, 120);
const ops = [];
if (pending) {
overlay.clear();
overlay.suppressBufferDetection?.();
app._flushedOffsets?.delete(sessionId);
app._flushedTexts?.delete(sessionId);
ops.push({ write: pending, useMux: true }, { gap: 120 });
}
app._predictiveEcho?.clearPredictions();
ops.push({ write: sequence });
app._enqueueInput(sessionId, ops);
},
/**
@@ -1380,38 +1400,41 @@ const KeyboardAccessoryBar = {
* broken because what came back was never what the row showed.
*/
sendNavKey(sequence) {
if (!app.activeSessionId) return;
if (!app._echoPassthroughSessions) app._echoPassthroughSessions = new Set();
app._echoPassthroughSessions.add(app.activeSessionId);
this.flushPendingThen(() => this.sendKey(sequence));
this.flushPendingThen(sequence, 'accessory-navigation', true);
},
/** Send a special key (arrow, escape, etc.) directly to the PTY.
* Bypasses tmux send-keys -l (literal mode) since escape sequences
* must be written raw to be interpreted as key presses by Ink. */
sendKey(escapeSequence) {
if (!app.activeSessionId) return;
// Arrows/Esc move the server-side cursor and bypass onData: clear
// predictions now instead of waiting out the ~150ms off-row grace.
* must be written raw to be interpreted as key presses by Ink.
* `keepDraft` leaves the unsent local-echo draft in the overlay. */
sendKey(escapeSequence, { keepDraft = false } = {}) {
const sessionId = this._prepareInput(undefined, 'accessory-key', keepDraft ? undefined : { flushEcho: true });
if (!sessionId) return;
app._predictiveEcho?.clearPredictions();
fetch(`/api/sessions/${app.activeSessionId}/input`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ input: escapeSequence })
}).catch(() => {});
app._enqueueInput(sessionId, [{ write: escapeSequence }]);
},
/** Browse the active session's workspace and insert a selected path without Enter. */
pickPath() {
if (!app.activeSessionId) return;
const session = app.sessions?.get(app.activeSessionId);
const pane = app._focusedPane?.();
const sessionId = typeof app._focusedPane === 'function' ? pane?.sessionId : app.activeSessionId;
if (!sessionId) return;
const session = app.sessions?.get(sessionId);
PathPicker.open({
title: 'Insert File or Folder Path',
sessionId: app.activeSessionId,
sessionId,
initialPath: session?.workingDir || '',
directoriesOnly: false,
onSelect: (path) => {
app.insertTerminalText?.(path);
const targetPane = app._paneForSession?.(sessionId);
if (targetPane?.isPrimary && app._localEchoPolicy === 'predict') app._predictiveEcho?.clearPredictions();
if (targetPane?.isPrimary && app._localEchoEnabled && app._localEchoOverlay && !app._echoPassthroughSessions?.has(sessionId)) {
app._prepareExternalInput?.(targetPane, 'accessory-path');
app._localEchoOverlay.appendText(path);
} else {
if (targetPane) app._prepareExternalInput?.(targetPane, 'accessory-path', { flushEcho: true });
app._sendInputAsync(sessionId, path, { useMux: true });
}
setTimeout(() => app.terminal?.focus(), 100);
},
});
@@ -1421,6 +1444,9 @@ const KeyboardAccessoryBar = {
* exists only in the overlay; flushed text already reached the PTY, so erase
* that prefix before making the textarea authoritative. */
_takePendingLocalEcho(sessionId) {
this._prepareInput(sessionId, 'accessory-compose-adopt');
const pane = app._focusedPane?.();
if (pane && (!pane.isPrimary || pane.sessionId !== sessionId)) return '';
if (!app._localEchoEnabled || !app._localEchoOverlay) return '';
const pending = app._localEchoOverlay.pendingText || '';
const overlayFlushed = app._localEchoOverlay.getFlushed?.() || {};
@@ -1458,17 +1484,15 @@ const KeyboardAccessoryBar = {
* Enter stays a separate delayed write because Codex drops keys sharing a
* PTY read with a bracketed paste. */
_sendComposedPrompt(sessionId, text) {
if (!this._sendBracketedPaste(sessionId, text, 'Prompt')) return false;
setTimeout(() => app._sendInputAsync(sessionId, '\r', { useMux: true }), 120);
return true;
return this._sendBracketedPaste(sessionId, text, 'Prompt', true);
},
/** One bracketed-paste write on the durable session-bound path, the same
* bytes a terminal paste produces, so the receiving shell or CLI takes a
* multi-line block as one edit. Never presses Enter: callers decide.
* `label` names the payload in the too-long toast. */
_sendBracketedPaste(sessionId, text, label) {
if (!sessionId || !text || typeof app._sendInputAsync !== 'function') return false;
_sendBracketedPaste(sessionId, text, label, submit = false) {
if (!sessionId || !text || typeof app._enqueueInput !== 'function') return false;
app._predictiveEcho?.clearPredictions();
// Match xterm's prepareTextForTerminal(): CR keeps embedded newlines inside
// the single-line input transport and is what terminal.paste() emitted.
@@ -1483,7 +1507,10 @@ const KeyboardAccessoryBar = {
app.showToast?.(`${label} is too long to send (maximum ${this._composerMaxLength.toLocaleString()} characters)`, 'error');
return false;
}
app._sendInputAsync(sessionId, `${COMPOSER_PASTE_START}${pasteText}${COMPOSER_PASTE_END}`);
this._prepareInput(sessionId, submit ? 'accessory-compose-send' : 'accessory-paste', { flushEcho: true });
const ops = [{ write: `${COMPOSER_PASTE_START}${pasteText}${COMPOSER_PASTE_END}` }];
if (submit) ops.push({ gap: 120 }, { write: '\r', useMux: true });
app._enqueueInput(sessionId, ops);
return true;
},
@@ -1500,13 +1527,15 @@ const KeyboardAccessoryBar = {
/** Open the manual agent prompt composer. Enter remains a newline; only the
* Send button submits. Cancel/backdrop/Escape preserve the per-session draft. */
composePrompt() {
if (typeof app === 'undefined' || !app.activeSessionId) return;
if (this._isShellSession()) {
if (typeof app === 'undefined') return;
const pane = app._focusedPane?.();
const sessionId = typeof app._focusedPane === 'function' ? pane?.sessionId : app.activeSessionId;
if (!sessionId) return;
if (app.sessions?.get(sessionId)?.mode === 'shell') {
this.pasteFromClipboard();
return;
}
const sessionId = app.activeSessionId;
const pending = this._takePendingLocalEcho(sessionId);
const saved = this._composerDrafts.get(sessionId) || '';
// A parked draft and text typed (or attached) on the prompt since are two
@@ -1614,7 +1643,7 @@ const KeyboardAccessoryBar = {
};
syncUploadUi();
try {
const paths = await app._uploadAndInsertImages(images, { insert: false });
const paths = await app._uploadAndInsertImages(images, { insert: false, sessionId });
if (paths?.length) {
const currentOverlay =
this._composerOverlay?.isConnected && this._composerOverlay.dataset.sessionId === sessionId
@@ -1687,10 +1716,13 @@ const KeyboardAccessoryBar = {
// draft would be prepended to it the next time the composer opens.
this._composerDrafts.delete(sessionId);
close({ focusTerminal: true, preserveDraft: false });
const targetPane = app._focusedPane?.();
if (targetPane?.sessionId === sessionId) app._prepareExternalInput?.(targetPane, 'accessory-compose-insert');
if (
app._localEchoEnabled &&
app._localEchoOverlay &&
app.activeSessionId === sessionId &&
(!targetPane || (targetPane.isPrimary && targetPane.sessionId === sessionId)) &&
!app._tilesOwnTerminal?.() &&
!app._echoPassthroughSessions?.has(sessionId)
) {
@@ -1737,10 +1769,11 @@ const KeyboardAccessoryBar = {
* All upload paths reuse app._uploadAndInsertImages() (image-input.js), which
* uploads to /api/sessions/:id/paste-image and inserts the saved path. */
pasteFromClipboard() {
if (typeof app === 'undefined' || !app.activeSessionId) return;
// The shell this overlay was opened for: a tab switch while it is open must
// not deliver the paste to whatever session is active at Send time.
const sessionId = app.activeSessionId;
if (typeof app === 'undefined') return;
// Capture once: switching focus while the dialog is open cannot redirect it.
const pane = app._focusedPane?.();
const sessionId = typeof app._focusedPane === 'function' ? pane?.sessionId : app.activeSessionId;
if (!sessionId) return;
// Create overlay
const overlay = document.createElement('div');
@@ -1846,6 +1879,13 @@ const KeyboardAccessoryBar = {
/**
* FocusTrap - Traps keyboard focus within an element (typically a modal).
* Saves the previously focused element and restores focus when deactivated.
*
* What it saves is {@link FocusTrap.focusToReturn}, not `document.activeElement`.
* By the time a dialog opens, the mouse press that opened it has already moved
* focus: in Chromium and Firefox the pressed control took it, and in WebKit on
* macOS (Safari, the Mac app) a button takes no focus from the mouse, so the
* press clears focus to `<body>`. Handing either one back left the keyboard out
* of the terminal the user was typing in until they clicked it again.
*/
class FocusTrap {
constructor(element) {
@@ -1854,8 +1894,96 @@ class FocusTrap {
this.boundHandleKeydown = this.handleKeydown.bind(this);
}
/**
* The element a dialog that is about to open should hand the keyboard back to
* when it closes.
*
* That is `document.activeElement`, with one exception: a dialog opened by a
* mouse press while the user was typing in a field (a terminal's textarea, the
* CJK field, a search box). The field is the answer when that press is the
* only reason focus is somewhere else now, which is the case when focus sits
* on the pressed control or on nothing at all.
*
* ⚠️ One press, and only from a typing field. A press made from a button (a
* dialog opened from inside another dialog) still returns to the pressed
* control, and the field of an earlier press is not carried over: it can be
* behind a dialog that has opened since. The one exception is a press on a
* menu item, see {@link FocusTrap._notePress}. A control reached with the
* keyboard keeps the usual pattern too, because any key forgets the press.
*
* ⚠️ Asking spends the press. Whatever is pressed inside the dialog that is
* opening starts with nothing remembered, so nothing in it can hand the
* keyboard to a field behind it.
*/
static focusToReturn() {
const active = document.activeElement || null;
const press = FocusTrap._press;
FocusTrap._press = null;
if (!press || !press.field || press.field === active || press.field.isConnected === false) return active;
const moved =
!active ||
active === document.body ||
active === press.target ||
(typeof active.contains === 'function' && active.contains(press.target));
return moved ? press.field : active;
}
/** True for an element text is typed into: a textarea, a text-like input, an editable region. */
static isTypingField(el) {
if (!el || el === document.body) return false;
const tag = String(el.tagName || '').toUpperCase();
if (tag === 'TEXTAREA') return true;
if (tag === 'INPUT') return !FocusTrap.NON_TEXT_INPUT_TYPES.includes(String(el.type || 'text').toLowerCase());
return el.isContentEditable === true;
}
/**
* Remember what a mouse press began on and which typing field had the keyboard.
*
* ⚠️ `pointerdown`, not `mousedown` or `click`: moving focus is the default
* action of `mousedown`, which comes after it, so `activeElement` is still the
* element that had the keyboard before the press.
*
* ⚠️ A finger or a pen forgets the press and records nothing: on a touch device
* a focused field means the on-screen keyboard, and handing focus back to it
* would raise the keyboard when a dialog closes.
*
* ⚠️ A press on an item of a menu (`[role="menu"]`) keeps the field of the
* press before it, the one that opened the menu: a tile's menu button and then
* "Session options" are two presses and one way into a dialog. No other press
* inherits a field.
*/
static _notePress(e) {
if (!e || e.pointerType !== 'mouse') {
FocusTrap._press = null;
return;
}
const active = document.activeElement;
const target = e.target || null;
let field = FocusTrap.isTypingField(active) ? active : null;
if (!field && FocusTrap._press && typeof target?.closest === 'function' && target.closest('[role="menu"]')) {
field = FocusTrap._press.field;
}
FocusTrap._press = { target, field };
}
/** Any key but a modifier held for the click (Shift+click) ends the press's say. */
static _forgetPress(e) {
if (e && FocusTrap.MODIFIER_KEYS.includes(e.key)) return;
FocusTrap._press = null;
}
/** Install the two document listeners behind {@link FocusTrap.focusToReturn}, once per page. */
static watchPresses() {
if (FocusTrap._watching) return;
if (typeof document === 'undefined' || typeof document.addEventListener !== 'function') return;
FocusTrap._watching = true;
document.addEventListener('pointerdown', FocusTrap._notePress, true);
document.addEventListener('keydown', FocusTrap._forgetPress, true);
}
activate() {
this.previouslyFocused = document.activeElement;
this.previouslyFocused = FocusTrap.focusToReturn();
this.element.addEventListener('keydown', this.boundHandleKeydown);
// Focus first focusable element after a brief delay (for CSS transitions)
@@ -1907,3 +2035,11 @@ class FocusTrap {
}
}
}
/** The last mouse press, `{ target, field }`, or null. See {@link FocusTrap._notePress}. */
FocusTrap._press = null;
FocusTrap._watching = false;
/** `<input>` types nobody types text into; every other type counts as a typing field. */
FocusTrap.NON_TEXT_INPUT_TYPES = ['button', 'checkbox', 'color', 'file', 'hidden', 'image', 'radio', 'range', 'reset', 'submit'];
FocusTrap.MODIFIER_KEYS = ['Shift', 'Control', 'Alt', 'Meta'];
FocusTrap.watchPresses();
+47 -13
View File
@@ -435,27 +435,55 @@ const KeyboardHandler = {
// BEHIND the keyboard with its own search box out of sight.
const caseSheet = document.querySelector('.mobile-case-picker.active .mobile-case-picker-sheet');
// A focused field that starts behind the keyboard (the pinned CJK / Send on
// Enter field) makes Android pan the visual viewport down to reveal it (measured
// on Chrome: offsetTop 285px with a 458px visual viewport in a 744px layout one).
// The app is sized to the visual viewport but laid out at the top of the layout
// viewport, so that pan left only the terminal's last line on screen. On phones,
// follow the pan while the keyboard is up, whatever has focus: without a pan
// (offsetTop 0, the usual case) nothing moves, and a focus change that keeps the
// pan cannot drop the shift. Every other branch clears it.
// ⚠️ The transform makes .app the box its position:fixed children (header,
// toolbar, accessory bar, the field) are placed against, so their keyboard lift
// below is measured from .app's bottom, not the layout viewport's, or they would
// be lifted twice on a partial pan. The case sheet (#mobileCasePickerModal) is
// inside .app too and takes the same lift.
const appEl = document.querySelector('.app');
const pan = isSmallMedium ? Math.round(window.visualViewport.offsetTop || 0) : 0;
if (appEl) appEl.style.transform = pan > 0 ? `translateY(${pan}px)` : '';
// The layout viewport's height, which position:fixed bottoms are measured from.
// ⚠️ Not window.innerHeight alone: on the first keyboard open after focusing the
// pinned field, iOS Safari reported innerHeight as the shrunk visual height (323)
// while the layout viewport stayed 640 (documentElement.clientHeight), so the lift
// came out 0 and the bars stayed behind the keyboard. Earlier a delayed
// scrollIntoView re-ran this pass once innerHeight had caught up; without it the
// stale value stuck. The larger of the two cannot be stale in that direction.
const layoutHeight = Math.max(window.innerHeight, document.documentElement?.clientHeight || 0);
const visualBottom = window.visualViewport.offsetTop + window.visualViewport.height;
const keyboardOffset = Math.max(0, layoutHeight - visualBottom);
const insideLift = pan > 0 && appEl ? Math.max(0, pan + appEl.offsetHeight - visualBottom) : keyboardOffset;
if (isSmallMedium) {
// Phones/small tablets: toolbar and accessory bar are position:fixed
// via CSS. Use translateY to lift them above the keyboard.
const toolbar = document.querySelector('.toolbar');
const main = document.querySelector('.main');
const layoutHeight = window.innerHeight;
const visualBottom = window.visualViewport.offsetTop + window.visualViewport.height;
const keyboardOffset = Math.max(0, layoutHeight - visualBottom);
if (toolbar) {
toolbar.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
toolbar.style.transform = insideLift > 0 ? `translateY(${-insideLift}px)` : '';
}
if (accessoryBar) {
accessoryBar.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
accessoryBar.style.transform = insideLift > 0 ? `translateY(${-insideLift}px)` : '';
}
if (caseSheet) {
caseSheet.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
caseSheet.style.transform = insideLift > 0 ? `translateY(${-insideLift}px)` : '';
}
if (main && keyboardHeight > 0) {
const cjkInputHeight = cjkInput?.classList.contains('cjk-input-visible') ? 44 : 0;
// The field grows with its text in Send-on-Enter mode, so reserve its
// real height (44 = the one-line field plus its border, the old constant).
const cjkInputHeight = cjkInput?.classList.contains('cjk-input-visible')
? Math.max(44, cjkInput.offsetHeight + 10)
: 0;
main.style.paddingBottom = `${84 + cjkInputHeight}px`;
}
} else if (keyboardHeight > 0) {
@@ -472,11 +500,8 @@ const KeyboardHandler = {
// CJK textarea positioning (always position:fixed on touch devices).
if (cjkInput?.classList.contains('cjk-input-visible') && keyboardHeight > 0) {
if (isSmallMedium) {
// Phones: use translateY like toolbar/accessory bar.
const layoutHeight = window.innerHeight;
const visualBottom = window.visualViewport.offsetTop + window.visualViewport.height;
const keyboardOffset = Math.max(0, layoutHeight - visualBottom);
cjkInput.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
// Phones: use translateY like toolbar/accessory bar (it sits inside .app too).
cjkInput.style.transform = insideLift > 0 ? `translateY(${-insideLift}px)` : '';
cjkInput.style.bottom = '';
} else {
// iPad: direct bottom = keyboard + accessory bar height.
@@ -499,7 +524,11 @@ const KeyboardHandler = {
// keyboard was still up must still have its inline offset cleared, or the
// next open slides in already displaced.
const caseSheet = document.querySelector('.mobile-case-picker-sheet');
const appEl = document.querySelector('.app');
if (appEl) {
appEl.style.transform = '';
}
if (toolbar) {
toolbar.style.transform = '';
}
@@ -729,6 +758,11 @@ const KeyboardHandler = {
if (el.closest('.xterm') || el.closest('.terminal-container')) {
return false;
}
// The pinned CJK / Send on Enter field is position:fixed and lifted above the
// keyboard by updateLayoutForKeyboard(). Scrolling it into view centred it in its
// scrollable ancestors instead, which pushed the terminal off screen whenever the
// field took focus.
if (el.id === 'cjkInput') return false;
const tagName = el.tagName?.toLowerCase();
// Exclude type=range, type=checkbox, type=radio (don't trigger keyboard)
+28 -3
View File
@@ -42,7 +42,9 @@
const KEEP_COMPOSING_KEYCODES = new Set([20, 229, 16, 17, 18]);
const CONTROL_OR_LINE_BREAK = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;
function isIosWebKitTouch(nav = navigator) {
// Shared with CodemanIosNativeInput.isSupported(); keep platform gating here
// because the preview predates and loads before the native input owner.
function isIosWebKitTouch(nav = global.navigator) {
const userAgent = String(nav && nav.userAgent ? nav.userAgent : '');
const platform = String(nav && nav.platform ? nav.platform : '');
const touchPoints = Number(nav && nav.maxTouchPoints ? nav.maxTouchPoints : 0);
@@ -59,6 +61,12 @@
const render = typeof options.render === 'function' ? options.render : function () {};
const clear = typeof options.clear === 'function' ? options.clear : function () {};
const onCommit = typeof options.onCommit === 'function' ? options.onCommit : function () {};
const ownsNativeInput =
typeof options.ownsNativeInput === 'function'
? options.ownsNativeInput
: function () {
return false;
};
const scheduleFrame = options.scheduleFrame || global.requestAnimationFrame.bind(global);
const cancelFrame = options.cancelFrame || global.cancelAnimationFrame.bind(global);
const setTimer = options.setTimer || global.setTimeout.bind(global);
@@ -73,6 +81,7 @@
let frameToken = null;
let timerToken = null;
let finalizedByKeydown = false;
let compositionStart = 0;
let destroyed = false;
let invokingClear = false;
@@ -140,17 +149,19 @@
cleanup();
if (destroyed) return;
composing = true;
compositionStart = textarea.selectionStart == null ? textarea.value.length : textarea.selectionStart;
}
function updateComposition(event) {
if (!composing) return;
latestValue = event.data == null ? '' : String(event.data);
const segment = safely(ownsNativeInput) ? textarea.value.slice(compositionStart, textarea.selectionEnd) : '';
latestValue = event.data == null ? segment : String(event.data);
scheduleLatestPreview('provisional');
}
function onComposingInput(event) {
if (!event.isComposing) return;
updateComposition({ data: event.data == null ? textarea.value : event.data });
updateComposition({ data: event.data == null && !safely(ownsNativeInput) ? textarea.value : event.data });
}
function armFallbackTimer(isCurrent) {
@@ -203,6 +214,9 @@
// finalizes it. `isComposing` and `key` are deliberately not consulted,
// because xterm does not consult them.
function onKeydown(event) {
// Native ownership, not xterm's terminal-key heuristic, decides when the
// retained field has finished composing.
if (safely(ownsNativeInput)) return;
if (keydownTarget !== textarea && event.target !== textarea) return;
if (!composing || KEEP_COMPOSING_KEYCODES.has(event.keyCode)) return;
finalizeComposition(latestValue, true);
@@ -246,6 +260,16 @@
return true;
}
function nativeTransaction({ inserted, deleted, composition }) {
if (destroyed || !awaitingCommit) return false;
if (inserted && consumeTerminalData(inserted)) return true;
// No inserted text (or unsafe terminal controls): nothing can display a
// commit later. In particular deletion-only/unchanged compositions settle
// now instead of leaving unrelated input to consume the 2 s fallback.
cleanup();
return false;
}
function completeCommit(result) {
if (destroyed || !result || result.predicted !== true || !committed) return;
cleanup();
@@ -275,6 +299,7 @@
return {
consumeTerminalData,
nativeTransaction,
completeCommit,
noteAuthoritativeOutput,
reset,
+21 -6
View File
@@ -1039,15 +1039,30 @@ html.mobile-init .file-browser-panel {
bottom: calc(var(--safe-area-bottom) + var(--chrome-overlap, 0px));
}
/* When keyboard is visible the JS translateY already accounts for the full
distance from the visual-viewport bottom to the layout-viewport bottom
(keyboard + Safari bar). Remove the CSS Safari-bar offset to avoid
double-counting, which otherwise creates a visible gap above the keyboard. */
/* With the keyboard up the bars sit directly on it. The JS translateY already
lifts them by the whole distance from the layout-viewport bottom to the
visual-viewport bottom (keyboard, plus Safari's bar where there is one), so
the Safari-bar offset is not added again here. Nor is the bottom safe area:
the keyboard covers the home-indicator strip it reserves. Keeping it (34px
on a Face ID iPhone, since the page sets viewport-fit=cover) left an empty
band between the toolbar and the keyboard, and worse, pushed the bars 34px
above the box main's keyboard padding reserves for them (84px, the two
bars only, set by KeyboardHandler), so the terminal's last row, the end of
the prompt being typed, was painted under the accessory bar. The second
selector of each pair outranks `.ios-device.safari-browser .toolbar`. */
.keyboard-visible .toolbar,
.keyboard-visible.ios-device.safari-browser .toolbar {
bottom: var(--safe-area-bottom);
bottom: 0;
}
.keyboard-visible .keyboard-accessory-bar,
.keyboard-visible.ios-device.safari-browser .keyboard-accessory-bar {
bottom: calc(var(--safe-area-bottom) + 40px);
bottom: 40px;
}
/* The CJK textarea stacks on the accessory bar, so it drops the same strip
(styles.css adds --safe-area-bottom for every touch device; on an iPad the
JS sets `bottom` inline and this rule never applies, being phone-only). */
.touch-device.keyboard-visible #cjkInput.cjk-input-visible {
bottom: 84px;
}
/* Show case selector in center */
+276 -15
View File
@@ -376,7 +376,14 @@ Object.assign(CodemanApp.prototype, {
* for, typing a filter the moment it opens.
*/
_rememberOverlayFocus(key) {
this[key] = (typeof document !== 'undefined' && document.activeElement) || null;
if (typeof document === 'undefined') {
this[key] = null;
return;
}
// The same answer a FocusTrap dialog saves (keyboard-accessory.js): an overlay
// opened by a mouse press goes back to the field the user was typing in, not
// to the pressed button.
this[key] = (typeof FocusTrap === 'function' ? FocusTrap.focusToReturn() : document.activeElement) || null;
},
/**
@@ -2719,6 +2726,7 @@ Object.assign(CodemanApp.prototype, {
searchEpoch: 0,
ownerSessionId,
view: 'normal',
workspaceSearch: false,
normalState: this.fileBrowserData
? { sessionId: ownerSessionId, showHidden, treeEpoch: 0, phase: 'ready', data: this.fileBrowserData }
: null,
@@ -2753,6 +2761,7 @@ Object.assign(CodemanApp.prototype, {
state.deferredDirectoryTarget = null;
state.filter = '';
state.view = 'normal';
state.workspaceSearch = false;
state.sessionRootPinned = false;
state.pinnedWorktree = null;
this.fileBrowserData = null;
@@ -2798,6 +2807,7 @@ Object.assign(CodemanApp.prototype, {
state.deferredDirectoryTarget = null;
state.filter = '';
state.view = 'normal';
state.workspaceSearch = false;
state.sessionRootPinned = false;
state.pinnedWorktree = null;
this.fileBrowserData = null;
@@ -2837,8 +2847,22 @@ Object.assign(CodemanApp.prototype, {
_renderFileBrowserNormalStatus(data, showHidden) {
const statusEl = this.$('fileBrowserStatus');
if (!statusEl || !data) return;
const { totalFiles, totalDirectories, truncated } = data;
statusEl.textContent = `${totalFiles} files, ${totalDirectories} dirs${truncated ? ' (truncated)' : ''}${showHidden ? ' · hidden shown' : ''}`;
if (this._ensureFileBrowserState().filter.trim()) {
const localCount = this._fileBrowserLocalMatchCount || 0;
statusEl.textContent = `${localCount} ${localCount === 1 ? 'match' : 'matches'} in loaded folders · Enter to search workspace`;
return;
}
let { totalFiles, totalDirectories, truncated } = data;
if (data.lazy === true) {
totalFiles = 0;
totalDirectories = 0;
const count = nodes => nodes.forEach(node => {
if (node.type === 'directory') { totalDirectories++; count(node.children || []); }
else totalFiles++;
});
count(data.tree);
}
statusEl.textContent = `${totalFiles} files, ${totalDirectories} dirs${data.lazy ? ' · loaded folders' : truncated ? ' (truncated)' : ''}${showHidden ? ' · hidden shown' : ''}`;
},
_isFileBrowserNormalCompatible(candidate, sessionId, showHidden, treeEpoch) {
@@ -3084,6 +3108,7 @@ Object.assign(CodemanApp.prototype, {
const state = this._ensureFileBrowserState();
const rawInput = typeof state.filter === 'string' ? state.filter : '';
const query = rawInput.trim();
const workspaceSearch = state.workspaceSearch === true;
if (state.inFlight?.timer !== undefined && state.inFlight?.timer !== null) {
clearTimeout(state.inFlight.timer);
@@ -3112,7 +3137,8 @@ Object.assign(CodemanApp.prototype, {
if (!query || query.length > 256) return;
const continuation = { ownerSessionId, showHidden, treeEpoch, searchEpoch, rawInput, query };
if (this._canContinueFileBrowserHiddenReload(continuation, state.normalState)) {
this.filterFileBrowser(rawInput);
if (workspaceSearch) this.searchFileBrowser(rawInput);
else this.filterFileBrowser(rawInput);
}
},
@@ -3157,7 +3183,7 @@ Object.assign(CodemanApp.prototype, {
const request = (async () => {
try {
const res = await fetch(
`/api/sessions/${encodeURIComponent(sessionId)}/files?depth=5&showHidden=${showHidden}${this._fileBrowserRootParam()}`,
`/api/sessions/${encodeURIComponent(sessionId)}/files?lazy=1&showHidden=${showHidden}${this._fileBrowserRootParam()}`,
);
if (!res.ok) throw new Error('Failed to load files');
const result = await res.json();
@@ -3175,6 +3201,9 @@ Object.assign(CodemanApp.prototype, {
this.fileBrowserData = data;
const deferredRendered = this._completeDeferredFileBrowserDirectory?.(nextNormalState) === true;
if (!deferredRendered) this._renderFileBrowserNormalState(nextNormalState);
if (data.lazy === true && !deferredRendered) {
await this._restoreFileBrowserExpandedDirs(nextNormalState);
}
} catch (error) {
if (!this._isFileBrowserTreeContextCurrent(record, true)) return;
const nextNormalState = {
@@ -3198,6 +3227,177 @@ Object.assign(CodemanApp.prototype, {
return record.promise;
},
_isFileBrowserDirectoryRequestCurrent(request) {
return this._isFileBrowserTreeContextCurrent(request) &&
this.activeSessionId === request.sessionId &&
this._ensureFileBrowserState().normalState?.data === request.data &&
this._fileBrowserRootParam() === request.rootParam &&
this.$('fileBrowserPanel')?.classList.contains('visible') === true;
},
// A page belongs to one tree epoch. Refresh, visibility, root and owner changes can never
// append an old response to a replacement tree, even if the same folder is expanded again.
_loadFileBrowserDirectory(path, { more = false } = {}) {
const state = this._ensureFileBrowserState();
const normal = state.normalState;
const data = normal?.data;
if (normal?.phase !== 'ready' || data?.lazy !== true) return Promise.resolve();
const container = path ? this._findFileBrowserDirectory(data.tree, path)?.target : data;
if (!container) return Promise.resolve();
const listing = container._listing ||= { nextCursor: container.nextCursor || null };
if (listing.promise) return listing.promise;
if (more ? !listing.nextCursor : path && Array.isArray(container.children)) return Promise.resolve();
const cursor = more ? listing.nextCursor : null;
const request = {
sessionId: normal.sessionId, showHidden: normal.showHidden, treeEpoch: normal.treeEpoch,
data, rootParam: this._fileBrowserRootParam(),
};
if (!this._isFileBrowserDirectoryRequestCurrent(request)) return Promise.resolve();
listing.loading = true;
listing.error = null;
listing.failedMore = more;
const work = (async () => {
try {
const res = await fetch(`/api/sessions/${encodeURIComponent(request.sessionId)}/files?lazy=1&showHidden=${request.showHidden}${request.rootParam}${path ? `&path=${encodeURIComponent(path)}` : ''}${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`);
const result = await res.json();
const page = this._validateFileBrowserTreeEnvelope(result);
if (!res.ok || !page || page.lazy !== true) throw new Error(result?.error || 'Folder unavailable');
if (page.root !== data.root) throw new Error('Workspace changed; refresh files');
if (!this._isFileBrowserDirectoryRequestCurrent(request)) return;
const key = path ? 'children' : 'tree';
const previous = more ? container[key] || [] : [];
const known = new Set(previous.map(node => node.path));
container[key] = [...previous, ...page.tree.filter(node => !known.has(node.path))];
listing.nextCursor = page.nextCursor || null;
if (!path) {
data.nextCursor = listing.nextCursor;
data.truncated = Boolean(listing.nextCursor);
}
} catch (error) {
if (this._isFileBrowserDirectoryRequestCurrent(request)) {
listing.error = this._normalizeFileBrowserTreeError(error);
}
} finally {
listing.loading = false;
listing.promise = null;
if (this._isFileBrowserDirectoryRequestCurrent(request)) this._renderFileBrowserNormalState(normal);
}
})();
listing.promise = work;
this._renderFileBrowserNormalState(normal);
return work;
},
// Follow only the ancestor chain of the named folder. Continuation is explicit for ordinary
// browsing; revealing a search hit/restoring an expansion reads the pages needed to reach it.
async _revealFileBrowserDirectory(target, normal, current, expandedOnly = false) {
const data = normal.data;
let container = data;
const paths = [];
while (current()) {
const nodes = container === data ? container.tree : container.children || [];
let found = nodes.find(node => node.type === 'directory' &&
(node.path === target || target.startsWith(node.path + '/') || target.startsWith(node.path + '\\')));
if (!found) {
// Automatic restoration must not bypass a failed page's explicit Retry action.
if (expandedOnly && container._listing?.error) return null;
const cursor = container._listing?.nextCursor ?? container.nextCursor;
// The server lists a folder's directories before its files, across every page. So once
// a loaded page holds a file, no later page can hold the folder that is looked for.
if (!cursor || nodes.some(node => node.type === 'file')) {
// A restore that cannot find its folder holds an expansion for a folder that is gone
// (deleted or renamed). Forget it, or every Refresh looks for it again.
if (expandedOnly) this.fileBrowserExpandedDirs.delete(target);
return null;
}
await this._loadFileBrowserDirectory(container === data ? '' : container.path, { more: true });
if (!current() || container._listing?.error) return null;
continue;
}
if (expandedOnly && !this.fileBrowserExpandedDirs.has(found.path)) return null;
if (expandedOnly && found._listing?.error) return null;
paths.push(found.path);
await this._loadFileBrowserDirectory(found.path);
if (!current() || found._listing?.error) return null;
if (found.path === target) return paths;
container = found;
}
return null;
},
async _restoreFileBrowserExpandedDirs(normal) {
if (normal?.data?.lazy !== true) return;
const request = { ...normal, rootParam: this._fileBrowserRootParam() };
const current = () => this._isFileBrowserDirectoryRequestCurrent(request);
// Root rows are immediate children, so their common path prefix is the listing root in
// returned-path terms. Dot segments in an inside worktree's prefix do not make its entries
// hidden. Skip inapplicable expansions before searching any continuation pages for them.
const first = normal.data.tree[0];
const rootPrefix = first?.name ? first.path.slice(0, -first.name.length) : null;
const separator = normal.data.root?.startsWith('/') ? '/' : '\\';
for (const path of [...this.fileBrowserExpandedDirs]) {
if (!current()) return;
if (rootPrefix === null || !path.startsWith(rootPrefix)) continue;
if (!normal.showHidden && path.slice(rootPrefix.length).split(separator).some(part => part.startsWith('.'))) continue;
await this._revealFileBrowserDirectory(path, normal, current, true);
}
},
_restoreFileBrowserAfterLoad(path, normal) {
if (normal?.data?.lazy !== true || this._ensureFileBrowserState().normalState !== normal) return;
const container = path ? this._findFileBrowserDirectory(normal.data.tree, path)?.target : normal.data;
if (container && !container._listing?.error && (!path || Array.isArray(container.children))) {
return this._restoreFileBrowserExpandedDirs(normal);
}
},
_fileBrowserListingControls(container, path, depth) {
const listing = container._listing;
const cursor = listing?.nextCursor ?? container.nextCursor;
let content = '';
if (listing?.loading) content = escapeHtml('Loading folder...');
else if (listing?.error) {
// Separate elements: the translator replaces a text node only when its WHOLE text is an
// entry, so the error and the label joined into one node were never translated.
content = `<span>${escapeHtml(listing.error)}</span> · <span>${escapeHtml('Incomplete folder')}</span> <button type="button" data-file-browser-load="${listing.failedMore ? 'more' : 'retry'}" data-path="${escapeHtml(path)}">${escapeHtml('Retry loading')}</button>`;
} else if (path && !Array.isArray(container.children)) {
// Drawn open before its own request started (it waits its turn in the restore after a
// Refresh): an unfinished load is never shown as an empty folder.
content = escapeHtml('Loading folder...');
} else if (cursor) {
content = `<button type="button" data-file-browser-load="more" data-path="${escapeHtml(path)}">${escapeHtml('Load more')}</button>`;
} else if (path && Array.isArray(container.children) && !container.children.length) {
content = escapeHtml('No files in this folder');
}
return content ? `<div class="file-tree-incomplete file-tree-listing-state" data-depth="${depth}"${this._fileBrowserDepthStyle(depth)}>${content}</div>` : '';
},
// Legacy CSS covers depths 0–9; lazy browsing can reach deeper folders.
_fileBrowserDepthStyle(depth) {
return depth > 9 ? ` style="padding-inline-start: ${0.5 + depth * 0.75}rem"` : '';
},
// Ordered, case-insensitive substring pieces; no user-supplied regular expression.
_filterFileBrowserLoadedTree(nodes, query) {
const pieces = query.toLowerCase().split('*').filter(Boolean);
let count = 0;
const filter = entries => entries.flatMap(node => {
const text = (query.includes('/') ? node.path : node.name).toLowerCase();
let offset = 0;
const matches = pieces.every(piece => {
const next = text.indexOf(piece, offset);
if (next < 0) return false;
offset = next + piece.length;
return true;
});
if (matches) count++;
const children = filter(node.children || []);
return matches || children.length ? [{ ...node, ...(node.children && { children }) }] : [];
});
const tree = filter(nodes);
return { tree, count };
},
renderFileBrowserTree(ownerSessionId) {
const treeEl = this.$('fileBrowserTree');
if (!treeEl || !this.fileBrowserData) return;
@@ -3206,9 +3406,12 @@ Object.assign(CodemanApp.prototype, {
const owner = ownerSessionId || state.normalState?.sessionId || state.ownerSessionId || this.activeSessionId;
if (!owner) return;
const { tree } = this.fileBrowserData;
const query = state.view === 'normal' ? state.filter.trim() : '';
const filtered = query ? this._filterFileBrowserLoadedTree(this.fileBrowserData.tree, query) : null;
const tree = filtered ? filtered.tree : this.fileBrowserData.tree;
this._fileBrowserLocalMatchCount = filtered?.count || 0;
if (!tree || tree.length === 0) {
treeEl.innerHTML = '<div class="file-browser-empty">No files found</div>';
treeEl.innerHTML = `<div class="file-browser-empty">${escapeHtml(query ? 'No matches in loaded folders · Enter to search workspace' : 'No files found')}</div>`;
return;
}
@@ -3217,7 +3420,7 @@ Object.assign(CodemanApp.prototype, {
const renderNode = (node, depth) => {
const isDir = node.type === 'directory';
const isExpanded = this.fileBrowserExpandedDirs.has(node.path);
const isExpanded = query ? !!node.children?.length : this.fileBrowserExpandedDirs.has(node.path);
const icon = isDir
? (isExpanded ? '\uD83D\uDCC2' : '\uD83D\uDCC1')
@@ -3245,7 +3448,7 @@ Object.assign(CodemanApp.prototype, {
: '';
html.push(`
<div class="file-tree-item" data-path="${escapeHtml(node.path)}" data-type="${escapeHtml(node.type)}" data-depth="${depth}">
<div class="file-tree-item" data-path="${escapeHtml(node.path)}" data-type="${escapeHtml(node.type)}" data-depth="${depth}"${this._fileBrowserDepthStyle(depth)}>
${expandIcon}
<span class="file-tree-icon">${icon}</span>
<span class="${nameClass}">${escapeHtml(node.name)}</span>
@@ -3264,7 +3467,9 @@ Object.assign(CodemanApp.prototype, {
// The scan stopped at a limit or the folder did not answer, so what is listed above is not all
// of it. Not a .file-tree-item: the click wiring below would try to open it as a file.
if (isDir && isExpanded && node.incomplete === true) {
if (isDir && isExpanded && this.fileBrowserData.lazy === true && !query) {
html.push(this._fileBrowserListingControls(node, node.path, depth + 1));
} else if (isDir && isExpanded && node.incomplete === true) {
html.push(`<div class="file-tree-incomplete" data-depth="${depth + 1}">${escapeHtml('Not fully scanned')}</div>`);
}
};
@@ -3272,9 +3477,18 @@ Object.assign(CodemanApp.prototype, {
for (const node of tree) {
renderNode(node, 0);
}
if (this.fileBrowserData.lazy === true && !query) html.push(this._fileBrowserListingControls(this.fileBrowserData, '', 0));
treeEl.innerHTML = html.join('');
treeEl.querySelectorAll('[data-file-browser-load]').forEach(button => {
button.addEventListener('click', () => {
const normal = this._ensureFileBrowserState().normalState;
this._loadFileBrowserDirectory(button.dataset.path, { more: button.dataset.fileBrowserLoad === 'more' })
.then(() => this._restoreFileBrowserAfterLoad(button.dataset.path, normal));
});
});
// Add click handlers
treeEl.querySelectorAll('.file-tree-item').forEach(item => {
item.addEventListener('click', () => {
@@ -3307,14 +3521,40 @@ Object.assign(CodemanApp.prototype, {
this.fileBrowserExpandedDirs.delete(path);
} else {
this.fileBrowserExpandedDirs.add(path);
const normal = this._ensureFileBrowserState().normalState;
this._loadFileBrowserDirectory(path).then(() => this._restoreFileBrowserAfterLoad(path, normal));
}
this.renderFileBrowserTree();
},
filterFileBrowser(value) {
const state = this._ensureFileBrowserState();
if (state.inFlight?.timer != null) clearTimeout(state.inFlight.timer);
state.searchEpoch++;
state.inFlight = null;
state.matches = [];
state.deferredDirectoryTarget = null;
state.filter = this.fileBrowserFilter = String(value ?? '');
state.view = 'normal';
state.workspaceSearch = false;
this._syncFileBrowserExpandBtn();
if (state.filter.trim().length > 256) {
const message = 'Search queries are limited to 256 characters';
state.view = 'query-error';
const treeEl = this.$('fileBrowserTree');
if (treeEl) treeEl.innerHTML = `<div class="file-browser-empty">${escapeHtml(message)}</div>`;
const statusEl = this.$('fileBrowserStatus');
if (statusEl) statusEl.textContent = message;
return;
}
this._renderFileBrowserNormalState(state.normalState);
},
searchFileBrowser(value = this.fileBrowserFilter) {
const state = this._ensureFileBrowserState();
const rawInput = String(value ?? '');
const query = rawInput.trim();
state.workspaceSearch = query.length > 0 && query.length <= 256;
state.searchEpoch++;
state.filter = rawInput;
state.deferredDirectoryTarget = null;
@@ -3424,7 +3664,7 @@ Object.assign(CodemanApp.prototype, {
view: state.view,
};
if (matches.length === 0) {
treeEl.innerHTML = `<div class="file-browser-empty">${escapeHtml('No matches')}</div>`;
treeEl.innerHTML = `<div class="file-browser-empty">${escapeHtml(data.truncated ? 'Search incomplete; no matches in scanned files' : 'No matches')}</div>`;
} else {
const ownerPath = encodeURIComponent(ownerSessionId);
const canDelete = this._fileBrowserCanDelete(ownerSessionId);
@@ -3571,6 +3811,10 @@ Object.assign(CodemanApp.prototype, {
return;
}
if (normalState.data.lazy === true) {
return this._revealFileBrowserSearchDirectory(target, normalState);
}
const found = this._findFileBrowserDirectory(normalState.data?.tree, target.path);
if (!found) {
this._promptFileBrowserDirectoryReload();
@@ -3605,6 +3849,11 @@ Object.assign(CodemanApp.prototype, {
return false;
}
if (normalState.data.lazy === true) {
this._revealFileBrowserSearchDirectory(target, normalState);
return true;
}
const found = this._findFileBrowserDirectory(normalState.data?.tree, target.path);
if (!found) {
this._promptFileBrowserDirectoryReload();
@@ -3614,6 +3863,18 @@ Object.assign(CodemanApp.prototype, {
return true;
},
async _revealFileBrowserSearchDirectory(target, normalState) {
const current = () => this._isFileBrowserDirectoryContextCurrent(target) &&
this._ensureFileBrowserState().normalState === normalState;
const paths = await this._revealFileBrowserDirectory(target.path, normalState, current);
if (!current()) return;
if (!paths) { this._promptFileBrowserDirectoryReload(); return; }
this._leaveFileBrowserSearchForDirectory(paths, normalState);
// The tree is drawn again with every folder that was expanded before. A reveal that was
// waiting for the tree to load ran in place of the restore, so load those folders now.
await this._restoreFileBrowserExpandedDirs(normalState);
},
_leaveFileBrowserSearchForDirectory(paths, normalState) {
const state = this._ensureFileBrowserState();
if (state.inFlight?.timer !== undefined && state.inFlight?.timer !== null) {
@@ -3626,6 +3887,7 @@ Object.assign(CodemanApp.prototype, {
state.deferredDirectoryTarget = null;
state.view = 'normal';
this.fileBrowserFilter = '';
state.workspaceSearch = false;
const input = this.$?.('fileBrowserSearch');
if (input) input.value = '';
@@ -3639,7 +3901,7 @@ Object.assign(CodemanApp.prototype, {
expandAllDirectories(nodes) {
for (const node of nodes) {
if (node.type === 'directory') {
if (node.type === 'directory' && Array.isArray(node.children)) {
this.fileBrowserExpandedDirs.add(node.path);
if (node.children) {
this.expandAllDirectories(node.children);
@@ -3681,11 +3943,10 @@ Object.assign(CodemanApp.prototype, {
state.matches = [];
state.deferredDirectoryTarget = null;
state.view = 'normal';
state.workspaceSearch = false;
this.fileBrowserFilter = '';
this.fileBrowserExpandedDirs.clear();
this.fileBrowserAllExpanded = false;
const expandBtn = this.$('fileBrowserExpandBtn');
if (expandBtn) expandBtn.innerHTML = '\u229E';
if (expandBtn) expandBtn.innerHTML = this.fileBrowserAllExpanded ? '\u229F' : '\u229E';
const searchInput = this.$('fileBrowserSearch');
if (searchInput) searchInput.value = '';
this._syncFileBrowserExpandBtn();
+10 -17
View File
@@ -2070,26 +2070,19 @@ Object.assign(CodemanApp.prototype, {
}
},
/** Send Enter to the active session (phone toolbar button).
*
* MUST go through xterm's onData path, NOT straight to sendInput()/the API.
* With local echo on (the mobile default) the characters you typed are still
* buffered in the LocalEchoOverlay and have NEVER reached the PTY. The onData
* Enter branch (terminal-ui.js) is what flushes that pending text and only
* then sends \r. Send a bare \r instead and you submit an empty line while the
* typed text stays stranded on screen — which reads as "the button does
* nothing". triggerDataEvent replays it exactly as if the key were pressed,
* so overlay flush, flushed-offset cleanup and ordering are all reused. */
/** Submit the focused pane through the shared native-input/echo boundary. */
sendEnterKey() {
if (!this.activeSessionId) return;
const coreService = this.terminal?._core?.coreService;
if (coreService && typeof coreService.triggerDataEvent === 'function') {
coreService.triggerDataEvent('\r', true);
// While the CJK field is visible, onData drops everything (cjkActive), this
// Enter included. Press Enter in the field instead: it sends what the field
// holds (a Send on Enter answer, or live text not yet flushed), then Enter.
if (
typeof CjkInput !== 'undefined' &&
document.getElementById('cjkInput')?.classList.contains('cjk-input-visible')
) {
CjkInput.submit?.();
return;
}
// Fallback only if xterm's private core API moves: correct when local echo
// is off, and still better than doing nothing.
this.sendInput('\r');
this.submitFromToolbar();
},
_initRunMode() {
+13 -1
View File
@@ -648,7 +648,11 @@ Object.assign(CodemanApp.prototype, {
);
document.getElementById('appSettingsTerminalWheelLocal').checked =
settings.terminalWheelLocalScrollback ?? defaults.terminalWheelLocalScrollback ?? false;
document.getElementById('appSettingsHistoryReloadAction').checked =
settings.historyReloadAction ?? defaults.historyReloadAction ?? true;
document.getElementById('appSettingsCjkInput').checked = settings.cjkInputEnabled ?? defaults.cjkInputEnabled ?? false;
document.getElementById('appSettingsCjkHoldUntilEnter').checked =
settings.cjkInputHoldUntilEnter ?? defaults.cjkInputHoldUntilEnter ?? false;
document.getElementById('appSettingsExtendedKeyboardBar').checked = settings.extendedKeyboardBar ?? false;
document.getElementById('appSettingsTabTwoRows').checked = settings.tabTwoRows ?? defaults.tabTwoRows ?? false;
document.getElementById('appSettingsShowTabCliLogos').checked = this.tabCliLogosEnabled(settings);
@@ -3194,7 +3198,9 @@ Object.assign(CodemanApp.prototype, {
document.getElementById('appSettingsTerminalFontWeightBold')
),
terminalWheelLocalScrollback: document.getElementById('appSettingsTerminalWheelLocal').checked,
historyReloadAction: document.getElementById('appSettingsHistoryReloadAction').checked,
cjkInputEnabled: document.getElementById('appSettingsCjkInput').checked,
cjkInputHoldUntilEnter: document.getElementById('appSettingsCjkHoldUntilEnter').checked,
webglRendererEnabled: document.getElementById('appSettingsWebglRenderer').checked,
extendedKeyboardBar: document.getElementById('appSettingsExtendedKeyboardBar').checked,
tabTwoRows: document.getElementById('appSettingsTabTwoRows').checked,
@@ -3282,6 +3288,7 @@ Object.assign(CodemanApp.prototype, {
this._updateLocalEchoState();
// Turning Keep Size Under Keyboard off while it holds releases it now.
this._reconcileKeyboardHold?.();
this._syncHistoryReloadAction?.();
this.applyTerminalFontFamily?.(settings.terminalFontFamily);
this.applyTerminalFontWeights?.(settings);
@@ -3440,6 +3447,7 @@ Object.assign(CodemanApp.prototype, {
// SettingsUpdateSchema (.strict()), so sending it would 400 the whole PUT.
keyboardHoldsRows: _khr,
cjkInputEnabled: _cjk,
cjkInputHoldUntilEnter: _cjkHold,
extendedKeyboardBar: _ekb,
skin: _skin,
language: _language,
@@ -3455,6 +3463,7 @@ Object.assign(CodemanApp.prototype, {
showTileGridButton: _stg,
webglRendererEnabled: _wgl,
terminalWheelLocalScrollback: _twls,
historyReloadAction: _hra,
// Copy-on-select. Per-device (clipboard access differs by device and by
// origin: the plain-HTTP LAN install has no navigator.clipboard at all)
// and absent from SettingsUpdateSchema (.strict()), so sending it would
@@ -4478,7 +4487,9 @@ Object.assign(CodemanApp.prototype, {
sessionListLayout: 'header',
sessionSidebarFontSize: 12,
cjkInputEnabled: false,
cjkInputHoldUntilEnter: false,
terminalWheelLocalScrollback: false, // mobile scrolls via touch, not wheel
historyReloadAction: true,
webglRendererEnabled: false, // mobile always uses the DOM renderer
skin: 'daylight-blue',
};
@@ -5206,11 +5217,12 @@ Object.assign(CodemanApp.prototype, {
'showFontControls', 'showSystemStats', 'showGpuStats', 'showCpuMhz', 'headerStatsStyle', 'showTokenCount', 'showCost',
'showLifecycleLog', 'showResponseViewer', 'showRedrawButton',
'showMonitor', 'showProjectInsights', 'showFileBrowser', 'showSubagents',
'subagentActiveTabOnly', 'tabTwoRows', 'showTabCliLogos', 'tabOrientation', 'tabRailWidth', 'tabRailDetail', 'tabRailSort', 'tabArrangement', 'tabStateOrder', 'sessionListLayout', 'sessionSidebarFontSize', 'localEchoEnabled', 'keyboardHoldsRows', 'cjkInputEnabled', 'extendedKeyboardBar',
'subagentActiveTabOnly', 'tabTwoRows', 'showTabCliLogos', 'tabOrientation', 'tabRailWidth', 'tabRailDetail', 'tabRailSort', 'tabArrangement', 'tabStateOrder', 'sessionListLayout', 'sessionSidebarFontSize', 'localEchoEnabled', 'keyboardHoldsRows', 'cjkInputEnabled', 'cjkInputHoldUntilEnter', 'extendedKeyboardBar',
'skin', 'showPlanUsageLimits', 'showAttachmentsButton', 'showFileViewerButton', 'webglRendererEnabled',
'terminalFontFamily', 'terminalFontWeight', 'terminalFontWeightBold',
'language',
'terminalWheelLocalScrollback',
'historyReloadAction',
'autoCopySelection', 'copyStripMargin',
'showSessionButton', 'showAwayDigestButton', 'showCronButton', 'showGitStatus', 'gitStatusTree', 'gitStatusMaxRepos', 'gitStatusTimeoutSeconds', 'showEditHistory',
'showTabDetachButton',
+50 -1
View File
@@ -11803,6 +11803,36 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
cursor: default;
}
.file-tree-incomplete button {
margin-inline-start: 0.25rem;
padding: 0.2rem 0.45rem;
color: var(--text-primary);
background: var(--bg-card);
border: 1px solid var(--border-color);
border-radius: 4px;
font: inherit;
font-style: normal;
white-space: nowrap;
cursor: pointer;
}
.file-tree-listing-state {
white-space: normal;
overflow-wrap: anywhere;
}
.file-tree-incomplete button:hover,
.file-tree-incomplete button:focus-visible {
background: var(--bg-hover);
}
@media (pointer: coarse) {
.file-tree-incomplete button {
min-width: 44px;
min-height: 44px;
}
}
.file-tree-icon {
width: 1rem;
text-align: center;
@@ -14199,6 +14229,12 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
resize: none;
line-height: 1.4;
box-sizing: border-box;
/* A backstop: Send on Enter grows the field with its text only on touch devices
(input-cjk.js _autoGrow), where the .touch-device rule caps it too. On desktop
it keeps its one-line height, so this cap only guards against anything else
setting a taller one, which would push the terminal (and its PTY) down. */
max-height: 68px;
overflow-y: auto;
}
#cjkInput:focus {
@@ -14235,6 +14271,13 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
bottom: calc(var(--safe-area-bottom) + 84px);
}
/* Send on Enter grows the field with its text, but with the keyboard down .main
reserves a fixed 84px (below), so a grown field would cover the terminal's
last rows. Keep it one line tall there; the text scrolls inside. */
.touch-device:not(.keyboard-visible) #cjkInput.cjk-input-visible {
max-height: 34px;
}
body.touch-device.cjk-input-visible .main {
padding-bottom: calc(84px + var(--safe-area-bottom));
}
@@ -23602,7 +23645,13 @@ html[data-session-list='sidebar'][data-sidebar='collapsed'] .session-sidebar .ta
font-weight: 500;
}
.session-tabs-host > .session-tabs.tabs-ledger > .session-tab .tab-status {
/* The bar replaces the dot, except on a WORKING cell: the bar is green for
idle and working alike, so the dot and its orbiting ring
(.tab-status.busy::after) stay, the same "working" mark the classic strip
and the home screens draw. An exited agent's cell hides it anyway, as the
classic strip hides the ring there. */
.session-tabs-host > .session-tabs.tabs-ledger > .session-tab .tab-status:not(.busy),
.session-tabs-host > .session-tabs.tabs-ledger > .session-tab.tab-agent-exited .tab-status {
display: none;
}
+731
View File
@@ -0,0 +1,731 @@
/**
* @fileoverview iOS WebKit native editing owner for xterm's helper textarea.
*
* Keep the native line intact and reconcile its projected text into one ordered
* transaction. xterm retains commands, paste and composition rendering, but no
* competing text producer. Native selection is visual only: never send arrows.
*
* The shared platform predicate lives in MobileImePreview, which already owns
* it and loads first. Delegating keeps native ownership and preview gating in
* lockstep without adding another platform detector or script dependency.
*
* @dependency mobile-ime-preview.js (shared isIosWebKitTouch predicate)
* @loadorder 5.56 (after mobile-ime-preview.js, before terminal-ui.js/terminal-tile.js)
*/
(function (global) {
'use strict';
// WebKit removes one grapheme cluster per Backspace, and Claude Code and Codex
// delete one grapheme per DEL, so an edit is counted in graphemes: a red heart,
// a skin-tone emoji, a flag or a ZWJ family is one DEL, as it was through xterm.
// Code points stand in where Intl.Segmenter is missing.
const graphemeSegmenter = (function () {
try {
return typeof Intl !== 'undefined' && typeof Intl.Segmenter === 'function'
? new Intl.Segmenter(undefined, { granularity: 'grapheme' })
: null;
} catch (_) {
return null;
}
})();
function graphemes(text) {
return graphemeSegmenter ? Array.from(graphemeSegmenter.segment(text), (part) => part.segment) : Array.from(text);
}
function editBetween(previous, next) {
// A pure append (including a combining mark or tone typed onto the last letter)
// is sent as-is, as xterm sends it: re-typing the extended cluster would make
// a code-point line editor (zsh) double the base letter.
if (next.startsWith(previous)) return { deleted: 0, inserted: next.slice(previous.length) };
const a = graphemes(previous);
const b = graphemes(next);
let prefix = 0;
while (prefix < a.length && prefix < b.length && a[prefix] === b[prefix]) prefix += 1;
return { deleted: a.length - prefix, inserted: b.slice(prefix).join('') };
}
// Native line breaks are provisional dictation text, never submit commands.
function project(value) {
return value.replace(/\r\n|[\r\n]/g, ' ');
}
const TERMINAL_KEYS = Object.freeze({
Enter: 13,
Tab: 9,
Escape: 27,
ArrowLeft: 37,
ArrowUp: 38,
ArrowRight: 39,
ArrowDown: 40,
Home: 36,
End: 35,
PageUp: 33,
PageDown: 34,
Insert: 45,
Delete: 46,
F1: 112,
F2: 113,
F3: 114,
F4: 115,
F5: 116,
F6: 117,
F7: 118,
F8: 119,
F9: 120,
F10: 121,
F11: 122,
F12: 123,
});
const IOS_COMMANDS = new Set([
'UIKeyInputUpArrow',
'UIKeyInputDownArrow',
'UIKeyInputLeftArrow',
'UIKeyInputRightArrow',
'UIKeyInputEscape',
]);
function classifyKey(ev, textarea) {
if (ev.isComposing || ev.key === 'Process' || ev.keyCode === 229) return 'compose';
if (
ev.ctrlKey ||
ev.metaKey ||
ev.altKey ||
IOS_COMMANDS.has(ev.key) ||
(Object.prototype.hasOwnProperty.call(TERMINAL_KEYS, ev.key) && TERMINAL_KEYS[ev.key] === ev.keyCode)
)
return 'command';
if (ev.key === 'Backspace' && ev.keyCode === 8 && textarea && textarea.value === '') {
return 'backspace-terminal';
}
return 'native';
}
function isSupported() {
return !!(global.MobileImePreview && global.MobileImePreview.isIosWebKitTouch(global.navigator));
}
function create(options) {
const opts = options || {};
function record(entry) {
try {
if (typeof opts.log === 'function') opts.log(entry);
} catch (_) {
/* Diagnostics are optional. */
}
}
function guard(hook, fn, fallback) {
return function (...args) {
try {
return fn.apply(this, args);
} catch (error) {
record({ type: 'error', hook, error });
return fallback;
}
};
}
const patches = [];
const listeners = [];
let textarea;
let whitespace;
let destroyed = false;
let timer = null;
let synced = '';
let cursor = 0;
let invalidated = false;
let foreignSnapshot = null;
let foreignTimer = null;
const caretListeners = new Set(typeof opts.onCaret === 'function' ? [opts.onCaret] : []);
let notifyCaret = function () {};
let composing = false;
let compositionPending = false;
let reconciling = false;
let again = false;
let generation = 0;
function cancelPending() {
if (timer !== null) {
global.clearTimeout(timer);
timer = null;
}
if (foreignTimer !== null) {
global.clearTimeout(foreignTimer);
foreignTimer = null;
}
}
const destroy = guard('destroy', function () {
if (destroyed) return;
destroyed = true;
cancelPending();
notifyCaret();
caretListeners.clear();
for (const [target, type, listener] of listeners) target.removeEventListener(type, listener, true);
if (whitespace) {
if (whitespace.value) textarea.style.setProperty('white-space', whitespace.value, whitespace.priority);
else textarea.style.removeProperty('white-space');
}
// Restore property ownership as well as function identity: most methods
// originally live on xterm's prototype, not on the instance.
for (let i = patches.length - 1; i >= 0; i -= 1) {
const { target, name, descriptor } = patches[i];
if (descriptor) Object.defineProperty(target, name, descriptor);
else delete target[name];
}
});
try {
const terminal = opts.terminal;
const core = terminal && terminal._core;
const helper = core && core._compositionHelper;
textarea = terminal && terminal.textarea;
if (
!textarea ||
!core ||
!helper ||
!core.coreService ||
typeof core.coreService.triggerDataEvent !== 'function' ||
typeof core._inputEvent !== 'function' ||
typeof core._handleTextAreaBlur !== 'function' ||
typeof helper._handleAnyTextareaChanges !== 'function' ||
typeof helper._finalizeComposition !== 'function' ||
!helper._compositionView ||
!helper._compositionView.classList ||
typeof textarea.setSelectionRange !== 'function' ||
(terminal.options && terminal.options.screenReaderMode) ||
(opts.isScreenReaderMode && opts.isScreenReaderMode())
)
return null;
const sendTransaction = opts.sendTransaction;
if (typeof sendTransaction !== 'function') return null;
whitespace = {
value: textarea.style.getPropertyValue('white-space'),
priority: textarea.style.getPropertyPriority('white-space'),
};
// nowrap collapses whitespace, making WebKit replace trailing spaces with
// NBSP. pre preserves native spaces without wrapping or changing real NBSP.
textarea.style.setProperty('white-space', 'pre');
// A pre-existing field has no provenance: it is not evidence of PTY input.
invalidated = textarea.value !== '';
const caret = guard(
'caret',
function () {
const text = project(textarea.value);
const offset = project(textarea.value.slice(0, textarea.selectionEnd)).length;
return {
visible:
!destroyed &&
textarea.ownerDocument.activeElement === textarea &&
!composing &&
textarea.selectionStart === textarea.selectionEnd &&
offset < text.length &&
text === synced &&
!invalidated &&
!foreignSnapshot,
text,
offset,
// Advances only when an edit is reconciled (sent) or the line is reset;
// a borrowed clipboard value and its restoration leave it unchanged.
generation,
};
},
{ visible: false, text: '', offset: 0, generation: 0 }
);
let previousCaret;
notifyCaret = function () {
const current = caret();
if (
previousCaret &&
previousCaret.visible === current.visible &&
previousCaret.text === current.text &&
previousCaret.offset === current.offset &&
previousCaret.generation === current.generation
)
return;
previousCaret = current;
for (const callback of caretListeners) {
try {
callback({ ...current });
} catch (error) {
record({ type: 'error', hook: 'onCaret', error });
}
}
};
const onCaret = guard('onCaret', function (callback) {
if (destroyed || typeof callback !== 'function') return function () {};
caretListeners.add(callback);
return function () {
caretListeners.delete(callback);
};
});
function restoreForeign() {
if (!foreignSnapshot || destroyed) return;
const snapshot = foreignSnapshot;
foreignSnapshot = null;
if (foreignTimer !== null) {
global.clearTimeout(foreignTimer);
foreignTimer = null;
}
textarea.value = snapshot.value;
textarea.setSelectionRange(snapshot.start, snapshot.end, snapshot.direction);
synced = snapshot.synced;
notifyCaret();
}
function invalidate() {
if (invalidated) return;
record({ type: 'drift', value: textarea.value, synced });
// Never replace a supposedly sent baseline with an unproven field.
cancelPending();
foreignSnapshot = null;
synced = '';
cursor = 0;
invalidated = true;
generation += 1;
record({ type: 'reset', reason: 'drift', generation });
notifyCaret();
}
function schedule() {
if (destroyed || timer !== null) return;
timer = global.setTimeout(
guard('timer', function () {
timer = null;
if (!destroyed) reconcile();
}),
0
);
}
function notifyTransaction(transaction) {
try {
if (typeof opts.onTransaction === 'function') opts.onTransaction(transaction);
} catch (error) {
record({ type: 'error', hook: 'onTransaction', error });
}
}
function reconcile() {
if (destroyed || composing || invalidated || foreignSnapshot) return;
if (reconciling) {
again = true;
return;
}
do {
again = false;
const current = project(textarea.value);
const transaction = { ...editBetween(synced, current), composition: compositionPending };
compositionPending = false;
const ops = [];
if (current !== synced) {
const { deleted, inserted } = transaction;
record({ type: 'reconcile', deleted, inserted });
for (let i = 0; i < deleted; i += 1) ops.push('\x7f');
if (inserted) ops.push(inserted);
synced = current;
cursor = Array.from(current).length;
generation += 1;
}
// Publish the end-anchored baseline BEFORE calling out. A reset inside
// the transaction survives; the destination receives all ops atomically.
reconciling = true;
try {
if (ops.length) {
// These ops bypass xterm's triggerDataEvent(data, true), so its
// scrollOnUserInput never runs; scroll to the prompt as xterm would.
try {
if (
terminal.options &&
terminal.options.scrollOnUserInput !== false &&
typeof terminal.scrollToBottom === 'function'
)
terminal.scrollToBottom();
} catch (error) {
record({ type: 'error', hook: 'scrollOnUserInput', error });
}
try {
sendTransaction(ops);
} catch (error) {
record({ type: 'error', hook: 'sendTransaction', error });
invalidated = true;
}
}
// Empty/deletion-only compositions still settle the visual preview.
notifyTransaction(transaction);
} finally {
reconciling = false;
}
} while (again && !destroyed && !composing && !invalidated && !foreignSnapshot);
notifyCaret();
}
const settle = guard('settle', function () {
cancelPending();
reconcile();
});
const reset = guard('reset', function (reason) {
if (destroyed) return;
cancelPending();
foreignSnapshot = null;
textarea.value = '';
invalidated = false;
synced = '';
cursor = 0;
generation += 1;
composing = false;
compositionPending = false;
record({ type: 'reset', reason, generation });
notifyTransaction({ inserted: '', deleted: 0, composition: false });
notifyCaret();
});
const keyFilter = guard(
'keyFilter',
function (ev) {
if (destroyed) return true;
if (ev.type === 'keypress') return false;
if (ev.type === 'keyup') return textarea.ownerDocument.activeElement === textarea;
if (ev.type !== 'keydown') return true;
restoreForeign();
const kind = composing ? 'compose' : classifyKey(ev, textarea);
if (kind === 'compose') {
schedule();
return false;
}
if (kind === 'command') {
settle();
reset('command');
return true;
}
if (kind === 'backspace-terminal') {
settle();
return true;
}
return false;
},
false
);
function patch(target, name, replacement) {
patches.push({ target, name, descriptor: Object.getOwnPropertyDescriptor(target, name) });
target[name] = guard(name, replacement, false);
}
function listen(type, fn, target = textarea) {
const listener = guard(type, fn);
listeners.push([target, type, listener]);
target.addEventListener(type, listener, true);
}
patch(core, '_inputEvent', function (ev) {
if (ev && ev.data && ev.inputType === 'insertText') core._unprocessedDeadKey = false;
return false;
});
patch(helper, '_handleAnyTextareaChanges', schedule);
patch(helper, '_finalizeComposition', function () {
helper._compositionView.classList.remove('active');
helper._isComposing = false;
helper._isSendingComposition = false;
schedule();
});
const originalBlur = core._handleTextAreaBlur;
patch(core, '_handleTextAreaBlur', function (...args) {
restoreForeign();
const value = textarea.value;
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const direction = textarea.selectionDirection;
const before = generation;
try {
return originalBlur.apply(this, args);
} finally {
if (opts.blurPolicy === 'stock') {
synced = '';
cursor = 0;
invalidated = false;
} else if (!destroyed && generation === before) {
textarea.value = value;
textarea.setSelectionRange(start, end, direction);
}
notifyCaret();
}
});
listen('beforeinput', function (ev) {
if (destroyed || composing || ev.isComposing) return;
if (foreignSnapshot || project(textarea.value) !== synced) invalidate();
});
listen('input', function (ev) {
if (!destroyed && !ev.isComposing && !composing) {
if (foreignSnapshot) invalidate();
if (invalidated) reset('drift');
else reconcile();
}
if (!destroyed) notifyCaret();
});
listen('compositionstart', function () {
if (!destroyed) {
composing = true;
notifyCaret();
}
});
listen('compositionend', function () {
if (destroyed) return;
composing = false;
compositionPending = true;
notifyCaret();
schedule();
});
listen(
'selectionchange',
function () {
if (!destroyed && textarea.ownerDocument.activeElement === textarea) notifyCaret();
},
textarea.ownerDocument
);
listen('focus', notifyCaret);
listen('blur', notifyCaret);
// xterm temporarily lends the helper to native Copy. Restore only before
// a new key edit, after Copy has read it, or before blur preservation.
if (terminal.element)
listen(
'contextmenu',
function () {
if (destroyed || foreignSnapshot) return;
foreignSnapshot = {
value: textarea.value,
start: textarea.selectionStart,
end: textarea.selectionEnd,
direction: textarea.selectionDirection,
synced,
};
notifyCaret();
},
terminal.element
);
listen('keydown', restoreForeign);
listen(
'copy',
function () {
if (destroyed || !foreignSnapshot || foreignTimer !== null) return;
foreignTimer = global.setTimeout(
guard('copy timer', function () {
foreignTimer = null;
restoreForeign();
}),
0
);
},
textarea.ownerDocument
);
listen('blur', restoreForeign);
// xterm's paste handler emits the clipboard (bracketed when the app asks)
// but never cancels the event, so the browser would also insert it into
// the field and reconcile would send it a second time. Cancel only the
// native insertion; xterm's bubble listener still runs.
listen('paste', function (ev) {
if (destroyed) return;
settle();
reset('paste');
ev.preventDefault();
});
notifyCaret();
return {
keyFilter,
reset,
settle,
destroy,
caret,
onCaret,
state: guard('state', function () {
return {
value: textarea.value,
synced,
cursor,
composing,
invalidated,
selectionStart: textarea.selectionStart,
selectionEnd: textarea.selectionEnd,
generation,
};
}),
};
} catch (error) {
record({ type: 'error', hook: 'create', error });
destroy();
return null;
}
}
// Visual only: an anchor(caret) supplies the exact viewport cell, 'hide', or
// null to resolve against parsed xterm cells. Neither mode moves native input.
// subscribe(callback) follows overlay repaints without an xterm render.
function bufferCaretAnchor(terminal, caret) {
const buffer = terminal.buffer.active;
const text = caret.text;
if (!text || caret.offset < 0 || caret.offset > text.length) return null;
let row = buffer.baseY + buffer.cursorY;
let col = buffer.cursorX;
let line = buffer.getLine(row);
// Read only as far as the native field and one preceding repetition.
function previousCell() {
while (line) {
if (col === 0) {
if (!line.isWrapped || row === 0) return null;
const following = line;
line = buffer.getLine(--row);
if (!line) return null;
col = terminal.cols;
// A wide glyph that did not fit leaves unused cells before a soft
// wrap. Validate that padding against the following glyph's width;
// ordinary blank cells (including printed spaces) remain text.
let padding = 0;
while (col - padding > 0) {
const cell = line.getCell(col - padding - 1);
if (!cell || cell.getWidth() !== 1 || cell.getChars()) break;
padding += 1;
}
const first = following.getCell(0);
if (padding && first && first.getWidth() > padding) col -= padding;
}
const cell = line.getCell(--col);
if (!cell) return null;
if (cell.getWidth() === 0) continue;
const chars = cell.getChars();
if (!chars) return null;
return { chars, col, row: row - buffer.viewportY };
}
return null;
}
const cells = [];
let remaining = text.length;
while (remaining > 0) {
const cell = previousCell();
if (!cell || cell.chars.length > remaining || text.slice(remaining - cell.chars.length, remaining) !== cell.chars)
return null;
cells.push(cell);
remaining -= cell.chars.length;
}
// A previous identical native-length suffix makes provenance ambiguous.
remaining = text.length;
while (remaining > 0) {
const cell = previousCell();
if (!cell || cell.chars.length > remaining || text.slice(remaining - cell.chars.length, remaining) !== cell.chars)
break;
remaining -= cell.chars.length;
}
if (remaining === 0) return null;
let offset = 0;
for (let i = cells.length - 1; i >= 0; i -= 1) {
const cell = cells[i];
if (caret.offset === offset) return { col: cell.col, row: cell.row };
offset += cell.chars.length;
if (caret.offset < offset) return null; // No cell inside a cluster.
}
return { col: buffer.cursorX, row: buffer.baseY + buffer.cursorY - buffer.viewportY };
}
function attachCaretMarker(terminal, owner, options) {
const anchor = options && typeof options.anchor === 'function' ? options.anchor : null;
const disposables = [];
let marker;
let disposed = false;
let caretGeneration = 0;
let awaitingEcho = false;
function dispose() {
if (disposed) return;
disposed = true;
for (const cleanup of disposables) {
try {
cleanup();
} catch (_) {
/* Terminal teardown may already have run. */
}
}
if (marker) marker.remove();
}
try {
const screen = terminal.element && terminal.element.querySelector('.xterm-screen');
if (!screen || !owner || typeof owner.caret !== 'function' || typeof owner.onCaret !== 'function') return dispose;
caretGeneration = owner.caret().generation;
marker = screen.ownerDocument.createElement('div');
marker.className = 'ios-native-caret';
marker.setAttribute('aria-hidden', 'true');
marker.style.cssText = 'position:absolute;width:2px;pointer-events:none;display:none;z-index:10';
screen.appendChild(marker);
function position() {
try {
const caret = owner.caret();
const core = terminal._core;
const dimensions = core && core._renderService && core._renderService.dimensions;
const cell = dimensions && dimensions.css && dimensions.css.cell;
if (disposed || !caret.visible || !cell || !cell.width || !cell.height || !terminal.cols) {
marker.style.display = 'none';
return;
}
let target = null;
if (anchor) {
try {
target = anchor(caret);
} catch (_) {
target = 'hide';
}
}
if (target == null && !awaitingEcho) target = bufferCaretAnchor(terminal, caret);
if (!target || target === 'hide' || target.row < 0 || target.row >= terminal.rows) {
marker.style.display = 'none';
return;
}
marker.style.display = 'block';
marker.style.left = target.col * cell.width + 'px';
marker.style.top = target.row * cell.height + 'px';
marker.style.height = cell.height + 'px';
marker.style.backgroundColor = (terminal.options.theme && terminal.options.theme.cursor) || 'currentColor';
} catch (_) {
marker.style.display = 'none';
}
}
disposables.push(
owner.onCaret((caret) => {
// Await parsed output only for a reconciled edit or reset (generation),
// never for a borrowed clipboard value or its restoration.
if (caret.generation !== caretGeneration) {
caretGeneration = caret.generation;
awaitingEcho = true;
}
position();
})
);
if (typeof terminal.onWriteParsed === 'function') {
const subscription = terminal.onWriteParsed(() => {
awaitingEcho = false;
position();
});
disposables.push(() => subscription.dispose());
}
for (const name of ['onRender', 'onCursorMove']) {
if (typeof terminal[name] === 'function') {
const subscription = terminal[name](position);
disposables.push(() => subscription.dispose());
}
}
if (options && typeof options.subscribe === 'function') {
try {
const unsubscribe = options.subscribe(position);
if (typeof unsubscribe === 'function') disposables.push(unsubscribe);
} catch (_) {
/* Optional anchor feed. */
}
}
position();
return dispose;
} catch (_) {
dispose();
return dispose;
}
}
global.CodemanIosNativeInput = Object.freeze({ create, editBetween, classifyKey, attachCaretMarker, isSupported });
})(typeof window !== 'undefined' ? window : globalThis);
+25 -4
View File
@@ -60,15 +60,36 @@
(function (global) {
'use strict';
// Grapheme clusters, the unit a soft-keyboard Backspace removes, Claude Code and
// Codex delete per DEL, and the local-echo overlay drops per DEL. Code points
// stand in where Intl.Segmenter is missing (same rule as terminal-ios-native-input.js).
const graphemeSegmenter = (() => {
try {
return typeof Intl !== 'undefined' && typeof Intl.Segmenter === 'function'
? new Intl.Segmenter(undefined, { granularity: 'grapheme' })
: null;
} catch {
return null;
}
})();
function graphemes(text) {
return graphemeSegmenter ? Array.from(graphemeSegmenter.segment(text), (part) => part.segment) : Array.from(text);
}
/**
* What turns `previous` into `next`, as a terminal sees it: how many characters to delete from
* the END of the line, then what to type. Everything after the common prefix is treated as
* replaced, because a terminal can only edit at its cursor. Counts are code points, so an
* emoji is one DEL, as it is one backspace.
* replaced, because a terminal can only edit at its cursor. Counts are grapheme clusters, so a
* red heart, a skin-tone emoji, a flag or a ZWJ family is one DEL, as it is one backspace.
*/
function editBetween(previous, next) {
const a = Array.from(previous);
const b = Array.from(next);
// A pure append (including a combining mark or tone typed onto the last letter)
// is sent as-is: re-typing the extended cluster would make a code-point line
// editor (zsh) double the base letter.
if (next.startsWith(previous)) return { deleted: 0, inserted: next.slice(previous.length) };
const a = graphemes(previous);
const b = graphemes(next);
let prefix = 0;
const max = Math.min(a.length, b.length);
while (prefix < max && a[prefix] === b[prefix]) prefix += 1;
+69 -1
View File
@@ -54,6 +54,7 @@
* @dependency constants.js (window.CodemanTerminalFont, window.CodemanFetchDeadline, DEFAULT_SCROLLBACK, TERMINAL_TAIL_SIZE, SHELL_LOAD_BASE_QUERY, SHELL_LOAD_QUERY, TERMINAL_CHUNK_SIZE)
* @dependency terminal-ui.js (codemanCurrentXtermTheme, codemanCurrentSkinIsLight, CodemanTerminalInput.shouldSuppressTerminalQueryResponse/isTerminalFocusOrMouseReport/wheelDeltaLines/wheelTicksForGesture/coalesceScrollBytes/sgrWheelReports/pageKeysForGesture, app._shouldForwardWheelToApp/_localScrollbackIsHollow/_terminalViewportAtBottom/_clientPointToCell/_handleDesktopTerminalClick, app.tabAlerts)
* @dependency terminal-keycode229-recovery.js (window.CodemanKeyCode229Recovery, optional: absent, xterm's own textarea handling stands)
* @dependency terminal-ios-native-input.js (window.CodemanIosNativeInput, optional iOS native editing owner)
* @loadorder 7.4 of 16, loaded after terminal-ui.js and before terminal-split.js
*/
@@ -227,6 +228,8 @@
// The soft-keyboard controller (terminal-keycode229-recovery.js): created
// in connect() once the xterm is open, torn down in destroy().
this._keyCode229Recovery = null;
this._iosNativeInput = null;
this._iosCaretMarker = null;
}
async connect() {
@@ -275,7 +278,7 @@
this._onFocusIn = () => global.app?._noteFocusedTile?.(this);
this.terminal.textarea?.addEventListener('focus', this._onFocusIn);
this._createKeyCode229Recovery();
this._createInputOwner();
// The twin of terminal-ui.js's onData gate (initTerminal; keep the two in
// step). Canonical xterm data tells the controller this keystroke was
// delivered, but not a query reply or a focus/mouse report, which xterm
@@ -309,6 +312,7 @@
// here too. Ctrl+V goes through the primary pane's paste trap
// (image-input.js), aimed at this pane (below).
this.terminal.attachCustomKeyEventHandler((ev) => {
if (this._iosNativeInput?.keyFilter(ev) === false) return false;
// FIRST, above the IME early return below, as in terminal-ui.js: every
// keydown settles this pane's pending textarea edit and drains a
// pending recovery BEFORE xterm handles the key, so a character an
@@ -639,6 +643,68 @@
app?._sendInputAsync?.(this.sessionId, data);
}
// iOS owns native textarea edits; other platforms retain the 229 recovery.
// Replacing either controller first settles the old tile's pending edit.
_createInputOwner() {
this._destroyIosNativeInput();
this._destroyKeyCode229Recovery();
if (!this.terminal) return;
const nativeInput = global.CodemanIosNativeInput;
if (!nativeInput?.isSupported?.()) {
this._createKeyCode229Recovery();
return;
}
this._iosNativeInput = nativeInput.create({
terminal: this.terminal,
sendTransaction: (ops) => this._sendNativeInputTransaction(ops),
isScreenReaderMode: () => this.terminal?.options?.screenReaderMode === true,
});
if (this._iosNativeInput) {
// Tiles have no local-echo overlay: resolve only from verified parsed cells.
this._iosCaretMarker = nativeInput.attachCaretMarker(this.terminal, this._iosNativeInput);
return;
}
// create() refused (screen reader, missing xterm internals): keep the
// soft-keyboard recovery rather than leaving the tile with neither.
this._createKeyCode229Recovery();
}
_sendNativeInputTransaction(ops) {
const sessionId = this.sessionId;
const app = global.app;
let ctrlIndex = -1;
// Same rule as the primary pane (terminal-ui.js _sendNativeInputTransaction):
// the edit's first insertion spends the armed Ctrl whatever its length.
// consumeCtrl maps a single character and passes a suggestion or emoji
// through unchanged, but it still disarms, so the next `c` stays a `c`.
if (typeof KeyboardAccessoryBar !== 'undefined' && KeyboardAccessoryBar.isCtrlArmed?.()) {
ctrlIndex = ops.findIndex((data) => data !== '\x7f');
if (ctrlIndex === -1 && ops.includes('\x7f')) KeyboardAccessoryBar.clearCtrl?.();
}
// Keep replacement deletions: Ctrl changes only the insertion, once for
// this edit, never once per DEL. Tiles have no local echo to reconcile.
const writes = ops.map((data, i) => ({
write: i === ctrlIndex ? KeyboardAccessoryBar.consumeCtrl(data) : data,
}));
if (app?._enqueueInput) app._enqueueInput(sessionId, writes);
else for (const { write } of writes) app?._sendInputAsync?.(sessionId, write);
if (ctrlIndex !== -1) this._iosNativeInput?.reset('ctrl');
}
_destroyIosNativeInput() {
try {
this._iosNativeInput?.settle();
} finally {
try {
this._iosNativeInput?.destroy();
} finally {
this._iosNativeInput = null;
this._iosCaretMarker?.();
this._iosCaretMarker = null;
}
}
}
// The soft-keyboard controller, the twin of the primary pane's wiring in
// terminal-ui.js initTerminal() (keep the two in step); the behaviour lives
// once, in terminal-keycode229-recovery.js. Everything it is handed is THIS
@@ -1554,6 +1620,8 @@
}
destroy() {
if (global.app?._focusedTile === this && typeof CjkInput !== 'undefined') CjkInput.flushNow?.();
this._destroyIosNativeInput();
this._destroyed = true;
// Anything still queued for this session stays in the app's queue and is
// delivered over HTTP by the redelivery sweep, so closing the pane mid-
File diff suppressed because it is too large. Load diff
+14
View File
@@ -2651,6 +2651,20 @@ Object.assign(CodemanApp.prototype, {
// Aborts any in-flight normal select at its next _isStaleSelect check.
const selectGen = ++this._selectGeneration;
this._hideWebviewLayer?.();
// The one CJK field follows tile focus, and Enter sends to the session
// active at that moment: a Send on Enter draft typed for one tile must not
// go to the next. Stash it for the tile left, show the one focused (also
// the draft openTileGrid's cleanup stashed for the session it parked).
if (typeof CjkInput !== 'undefined') {
if (this.activeSessionId && this.activeSessionId !== sessionId) {
// A tile closed from this tab is already gone from this.sessions and
// its draft discarded: stashing it again would leave it in the map
// until the page reloads.
if (this.sessions?.has(this.activeSessionId)) CjkInput.stashDraft?.(this.activeSessionId);
CjkInput.clear();
}
CjkInput.restoreDraft?.(sessionId);
}
this.activeSessionId = sessionId;
grid.focusedId = sessionId;
// Moving focus off a zoomed tile restores the grid, as selecting another
+28 -12
View File
@@ -25,7 +25,7 @@
* @globals {object} VoiceInput
*
* @dependency mobile-handlers.js (MobileDetection for device checks)
* @dependency app.js (uses global `app` for sendInput, showToast, terminal focus)
* @dependency app.js (uses global `app` for _sendInputAsync, _enqueueInput, _prepareExternalInput, showToast, terminal focus)
* @loadorder 3 of 15 — loaded after mobile-handlers.js, before notification-manager.js
*/
@@ -1071,19 +1071,18 @@ const VoiceInput = {
return this._targetSessionId || app.activeSessionId;
},
/**
* Send text to the dictation's own session. The active session keeps going
* through app.sendInput() exactly as before; any other session goes straight
* to the durable queue with the same useMux flag sendInput() passes.
*/
/** Send only to the captured dictation session, never the current tab. */
_sendToTarget(target, text) {
if (target === app.activeSessionId) return app.sendInput(text);
// Closed while dictating: say so instead of queueing text for a session
// that will only answer 404 (and never typing it into some other tab).
if (app.sessions && !app.sessions.has(target)) {
app.showToast?.('That session has closed; dictation not sent', 'warning');
return Promise.resolve();
}
// Settle the destination's iOS owner, but leave an unsent local-echo draft
// in the overlay: flushing it would prepend it to the reviewed dictation.
const pane = app._paneForSession?.(target);
if (pane) app._prepareExternalInput?.(pane, 'voice-send');
app._sendInputAsync(target, text, { useMux: true });
return Promise.resolve();
},
@@ -1098,6 +1097,7 @@ const VoiceInput = {
// If a compose overlay is already open, populate its textarea instead of recreating
const existingTextarea = document.querySelector('.voice-compose-overlay .paste-textarea');
if (existingTextarea) {
existingTextarea.closest('.voice-compose-overlay').dataset.targetSessionId = target;
existingTextarea.value = trimmed;
existingTextarea.focus();
existingTextarea.selectionStart = existingTextarea.selectionEnd = trimmed.length;
@@ -1113,7 +1113,13 @@ const VoiceInput = {
// sees, so it goes straight to the session instead.
const isActive = target === app.activeSessionId;
const tilesOpen = !!app._tilesOwnTerminal?.();
const pane = app._focusedPane?.();
if (isActive && !tilesOpen && app._localEchoEnabled && app._localEchoOverlay) {
// Focus may have moved to Pane B, but this overlay still belongs to A.
const targetPane = pane?.isPrimary && pane.sessionId === target
? pane
: { isPrimary: true, tile: null, terminal: app.terminal, sessionId: target };
app._prepareExternalInput?.(targetPane, 'voice-insert');
app._localEchoOverlay.appendText(trimmed);
} else {
this._sendToTarget(target, trimmed).catch(() => {});
@@ -1158,24 +1164,33 @@ const VoiceInput = {
this._voiceSendHandler = () => {
const target = this._targetSession();
if (!target) return;
const pane = app._focusedPane?.();
const tilesOpen = !!app._tilesOwnTerminal?.();
if (target === app.activeSessionId && !tilesOpen) {
const targetPane = pane?.isPrimary && pane.sessionId === target
? pane
: { isPrimary: true, tile: null, terminal: app.terminal, sessionId: target };
app._prepareExternalInput?.(targetPane, 'voice-submit');
}
// Simulate Enter key: if local echo is active, flush its buffer + send \r;
// otherwise just send \r directly to the PTY. Both the overlay and the
// predictions belong to the ACTIVE session's MAIN terminal, so a
// dictation for another session, or for a tile while the grid has the
// main terminal parked, just sends its Enter there.
if (target !== app.activeSessionId || app._tilesOwnTerminal?.()) {
if (target !== app.activeSessionId || tilesOpen) {
this._sendToTarget(target, '\r').catch(() => {});
} else if (app._localEchoEnabled && app._localEchoOverlay) {
const text = app._localEchoOverlay.pendingText || '';
app._localEchoOverlay.clear();
app._localEchoOverlay.suppressBufferDetection();
if (text) app.sendInput(text).catch(() => {});
setTimeout(() => app.sendInput('\r').catch(() => {}), 80);
const ops = text ? [{ write: text, useMux: true }, { gap: 80 }] : [];
ops.push({ write: '\r', useMux: true });
app._enqueueInput(target, ops);
} else {
// Predict-mode sessions (codex) take this branch: the send bypasses
// onData, so clear outstanding predictions here (composer will reset)
app._predictiveEcho?.clearPredictions();
app.sendInput('\r').catch(() => {});
app._sendInputAsync(target, '\r', { useMux: true });
}
// Blink then restore
gear.classList.add('voice-send-blink');
@@ -1205,6 +1220,7 @@ const VoiceInput = {
document.querySelector('.voice-compose-overlay')?.remove();
const overlay = document.createElement('div');
overlay.className = 'voice-compose-overlay paste-overlay';
overlay.dataset.targetSessionId = this._targetSession();
overlay.innerHTML = `
<div class="paste-dialog">
<textarea class="paste-textarea">${text.replace(/</g, '&lt;')}</textarea>
@@ -1219,7 +1235,7 @@ const VoiceInput = {
const send = () => {
const val = textarea.value.trim();
overlay.remove();
if (val) this._sendToTarget(this._targetSession(), val + '\r').catch(() => {});
if (val) this._sendToTarget(overlay.dataset.targetSessionId, val + '\r').catch(() => {});
};
const cancel = () => overlay.remove();
const newInput = () => {
+9 -9
View File
@@ -1,13 +1,13 @@
{
"version": "1.51.0",
"version": "1.52.0",
"highlights": [
"Local models: a library, more models, and the coding agent you choose (#803, #804, #806, #807, #808)",
"Mac app: With the Lid Closed no longer asks for a password",
"Auto-compact and auto-clear see the whole context (#777)",
"jcode as a run mode (#650)",
"The File Viewer edits `.env` files (#796, #797)",
"Response viewer: a Copy Markdown button (#810)",
"Firefox no longer pastes twice on Ctrl+V (#799)",
"An omp pane that asks for a tool approval alerts (#798)"
"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)"
]
}
+112 -1
View File
@@ -23,6 +23,7 @@ import type {
FilesystemPreviewKind,
FileDeleteData,
FileWriteData,
LazyFileListingData,
} from '../../types.js';
import { ApiErrorCode, createErrorResponse, getErrorMessage } from '../../types.js';
import { compileFileQuery } from '../../utils/file-query.js';
@@ -91,6 +92,8 @@ import {
FilesystemMkdirSchema,
FilesystemPreviewQuerySchema,
FileWriteSchema,
LazyFileListingQuerySchema,
FileListingCursorSchema,
} from '../schemas.js';
import {
MAX_EDITABLE_BYTES,
@@ -1742,11 +1745,12 @@ export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort & Even
// File tree listing
app.get('/api/sessions/:id/files', async (req) => {
const { id } = req.params as { id: string };
const { depth, showHidden, q, root } = req.query as {
const { depth, showHidden, q, root, lazy } = req.query as {
depth?: string;
showHidden?: string;
q?: string;
root?: string;
lazy?: string;
};
const session = findSessionOrFail(ctx, id, req);
@@ -1821,6 +1825,113 @@ export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort & Even
const isListed = (entry: Dirent): boolean =>
(includeHidden || !entry.name.startsWith('.')) && !(entry.isDirectory() && excludeDirs.has(entry.name));
// One folder at a time for the Files panel. Keep the legacy tree/search branches below
// untouched: existing callers depend on their exact response shape and scan policy.
if (lazy === '1' && !matcher && !session.remote) {
const parsed = LazyFileListingQuerySchema.safeParse(req.query);
if (!parsed.success) throwRouteError(400, ApiErrorCode.INVALID_INPUT, 'Invalid directory listing query');
const { path: directoryPath, cursor } = parsed.data;
const namedPath = directoryPath ? resolve(workingDir, directoryPath) : walkRoot;
const lexical = validateSessionFilePathLexical(walkRoot, namedPath);
if (!lexical) throwRouteError(403, ApiErrorCode.FORBIDDEN, 'Directory is outside the selected workspace');
const checkKind = async (folder: string): Promise<void> => {
const kind = await probePathKind(folder, { pastCap: true });
if (kind === 'unknown') {
throwRouteError(
422,
ApiErrorCode.OPERATION_FAILED,
describeUnknownPath('The folder', folder, { pastCap: true })
);
}
if (kind === 'absent') throwRouteError(404, ApiErrorCode.NOT_FOUND, 'Folder not found');
if (kind !== 'directory') throwRouteError(400, ApiErrorCode.INVALID_INPUT, 'Path is not a directory');
};
// Probe before synchronous confinement and before readdir (#516), including a request
// naming a directory on an unresponsive mount. Never turn unknown into an empty list.
await checkKind(walkRoot);
if (namedPath !== walkRoot) await checkKind(namedPath);
const validated = validateLocalSessionFilePath({ workingDir, liveWorktree }, namedPath);
const selected = validated && validateSessionFilePath(walkRoot, namedPath);
if (!selected) throwRouteError(403, ApiErrorCode.FORBIDDEN, 'Directory is outside the selected workspace');
const refusedSegment = (path: string): boolean =>
path.split(sep).some((part) => excludeDirs.has(part) || (!includeHidden && part.startsWith('.')));
// Both names matter: an alias may point at an excluded/hidden directory.
if (refusedSegment(lexical.relativePath) || refusedSegment(selected.relativePath)) {
throwRouteError(403, ApiErrorCode.FORBIDDEN, 'Directory is excluded or hidden');
}
const scope = createHash('sha256')
.update(JSON.stringify([id, walkRoot, namedPath, includeHidden]))
.digest('hex');
let after: { name: string; directory: boolean } | undefined;
if (cursor) {
try {
const decoded = FileListingCursorSchema.parse(JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')));
if (decoded.scope !== scope) throw new Error('Different listing');
after = decoded;
} catch {
throwRouteError(400, ApiErrorCode.INVALID_INPUT, 'Invalid directory continuation; refresh files');
}
}
const compare = (a: { name: string; directory: boolean }, b: { name: string; directory: boolean }): number =>
Number(b.directory) - Number(a.directory) ||
a.name.localeCompare(b.name) ||
(a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
let entries: Dirent[];
try {
entries = await fs.readdir(namedPath, { withFileTypes: true });
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT')
throwRouteError(404, ApiErrorCode.NOT_FOUND, 'Folder not found');
throwRouteError(422, ApiErrorCode.OPERATION_FAILED, 'Folder unavailable; retry or refresh files');
}
const listed = entries
.filter(
(entry) =>
isListed(entry) && (!after || compare({ name: entry.name, directory: entry.isDirectory() }, after) > 0)
)
.sort((a, b) =>
compare({ name: a.name, directory: a.isDirectory() }, { name: b.name, directory: b.isDirectory() })
);
// Bound both the response and metadata reads, independently for every folder/page.
const page = listed.slice(0, 500);
const data: LazyFileListingData = {
root: walkRoot,
...(reportedWorktree && { worktree: reportedWorktree }),
lazy: true,
tree: [],
totalFiles: 0,
totalDirectories: 0,
truncated: listed.length > page.length,
};
for (const entry of page) {
const fullPath = join(namedPath, entry.name);
if (entry.isDirectory()) {
data.tree.push({ name: entry.name, path: nodePath(fullPath), type: 'directory' });
data.totalDirectories++;
} else {
// Match legacy leaf rows, including symbolic links; directory links are not traversed.
let size: number | undefined;
try {
size = (await fs.stat(fullPath)).size;
} catch {
/* A disappearing file is still a listed entry. */
}
const extension = entry.name.includes('.') ? entry.name.split('.').pop()?.toLowerCase() : undefined;
data.tree.push({ name: entry.name, path: nodePath(fullPath), type: 'file', size, extension });
data.totalFiles++;
}
}
if (data.truncated) {
const last = page[page.length - 1];
data.nextCursor = Buffer.from(
JSON.stringify({ scope, name: last.name, directory: last.isDirectory() })
).toString('base64url');
}
return { success: true, data };
}
// ===== Search mode =====
// A query turns this endpoint into a FLAT match list rather than a nested
// tree. It recurses past non-matching directories on purpose — the whole
+16 -5
View File
@@ -14,11 +14,12 @@ import { execSync, spawn } from 'node:child_process';
import { randomBytes } from 'node:crypto';
import { dataPath } from '../../config/instance.js';
import { readHostSensors } from '../../host-sensors.js';
import { createCpuUsageMeter } from '../../cpu-usage.js';
import { ApiErrorCode, createErrorResponse, getErrorMessage, type NiceConfig } from '../../types.js';
import { isExplicitlyEnabled, isUnauthenticatedTunnelAcknowledged } from '../network-auth-policy.js';
import { isMultiUserMode } from '../../config/multiuser.js';
import { findUser, canUsernameRunPrivilegedCommands } from '../../user-store.js';
import { getAuthUser, isAdmin, requireAdmin, canAccessOwned, revokeUserSessions } from '../route-helpers.js';
import { getAuthUser, isAdmin, requireAdmin, canAccessOwned, revokeUserSessions, ownerFor } from '../route-helpers.js';
import {
ConfigUpdateSchema,
SettingsUpdateSchema,
@@ -93,6 +94,15 @@ const SCREENSHOTS_DIR = dataPath('screenshots');
/** Cached CPU count — doesn't change at runtime */
const CPU_COUNT = cpus().length;
/** Header CPU use; the 1-minute load average per core only when the platform reports no core times. */
const cpuUsagePercent = createCpuUsageMeter(
cpus,
() => performance.now(),
() =>
// That is also the platform where cpus() is empty, so CPU_COUNT can be 0 here.
CPU_COUNT > 0 ? Math.min(100, Math.round((loadavg()[0] / CPU_COUNT) * 100)) : 0
);
function parseOptionalNumber(value: string | undefined): number | undefined {
if (value === undefined || value.trim() === '') return undefined;
const parsed = Number(value);
@@ -125,9 +135,7 @@ function getSystemStats(): {
usedMem = totalMem - freemem();
}
// CPU load average (1 min) as percentage (rough approximation)
const load = loadavg()[0];
const cpuPercent = Math.min(100, Math.round((load / CPU_COUNT) * 100));
const cpuPercent = cpuUsagePercent();
return {
cpu: cpuPercent,
@@ -659,7 +667,10 @@ export function registerSystemRoutes(
if (!dir) return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getDeepSeekNotFoundMessage());
const { startDeepSeekWeb } = await import('../../deepseek-web-server.js');
const result = await startDeepSeekWeb(dir, authority);
// The launch cookie is bound to the identity whose request started the
// process, so `ownerFor` (undefined in single-user) is recorded here rather
// than the synthetic admin `getAuthUser` would report.
const result = await startDeepSeekWeb(dir, authority, ownerFor(req));
if (!result.ok) return createErrorResponse(ApiErrorCode.OPERATION_FAILED, result.error);
return { success: true, data: { port: result.port, url: result.url, reused: result.reused } };
});
+66 -2
View File
@@ -36,6 +36,7 @@ import { WebSocket as WsClient } from 'ws';
import type { ClientOptions as WsClientOptions, WebSocket } from 'ws';
import type { Response as UndiciResponse } from 'undici';
import { getDataDir } from '../../config/instance.js';
import { isMultiUserMode } from '../../config/multiuser.js';
import {
MAX_LIVE_WEBVIEW_FRAMES,
MAX_WEBVIEWS,
@@ -47,9 +48,11 @@ import {
WEBVIEW_WS_HANDSHAKE_TIMEOUT_MS,
} from '../../config/webview-limits.js';
import { readWebviews, writeWebviews } from '../../webview-store.js';
import { canUsernameRunPrivilegedCommands } from '../../user-store.js';
import { webviewCapabilities } from '../../webview-capabilities.js';
import { egressBlockedReason, webviewEgressLookup, webviewFetch, type EgressLookup } from '../webview-egress.js';
import { blockedWebviewHostReason } from '../webview-egress-policy.js';
import { getDeepSeekWebCookie } from '../../deepseek-web-server.js';
import { ApiErrorCode, createErrorResponse } from '../../types.js';
import type { Webview, WebviewOpenData, WebviewProbe } from '../../types.js';
import { AUTH_COOKIE_NAME } from '../middleware/auth.js';
@@ -64,8 +67,10 @@ import {
buildUpstreamRequestHeaders,
capabilityFromReferer,
extractFrameAncestors,
filterCookieHeader,
isFramableCrossOrigin,
isHtmlContentType,
mergeCookieHeader,
parseWebviewUrl,
proxyPrefixFor,
resolveUpstreamUrl,
@@ -426,6 +431,51 @@ function proxyHttp(
return proxyRequest(req, reply, req.params.cap, req.params['*'] ?? '', basePath);
}
/**
* The credential a Codeman-managed dashboard needs on every upstream request.
*
* `dsh web` now gates its index and `/api` behind a cookie minted for the
* authority it was started on, and only the URL it prints on boot carries the
* token that buys it. The managed DeepSeek tab deliberately stores the clean
* URL, so the browser can never hold that cookie: `deepseek-web-server.ts`
* exchanges the token at startup, and this is where the supervisor's result
* reaches the request.
*
* Strictly scoped to the exact loopback origin the cookie was minted for. A
* web tab the user repointed at another host, or a stale tab still naming a
* previous port, must not be handed a credential that is not its own.
*
* ⚠️ `managed` is accepted from the client on POST/PATCH /api/webviews, and the
* live port is published by GET /api/deepseek/web, so "this record is managed and
* points at the port" is NOT an entitlement: without the check below, any signed-in
* user could save `{ url: "http://127.0.0.1:<port>", managed: "deepseek-web" }` and
* be handed the cookie bought by the user allowed to start the server. The gate
* needs the owner's privileged-commands grant, which is the same bar
* `POST /api/deepseek/web` applies before it starts a server.
*
* @param webview - the saved tab being proxied.
* @param upstream - resolved upstream URL for this request.
* @returns `name=value` cookie pair, or undefined when none applies.
*/
async function managedDashboardCookie(webview: Webview, upstream: URL): Promise<string | undefined> {
if (webview.managed !== 'deepseek-web') return undefined;
if (upstream.hostname !== '127.0.0.1') return undefined;
if (isMultiUserMode()) {
// Fail closed on an ownerless legacy record: `canUsernameRunPrivilegedCommands`
// treats an absent username as privileged (right for a cron job with no owner,
// wrong here), so the owner must be present before it is asked.
if (!webview.owner) return undefined;
if (!(await canUsernameRunPrivilegedCommands(webview.owner))) return undefined;
}
const port = Number(upstream.port || (upstream.protocol === 'https:' ? 443 : 80));
// The second identity check is the supervisor's: even an entitled owner gets
// nothing from a process another user started (POST restarts it for a new
// starter, so that tab simply reopens with its own cookie). Only in multi-user
// mode: a record created there keeps its owner, while a single-user start has
// no starter, so comparing that owner would refuse the tab for good.
return getDeepSeekWebCookie(port, isMultiUserMode() ? webview.owner : undefined) ?? undefined;
}
/**
* Proxy one request to the dashboard behind `cap`, serving `wildcard` as the
* upstream path. Split out from the route handler so the 404 fallback (which has
@@ -468,12 +518,14 @@ async function proxyRequest(
}
const hasBody = req.method !== 'GET' && req.method !== 'HEAD';
const injectedCookie = await managedDashboardCookie(webview, upstream);
const headers = buildUpstreamRequestHeaders(req.headers, upstream, {
forwardCookies: webview.trusted,
sessionCookieName: AUTH_COOKIE_NAME,
refererPath:
typeof req.headers.referer === 'string' ? stripProxyPrefix(req.headers.referer, cap, basePath) : undefined,
relayBodyLength: hasBody && req.body !== undefined,
...(injectedCookie ? { injectedCookie } : {}),
});
// #237: the timeout bounds TIME-TO-HEADERS only. A plain AbortSignal.timeout on
@@ -595,7 +647,9 @@ async function proxyRequest(
// Buffer only HTML, only under the cap: `<base>` injection needs the whole
// document, and buffering an unbounded upstream body is a memory hazard.
const html = await response.text();
return reply.send(html.length <= MAX_WEBVIEW_HTML_REWRITE_BYTES ? rewriteHtml(html, cap, basePath) : html);
return reply.send(
html.length <= MAX_WEBVIEW_HTML_REWRITE_BYTES ? rewriteHtml(html, cap, basePath, wildcard) : html
);
}
return reply.send(Readable.fromWeb(response.body as Parameters<typeof Readable.fromWeb>[0]));
@@ -707,13 +761,23 @@ function proxyWebSocket(socket: WebSocket, req: FastifyRequest<{ Params: ProxyPa
};
const protocols = req.headers['sec-websocket-protocol'];
// The same credential the HTTP leg presents. A managed dashboard's realtime
// channel is gated exactly like its index, so without this the page loads
// and then sits there silently disconnected. Trusted dashboards get the
// browser's other cookies too, but never Codeman's own session cookie,
// with or without an injected one: the HTTP leg strips it the same way.
const injectedCookie = await managedDashboardCookie(webview, upstream);
const browserCookie = webview.trusted
? filterCookieHeader(req.headers.cookie ? String(req.headers.cookie) : undefined, [AUTH_COOKIE_NAME])
: undefined;
const cookie = injectedCookie ? mergeCookieHeader(browserCookie, injectedCookie) : browserCookie;
// `lookup` is absent from ws's ClientOptions typings but flows through
// http.request to net.connect untouched, which is where the resolved
// address is judged (see webview-egress.ts).
const upstreamOptions: WsClientOptions & { lookup: EgressLookup } = {
headers: {
origin: upstream.origin,
...(webview.trusted && req.headers.cookie ? { cookie: String(req.headers.cookie) } : {}),
...(cookie ? { cookie } : {}),
},
handshakeTimeout: WEBVIEW_WS_HANDSHAKE_TIMEOUT_MS,
lookup: webviewEgressLookup,
+28
View File
@@ -134,6 +134,34 @@ export const FilesystemPreviewQuerySchema = z.object({
showHidden: showHiddenQuerySchema,
});
/** Additive Files-panel listing mode. Existing recursive callers are not parsed through this. */
export const LazyFileListingQuerySchema = z.object({
path: z
.string()
.max(4096)
.refine((p) => !p.includes('\0'))
.optional(),
cursor: z
.string()
.min(1)
.max(4096)
.regex(/^[A-Za-z0-9_-]+$/)
.optional(),
});
/** A continuation key, scoped to one session, root, directory and hidden-files preference. */
export const FileListingCursorSchema = z
.object({
scope: z.string().regex(/^[a-f0-9]{64}$/),
name: z
.string()
.min(1)
.max(255)
.refine((name) => !name.includes('\0') && !name.includes('/')),
directory: z.boolean(),
})
.strict();
/**
* Body validation for `PUT /api/sessions/:id/file-content` (File Viewer edit
* mode). `content.max()` counts UTF-16 code units, which for UTF-8 output is
+51 -1
View File
@@ -269,7 +269,7 @@ import {
registerCliRegistryRoutes,
registerLocalModelRoutes,
} from './routes/index.js';
import { isLostWebviewFrameNavigation } from './webview-proxy.js';
import { escapedWebviewAssetPath, isLostWebviewFrameNavigation } from './webview-proxy.js';
import { CronService } from '../cron/cron-service.js';
import { caseSessionSettled } from '../case-rename.js';
@@ -361,6 +361,38 @@ function getOrCreateSelfSignedCert(): { key: string; cert: string } {
};
}
/**
* One warn per escaped path per few minutes.
*
* A page whose boot module 404s retries in a loop, so an undeduped warn would
* bury the log it is meant to explain. Capped so a page emitting unbounded
* unique paths cannot grow the map without limit.
*/
const escapedWebviewWarnedAt = new Map<string, number>();
const ESCAPED_WEBVIEW_WARN_TTL_MS = 5 * 60_000;
/**
* Name a root-absolute request that escaped a web tab's proxy prefix.
*
* Nothing is retried or rewritten here — the request genuinely has no capability
* to relay to. This exists because that failure is otherwise silent: the tab
* shows a blank page or a spinner that never resolves, and the log says nothing.
*
* @param path - request path already judged as that shape.
*/
function warnEscapedWebviewAsset(path: string): void {
const now = Date.now();
const last = escapedWebviewWarnedAt.get(path);
if (last !== undefined && now - last < ESCAPED_WEBVIEW_WARN_TTL_MS) return;
if (escapedWebviewWarnedAt.size >= 200) escapedWebviewWarnedAt.clear();
escapedWebviewWarnedAt.set(path, now);
console.warn(
`[Webview] ${path} escaped the proxy: a web tab asked for a root-absolute URL that no Codeman route serves. ` +
`Its URL is masked, so the Referer cannot identify the dashboard. Usual cause: a URL built at runtime ` +
`(dynamic import(), worker, service worker) or an import inside an external script. The tab will look blank or stuck.`
);
}
export class WebServer extends EventEmitter {
private app: FastifyInstance;
private sessions: Map<string, Session> = new Map();
@@ -1294,6 +1326,11 @@ export class WebServer extends EventEmitter {
// and the relay declines unless the Referer carries a live capability, so
// genuinely unknown `/api` paths still get the envelope below.
if (await tryWebviewRefererFallback(req, reply, this.basePath)) return reply;
// No capability in the Referer, so this cannot be relayed — but if it has
// the shape of a dashboard asset, say so once. Silent 404s here are what
// turned a boot-module failure into a "blank tab" mystery more than once.
const escaped = escapedWebviewAssetPath({ method: req.method, url: req.url, headers: req.headers });
if (escaped) warnEscapedWebviewAsset(escaped);
// An authenticated web-tab frame (Basic auth, or trusted mode with a cookie)
// that navigated itself off its proxy prefix: the runtime shim masks the
// prefix so the page's router sees its own path, and a reload of that page
@@ -2133,6 +2170,19 @@ export class WebServer extends EventEmitter {
'</head>',
() => `<script>window.__codemanKeyboardHoldModes=${JSON.stringify(keyboardHoldClis)};</script>\n</head>`
);
// Which run modes take the wheel as SGR reports while they track the mouse
// (`_shouldForwardWheelToApp`), keyed by id with the `wheelForward` rule itself, so a
// custom clis.json entry shaped like pi forwards under its own id. `never` is left out.
// Disabled entries are kept (`listClis`, not `enabledClis`): disabling a CLI never ends
// its running sessions, and their wheel must keep working across a reload.
// `minVersion` is a free string a user's clis.json sets, hence the script escaper.
const wheelForwardClis = Object.fromEntries(
listClis()
.filter((entry) => entry.capabilities.wheelForward.mode !== 'never')
.map((entry) => [entry.id, entry.capabilities.wheelForward])
);
const wheelForwardJson = escapeScriptJson(JSON.stringify(wheelForwardClis));
html = html.replace('</head>', () => `<script>window.__codemanWheelForward=${wheelForwardJson};</script>\n</head>`);
if (!soloSessionId && process.env.CODEMAN_GESTURE === '1') {
html = html.replace('</head>', () => `<script>window.__codemanGestureAvailable=true;</script>\n</head>`);
if (settings.gestureControlEnabled === true) {
+194 -5
View File
@@ -207,6 +207,73 @@ export function capabilityFromReferer(referer: string | undefined, basePath = ''
}
}
/** `Sec-Fetch-Dest` values that describe a page fetching for itself, not navigating. */
const ASSET_FETCH_DESTS = new Set([
'script',
'style',
'image',
'font',
'manifest',
'worker',
'sharedworker',
'audio',
'video',
'track',
'embed',
'object',
'empty',
]);
/** Codeman's own missing files: a 404 here says nothing about a web tab. */
const CODEMAN_OWN_404 =
/^\/(?:favicon\.ico|manifest\.json|manifest\.webmanifest|robots\.txt|apple-touch-icon[\w.-]*)$/i;
/**
* Whether a 404 looks like a proxied dashboard's root-absolute request that
* escaped the prefix.
*
* This decides NOTHING about the response — the request cannot be relayed (a
* masked frame's `Referer` carries no capability, which is exactly why the
* Referer fallback above declined). It exists so the failure is diagnosable:
* the symptom of an escaped URL is a blank page or a spinner that never
* resolves, with nothing in the log to say why. Naming the path turns that into
* one grep.
*
* Deliberately conservative — a masked landing frame (`Referer` path `/`), an
* asset-shaped `Sec-Fetch-Dest`, same origin, not the API, not one of Codeman's
* own files. A false positive is a log line, never a behaviour change.
*
* @param input - method, request URL and headers of the 404.
* @returns the escaped path (no query), or null when it is not that shape.
*/
export function escapedWebviewAssetPath(input: {
method: string;
url: string;
headers: Record<string, string | string[] | undefined>;
}): string | null {
if (input.method !== 'GET' && input.method !== 'HEAD') return null;
const path = input.url.split('?')[0] ?? '';
if (path.startsWith('/api') || CODEMAN_OWN_404.test(path)) return null;
const single = (value: string | string[] | undefined): string | undefined =>
Array.isArray(value) ? value[0] : value;
const dest = single(input.headers['sec-fetch-dest']);
if (!dest || !ASSET_FETCH_DESTS.has(dest.toLowerCase())) return null;
const host = single(input.headers.host);
const referer = single(input.headers.referer);
if (!host || !referer) return null;
try {
const from = new URL(referer);
// Same origin, and the masked landing path: a real Codeman page's assets all
// resolve, so a 404 from one is not this shape.
if (from.host !== host || from.pathname !== '/') return null;
} catch {
return null;
}
return path;
}
/** Remove the `frame-ancestors` directive from a CSP, preserving the rest. */
export function stripFrameAncestors(csp: string): string {
return csp
@@ -296,6 +363,20 @@ export function rewriteSetCookie(cookie: string, capability: string, secureConte
return out.join('; ');
}
/**
* Put a server-held credential in front of the cookies the browser sent.
*
* Order matters: a `Cookie` header can name the same cookie twice, and parsers
* that collapse it into a map keep the FIRST value (RFC 6265 §5.4 leaves the
* choice open; the common Node parsers take the first). The browser may still
* hold a stale copy of the same dsh cookie from an earlier proxied response, so
* the credential minted by the running process must lead, with everything else
* preserved behind it.
*/
export function mergeCookieHeader(browserCookie: string | undefined, injectedCookie: string): string {
return browserCookie ? `${injectedCookie}; ${browserCookie}` : injectedCookie;
}
/** Drop named cookies from a `Cookie` request header, returning undefined if none remain. */
export function filterCookieHeader(cookie: string | undefined, drop: string[]): string | undefined {
if (!cookie) return undefined;
@@ -311,7 +392,21 @@ export function filterCookieHeader(cookie: string | undefined, drop: string[]):
export function buildUpstreamRequestHeaders(
incoming: Record<string, string | string[] | undefined>,
upstream: URL,
opts: { forwardCookies: boolean; sessionCookieName: string; refererPath?: string; relayBodyLength?: boolean }
opts: {
forwardCookies: boolean;
sessionCookieName: string;
refererPath?: string;
relayBodyLength?: boolean;
/**
* A credential the SERVER holds for this dashboard, put in front of whatever
* browser cookies were forwarded (see `mergeCookieHeader` for why the order
* matters). `dsh web` mints its session cookie for a loopback authority the
* browser never visits, so the proxy is the only party that can present it
* (see `deepseek-web-server.ts`); the managed tab is trusted, which means the
* browser may also carry other cookies dsh set, and those must survive.
*/
injectedCookie?: string;
}
): Record<string, string> {
const headers: Record<string, string> = {};
@@ -343,6 +438,14 @@ export function buildUpstreamRequestHeaders(
if (cookie) headers['cookie'] = cookie;
}
// In front of the relayed cookies rather than after them, so a stale browser
// copy of the same cookie cannot shadow the one minted by the running process
// (the parser keeps the first value). Other cookies are kept: a managed dsh tab
// is trusted, so dsh's own non-auth cookies may legitimately be there.
if (opts.injectedCookie) {
headers['cookie'] = mergeCookieHeader(headers['cookie'], opts.injectedCookie);
}
// Present as if the browser were talking to the dashboard directly. Apps that
// check Origin on writes (CSRF defenses) need this to match their own origin.
headers['origin'] = upstream.origin;
@@ -646,6 +749,79 @@ try{
}catch(e){}})();</script>`;
}
/**
* Make a page's own RELATIVE `<base href>` absolute under the proxy prefix.
*
* A base element is resolved against the document's URL, and {@link runtimeUrlShim}
* deliberately rewrites that URL to strip the proxy prefix. So a page shipping
* `<base href="./">` — which is what a Vite build does, DeepSeek Harness among
* them — has its base re-resolved to Codeman's ROOT the moment the shim runs:
* every module script, stylesheet and `fetch('./api')` then asks the Codeman
* origin instead of the dashboard. The visible symptom is not an error page but
* a blank one: the markup and inline `<style>` paint (dsh paints a dark
* `#151517`), the module 404s, and nothing else ever renders.
*
* Resolving it here, while the prefix is still known, keeps the author's target
* (the document as it existed before masking) and is idempotent: an
* already-absolute path resolves to itself. Cross-origin bases are the author
* pointing at a CDN and are left exactly as written.
*
* The document path matters: a base in `/webview/<cap>/app/page.html` is
* relative to `/webview/<cap>/app/`, not to the proxy root, or a page served
* from a subdirectory would resolve its assets one level too high.
*
* @param html - document with attributes already rebased.
* @param prefix - proxy prefix the document was served from.
* @param documentPath - upstream path of the document, without the leading slash.
* @returns the document with a relative base href made absolute.
*/
function rebaseRelativeBase(html: string, prefix: string, documentPath: string): string {
const documentUrl = `http://codeman.invalid${prefix}${documentPath.replace(/^\/+/, '')}`;
return html.replace(
/(<base\b[^>]*?\bhref\s*=\s*)(["'])([^"']*)\2/i,
(match: string, head: string, quote: string, href: string) => {
let resolved: URL;
try {
// A stand-in origin: only the path is kept, and a different origin here
// is exactly the "absolute base" case this must not touch.
resolved = new URL(href, documentUrl);
} catch {
return match;
}
if (resolved.origin !== 'http://codeman.invalid') return match;
return `${head}${quote}${resolved.pathname}${resolved.search}${resolved.hash}${quote}`;
}
);
}
/**
* Rewrite root-absolute specifiers of dynamic `import()` calls in `<script>`
* bodies.
*
* A dynamic import is the one URL no other layer can reach: it is not an
* attribute, so `<base>` does not apply to it; it is not `fetch()`, so the runtime
* shim cannot rewrite it; and the browser resolves it against the ORIGIN root, not
* the document. SvelteKit's inline bootstrap is exactly this shape
* (`import("/_app/…")`), and the failure mode is silent: the module 404s against
* Codeman and the app's own loading spinner never resolves.
*
* ⚠️ Scoped to script bodies on purpose. Running the same regex over the whole
* document also rewrote visible text — `<pre>import("/x")</pre>` became a broken
* example — which is a rendering bug, not a loader the browser was going to run.
*
* @param html - document with attributes already rebased.
* @param prefix - proxy prefix to put in front of a `/`-rooted specifier.
*/
function rewriteScriptImports(html: string, prefix: string): string {
return html.replace(
/(<script\b[^>]*>)([^]*?)(<\/script>)/gi,
(_match: string, open: string, body: string, close: string) =>
open +
body.replace(/\bimport\s*\(\s*(["'])\/(?!\/)/g, (_import: string, quote: string) => `import(${quote}${prefix}`) +
close
);
}
/**
* Inject `<base href="/webview/<cap>/">` plus the runtime URL shim, and rebase
* root-absolute `src`/`href`/`action` attributes, which `<base>` alone does not
@@ -654,14 +830,27 @@ try{
* Three layers, because no single one is sufficient: `<base>` for parser-resolved
* relative URLs, attribute rewriting for root-absolute markup, and the shim for
* URLs built at runtime.
*
* @param html - the upstream document.
* @param capability - capability the document is being served under.
* @param basePath - reverse-proxy mount prefix (`''` at root).
* @param documentPath - upstream path of the document, without the leading slash.
* Used to resolve the page's own relative `<base>` against its directory.
*/
export function rewriteHtml(html: string, capability: string, basePath = ''): string {
export function rewriteHtml(html: string, capability: string, basePath = '', documentPath = ''): string {
const prefix = proxyPrefixFor(capability, basePath);
// Fresh regexes per call: module-level /g patterns carry `lastIndex` between calls.
const rebased = html
.replace(/(\s(?:src|href|action)\s*=\s*")\/(?!\/)/gi, `$1${prefix}`)
.replace(/(\s(?:src|href|action)\s*=\s*')\/(?!\/)/gi, `$1${prefix}`);
const rebased = rebaseRelativeBase(
rewriteScriptImports(
html
.replace(/(\s(?:src|href|action)\s*=\s*")\/(?!\/)/gi, `$1${prefix}`)
.replace(/(\s(?:src|href|action)\s*=\s*')\/(?!\/)/gi, `$1${prefix}`),
prefix
),
prefix,
documentPath
);
// A page that ships its own <base> keeps it (overriding it would break the
// author's intent), but it STILL needs the shim, which is the layer that
+3 -4
View File
@@ -40,6 +40,7 @@ import { join } from 'node:path';
import { watch as chokidarWatch, type FSWatcher as ChokidarWatcher } from 'chokidar';
import type { WorkflowRunInfo, WorkflowRunSummary, WorkflowAgentInfo, WorkflowRunPhase } from './types/workflow-run.js';
import { closeWatcherOnError } from './utils/close-watcher-on-error.js';
import { LRUMap } from './utils/lru-map.js';
import {
WORKFLOW_RUN_POLL_INTERVAL_MS,
@@ -865,10 +866,8 @@ export class WorkflowRunWatcher extends EventEmitter {
// subagents/workflows/ children are wf_<id>/ DIRS — catch their add/remove too.
watcher.on('addDir', handler);
watcher.on('unlinkDir', handler);
watcher.on('error', () => {
// chokidar surfaced an error for this dir — drop the watcher; poll still covers it.
this.removeDirWatcher(workflowsDir);
});
// chokidar surfaced an error for this dir — drop the watcher; poll still covers it.
closeWatcherOnError(watcher, () => this.dirWatchers.delete(workflowsDir));
this.dirWatchers.set(workflowsDir, watcher);
} catch {
// Watch setup failed — periodic poll still discovers changes.
+43
View File
@@ -244,6 +244,49 @@ describe('Auth Security', () => {
expect(wrongAfterRecovery.status).toBe(401);
});
it('should not count requests without credentials (restart with a tab open)', async () => {
// After a restart the open tab's background requests carry only a dead cookie.
for (let i = 0; i < AUTH_FAILURE_MAX * 3; i++) {
const res = await fetch(`${rateBaseUrl}/api/status`, {
headers: { Cookie: 'codeman_session=stale-from-before-restart' },
});
expect(res.status).toBe(401);
expect(res.headers.get('www-authenticate')).toBe('Basic realm="Codeman"');
}
// None of them were guesses: the wrong-password bucket is still empty.
await exhaustAuthFailures(rateBaseUrl, 'cod-no-creds');
});
it('should keep challenging requests without credentials during lockout', async () => {
await exhaustAuthFailures(rateBaseUrl, 'cod-challenge');
// A 429 never makes a browser show its login dialog; a 401 challenge does.
const res = await fetch(`${rateBaseUrl}/api/status`);
expect(res.status).toBe(401);
expect(res.headers.get('www-authenticate')).toBe('Basic realm="Codeman"');
const wrong = await fetch(`${rateBaseUrl}/api/status`, {
headers: { Authorization: basicAuthHeader(TEST_USER, 'still-wrong') },
});
expect(wrong.status).toBe(429);
});
it('should still count malformed authorization headers and rate-limit them', async () => {
// The other side of the line: a header that is present but not valid Basic
// is a failed login, counted like a wrong password.
for (let i = 0; i < AUTH_FAILURE_MAX; i++) {
const res = await fetch(`${rateBaseUrl}/api/status`, {
headers: { Authorization: 'Bearer x' },
});
expect(res.status, `request ${i + 1}`).toBe(401);
}
const res = await fetch(`${rateBaseUrl}/api/status`, {
headers: { Authorization: 'Bearer x' },
});
expect(res.status).toBe(429);
});
});
describe('Hook Event Endpoint', () => {
+217
View File
@@ -0,0 +1,217 @@
// test/cjk-hold-per-device-setting.test.ts
// Port: none (static analysis + vm, runs in CI, no browser/server).
//
// Send on Enter for the CJK input field (`cjkInputHoldUntilEnter`) is a
// PER-DEVICE setting like `cjkInputEnabled`: in settings-ui.js's displayKeys
// merge policy, stripped out of the object saveAppSettings() PUTs
// (SettingsUpdateSchema is .strict(), so sending it would 400 every save), and
// never declared in the schema. Plus the pieces around the mode: a held draft
// surviving a reload of the same session, the field staying one line tall with
// the keyboard down, and zh-CN strings for its placeholders.
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';
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('cjkInputHoldUntilEnter 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("'cjkInputHoldUntilEnter'");
});
it('is stripped out of the object saveAppSettings() PUTs to the server', () => {
expect(settingsUi).toContain('cjkInputHoldUntilEnter: _cjkHold,');
});
it('is never declared in the .strict() SettingsUpdateSchema', () => {
expect(schemas).not.toContain('cjkInputHoldUntilEnter');
});
it('defaults OFF on handhelds, next to cjkInputEnabled', () => {
expect(settingsUi).toMatch(/cjkInputEnabled: false,\s*cjkInputHoldUntilEnter: false,/);
});
it('is loaded into and saved from its App Settings switch', () => {
expect(read('index.html')).toContain('id="appSettingsCjkHoldUntilEnter"');
expect(settingsUi).toContain("document.getElementById('appSettingsCjkHoldUntilEnter').checked =");
expect(settingsUi).toContain(
"cjkInputHoldUntilEnter: document.getElementById('appSettingsCjkHoldUntilEnter').checked,"
);
});
});
describe('a held draft survives a reload of the same session', () => {
// The REAL _cleanupPreviousSession from app.js. selectSession() nulls
// activeSessionId before calling it on a same-session forceReload (tapping the
// tab already shown, the geometry retry), so it is told through keepCjkDraft.
function cleanup(hold: boolean, keepCjkDraft: boolean, outgoing: string | null = null) {
const clear = vi.fn();
const stashDraft = vi.fn();
const context = vm.createContext({
console,
setTimeout,
clearTimeout,
setInterval: vi.fn(),
clearInterval: vi.fn(),
requestAnimationFrame: vi.fn(),
HTMLCanvasElement: class HTMLCanvasElement {},
WebSocket: { OPEN: 1 },
fetch: vi.fn(),
URLSearchParams,
document: { addEventListener: vi.fn(), documentElement: { dataset: {} }, getElementById: () => null },
localStorage: { length: 0, key: vi.fn(), getItem: vi.fn(), setItem: vi.fn(), removeItem: vi.fn() },
window: { addEventListener: vi.fn(), removeEventListener: vi.fn() },
MobileDetection: { isTouchDevice: () => true, isHandheldDevice: () => true, getDeviceType: () => 'mobile' },
CjkInput: { holdUntilEnter: hold, clear, stashDraft },
});
vm.runInContext(`${read('constants.js')}\n${read('app.js')}\nglobalThis.__CodemanApp = CodemanApp;`, context);
const CodemanApp = (context as unknown as { __CodemanApp: { prototype: object } }).__CodemanApp;
const app = Object.create(CodemanApp.prototype) as Record<string, unknown> & {
_cleanupPreviousSession(id: string, opts?: { keepCjkDraft?: boolean }): void;
};
app.activeSessionId = outgoing;
app.sessions = new Map();
app._clearTimer = vi.fn();
app._disconnectWs = vi.fn();
app._xtermSnapshots = new Map();
app.pendingWrites = [];
app._cleanupPreviousSession('s1', { keepCjkDraft });
return Object.assign(clear, { stashDraft });
}
it('keeps the draft on a same-session reload in Send on Enter mode', () => {
expect(cleanup(true, true)).not.toHaveBeenCalled();
});
it('still clears on a real switch', () => {
expect(cleanup(true, false)).toHaveBeenCalled();
});
it('still clears in live mode, where a pending flush could fire mid-reconnect', () => {
expect(cleanup(false, true)).toHaveBeenCalled();
});
it('stashes the held draft of the session being left before clearing', () => {
const clear = cleanup(true, false, 's0');
expect(clear.stashDraft).toHaveBeenCalledWith('s0');
expect(clear.stashDraft.mock.invocationCallOrder[0]).toBeLessThan(clear.mock.invocationCallOrder[0]);
});
it('selectSession restores the draft of the session it lands on', () => {
// After _activateFileBrowserSession: test/file-browser-search.test.ts pins
// that call as the line right after the activeSessionId assignment.
expect(read('app.js')).toContain(
"this.activeSessionId = sessionId;\n this._activateFileBrowserSession?.(sessionId);\n if (typeof CjkInput !== 'undefined') CjkInput.restoreDraft?.(sessionId);"
);
});
it('leaving the tile grid for another session stashes the focused tile draft', () => {
// selectSession nulls activeSessionId there, which hides the tile from
// _cleanupPreviousSession.
expect(read('app.js')).toMatch(
/CjkInput\.stashDraft\?\.\(this\.activeSessionId\);\n(?:\s*\/\/.*\n)*\s*this\.activeSessionId = null;/
);
});
it('tile focus does not stash again for a tile closed from this tab', () => {
// removeSession discards the closed session's draft first; a stash after
// that would keep it in the map until the page reloads.
expect(read('tile-grid.js')).toContain(
'if (this.sessions?.has(this.activeSessionId)) CjkInput.stashDraft?.(this.activeSessionId);'
);
});
it('tile focus stashes the draft of the tile left and restores the focused one', () => {
const tiles = read('tile-grid.js');
const start = tiles.indexOf(' _selectTiledSession(sessionId, options = {}) {');
const body = tiles.slice(start, tiles.indexOf('grid.focusedId = sessionId;', start));
expect(body).toMatch(
/CjkInput\.stashDraft\?\.\(this\.activeSessionId\);\s*CjkInput\.clear\(\);\s*\}\s*CjkInput\.restoreDraft\?\.\(sessionId\);\s*\}\s*this\.activeSessionId = sessionId;/
);
});
it('going Home stashes the draft of the session it leaves', () => {
const appJs = read('app.js');
const start = appJs.indexOf(' goHome() {');
const body = appJs.slice(start, appJs.indexOf('this.activeSessionId = null;', start));
expect(body).toContain('CjkInput.stashDraft?.(this.activeSessionId);');
});
it('a removed session drops its stashed draft', () => {
expect(read('app.js')).toMatch(
/discardComposerDraft\?\.\(sessionId\);\n\s*if \(typeof CjkInput !== 'undefined'\) CjkInput\.discardDraft\?\.\(sessionId\);/
);
});
it('selectSession passes the same-session flag it captured before nulling activeSessionId', () => {
const appJs = read('app.js');
expect(appJs).toMatch(
/if \(this\.activeSessionId === sessionId && forceReload\) \{\s*reloadingSameSession = true;/
);
expect(appJs).toContain('this._cleanupPreviousSession(sessionId, { keepCjkDraft: reloadingSameSession });');
// Nothing in the same-session reload block may clear the field ahead of
// that flag: a CjkInput.clear() there wipes the held draft keepCjkDraft keeps.
const start = appJs.indexOf('if (this.activeSessionId === sessionId && forceReload) {');
const block = appJs.slice(start, appJs.indexOf('this.activeSessionId = null;', start));
expect(block).not.toContain('CjkInput.clear');
});
});
describe('Send on Enter field layout and strings', () => {
it('keeps the field one line tall while the keyboard is down', () => {
// .main reserves a fixed 84px there; a grown field would cover the terminal.
expect(read('styles.css')).toMatch(
/\.touch-device:not\(\.keyboard-visible\) #cjkInput\.cjk-input-visible \{\s*max-height: 34px;\s*\}/
);
});
it('caps the field on every device, not only in the .touch-device rule', () => {
// The setting is not limited to phones; on desktop an uncapped field grew to
// 502px at 25 lines and resized the PTY on every step.
const css = read('styles.css');
const base = css.slice(css.indexOf('#cjkInput {'), css.indexOf('}', css.indexOf('#cjkInput {')));
expect(base).toContain('max-height: 68px;');
expect(base).toContain('overflow-y: auto;');
});
it('the phone toolbar Enter presses Enter in the visible CJK field, not a bare terminal Enter', () => {
// onData drops everything while cjkActive, so the xterm path does nothing.
// The real sendEnterKey from session-ui.js, run with and without the field.
for (const visible of [true, false]) {
const submit = vi.fn();
const field = { classList: { contains: (name: string) => visible && name === 'cjk-input-visible' } };
const context = vm.createContext({
CodemanApp: function CodemanApp() {},
CjkInput: { submit },
document: { getElementById: (id: string) => (id === 'cjkInput' ? field : null) },
});
vm.runInContext(`${read('session-ui.js')}\nglobalThis.__mixin = CodemanApp.prototype;`, context);
const mixin = (context as unknown as { __mixin: { sendEnterKey(this: object): void } }).__mixin;
const submitFromToolbar = vi.fn();
mixin.sendEnterKey.call({ submitFromToolbar });
expect(submit).toHaveBeenCalledTimes(visible ? 1 : 0);
expect(submitFromToolbar).toHaveBeenCalledTimes(visible ? 0 : 1);
}
});
it('has zh-CN strings for both field placeholders', () => {
const i18n = read('i18n.js');
const cjk = read('input-cjk.js');
for (const placeholder of [
'CJK input (Enter = send, Esc = clear)',
'Type, Enter to send (Shift+Enter: new line, Esc: clear)',
]) {
expect(cjk).toContain(`'${placeholder}'`);
expect(i18n.split(`'${placeholder}':`).length - 1).toBe(1);
}
});
});
+1 -1
View File
@@ -172,7 +172,7 @@ describe('registered arguments', () => {
['attach', ['path']],
['start', []],
// Optional: bare `codeman tui` opens the dashboard.
['tui', ['n']],
['tui', ['session']],
])('declares the operands of `%s`', (name, expected) => {
const args = find(program, name)!.registeredArguments.map((arg) => arg.name());
expect(args).toEqual(expected);
@@ -435,7 +435,6 @@ describe('declared-for-later fields', () => {
const DECLARED_FOR_LATER = [
'accent',
'capabilities.echo',
'capabilities.wheelForward',
'capabilities.keyboardAccessory',
'capabilities.maxFrameBytes',
// The Docker credential-seeding path still reads its own CRED_STORES table: this shape
+25 -13
View File
@@ -40,6 +40,16 @@ let untrustedWorkdir: string;
let sessionId: string;
const createdSessions: string[] = [];
/** The transport edge the recorders wrap: every typed producer reaches it through the session FIFO. */
type ReliableSend = (sid: string, data: string, opts?: unknown) => void;
interface RecorderWindow {
app: { _enqueueReliableInput: ReliableSend };
__dbg: Array<[string, string]>;
__trace: string[];
__origSend?: ReliableSend;
__origSend2?: ReliableSend;
}
function hasCodex(): boolean {
try {
execSync(`PATH="${CODEX_BIN_DIR}:$PATH" codex --version`, { stdio: 'pipe' });
@@ -324,12 +334,13 @@ d('codex predictive echo E2E (real codex TUI)', () => {
await resetComposer();
const pidBefore = execSync(`${TMUX} list-panes -a -F '#{pane_id} #{pane_pid}'`, { encoding: 'utf8' }).trim();
await page.evaluate(() => {
const app = (window as any).app;
(window as any).__dbg = [];
if (!(window as any).__origSend2) (window as any).__origSend2 = app._sendInputAsync.bind(app);
app._sendInputAsync = (sid: string, data: string, opts?: unknown) => {
(window as any).__dbg.push([sid.slice(0, 8), JSON.stringify(data)]);
return (window as any).__origSend2(sid, data, opts);
const w = window as unknown as RecorderWindow;
const app = w.app;
w.__dbg = [];
const original = (w.__origSend2 ??= app._enqueueReliableInput.bind(app));
app._enqueueReliableInput = (sid, data, opts) => {
w.__dbg.push([sid.slice(0, 8), JSON.stringify(data)]);
return original(sid, data, opts);
};
});
await page.keyboard.type('abc', { delay: 30 });
@@ -471,15 +482,16 @@ d('codex predictive echo E2E (real codex TUI)', () => {
const record = () =>
page.evaluate(() => {
const app = (window as any).app;
(window as any).__trace = [];
if (!(window as any).__origSend) (window as any).__origSend = app._sendInputAsync.bind(app);
app._sendInputAsync = (sid: string, data: string, opts?: unknown) => {
(window as any).__trace.push(data);
return (window as any).__origSend(sid, data, opts);
const w = window as unknown as RecorderWindow;
const app = w.app;
w.__trace = [];
const original = (w.__origSend ??= app._enqueueReliableInput.bind(app));
app._enqueueReliableInput = (sid, data, opts) => {
w.__trace.push(data);
return original(sid, data, opts);
};
});
const trace = () => page.evaluate(() => ((window as any).__trace as string[]).join(''));
const trace = () => page.evaluate(() => (window as unknown as RecorderWindow).__trace.join(''));
await record();
await script();
+77
View File
@@ -0,0 +1,77 @@
/**
* @fileoverview The header CPU reading's meter: busy time over all cores between readings, the minimum window
* that keeps several browsers from shrinking it, and the fallback when no usable core times exist.
*/
import { describe, expect, it } from 'vitest';
import { createCpuUsageMeter } from '../src/cpu-usage.js';
const core = (busy: number, idle: number) => ({ times: { user: busy, nice: 0, sys: 0, idle, irq: 0 } });
function meterOver(samples: ReturnType<typeof core>[][], fallback = () => 999) {
let at = 0;
let index = 0;
const meter = createCpuUsageMeter(
() => samples[Math.min(index, samples.length - 1)],
() => at,
fallback
);
return (ms: number) => {
at += ms;
index += 1;
return meter();
};
}
describe('createCpuUsageMeter', () => {
it('reports busy time over all cores between readings', () => {
const next = meterOver([
[core(0, 0), core(0, 0)],
[core(50, 50), core(50, 50)],
[core(150, 50), core(50, 150)],
]);
expect(next(2000)).toBe(50);
expect(next(2000)).toBe(50);
});
it('counts nice, system and interrupt time as busy', () => {
const times = (user: number, nice: number, sys: number, irq: number, idle: number) => ({
times: { user, nice, sys, idle, irq },
});
const meter = createCpuUsageMeter(
(() => {
let calls = 0;
return () => [calls++ === 0 ? times(0, 0, 0, 0, 0) : times(10, 20, 30, 15, 25)];
})(),
(() => {
let at = 0;
return () => (at += 2000);
})(),
() => 999
);
expect(meter()).toBe(75);
});
it('reads idle cores as idle however long the run queue is', () => {
expect(meterOver([[core(0, 0)], [core(40, 60)]])(5000)).toBe(40);
});
it('reuses the last value for readings under a second apart and keeps the baseline', () => {
const next = meterOver([[core(0, 0)], [core(30, 70)], [core(30, 170)], [core(130, 170)]]);
expect(next(2000)).toBe(30);
expect(next(200)).toBe(30);
expect(next(2000)).toBe(50);
});
it('falls back without a bogus reading when there are no core times or the counters go backwards', () => {
expect(meterOver([[], []], () => 7)(2000)).toBe(7);
const next = meterOver([[core(100, 100)], [core(10, 10)], [core(60, 60)]], () => 7);
expect(next(2000)).toBe(7);
expect(next(2000)).toBe(50);
});
it('answers a whole number from 0 to 100', () => {
expect(meterOver([[core(0, 0)], [core(2, 1)]])(2000)).toBe(67);
expect(meterOver([[core(0, 0)], [core(0, 9)]])(2000)).toBe(0);
expect(meterOver([[core(0, 0)], [core(9, 0)]])(2000)).toBe(100);
});
});
+362 -2
View File
@@ -12,10 +12,25 @@
* 2. The supervisor tracks at most ONE server. The status accessor is what every
* caller reads to decide whether to start another, so "no server" must report
* as absent rather than as a half-populated record.
* 3. `dsh web` now gates its index behind a launch token it prints on boot. The
* supervisor is the only party that can trade it, and the cookie it produces
* is authority-bound: getting that wrong is a blank tab, not a visible error.
*/
import { describe, expect, it, beforeEach } from 'vitest';
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import http from 'node:http';
import { DeepSeekWebStartSchema } from '../src/web/schemas.js';
import { getDeepSeekWebStatus, resetDeepSeekWebForTest, stopDeepSeekWeb } from '../src/deepseek-web-server.js';
import {
getDeepSeekWebCookie,
getDeepSeekWebStatus,
launchUrlTargetsServer,
parseLaunchUrl,
resetDeepSeekWebForTest,
startDeepSeekWeb,
stopDeepSeekWeb,
} from '../src/deepseek-web-server.js';
describe('DeepSeekWebStartSchema: the authority reaching --trusted-host', () => {
it('accepts the authority shapes a browser can actually report', () => {
@@ -71,3 +86,348 @@ describe('DeepSeek web supervisor: status', () => {
expect(getDeepSeekWebStatus().running).toBe(false);
});
});
describe('parseLaunchUrl: the one-time token dsh prints on boot', () => {
it('pulls the URL out of the banner a real boot writes', () => {
const output = ['dsh web: http://127.0.0.1:3080/?token=0Yb3sJk9Qm2xLd7Tf1Vc', 'ready'].join('\n');
expect(parseLaunchUrl(output)).toBe('http://127.0.0.1:3080/?token=0Yb3sJk9Qm2xLd7Tf1Vc');
});
it('sees through SGR colouring, which would otherwise hide the token', () => {
const output = '\u001b[36mdsh web:\u001b[0m \u001b[4mhttp://127.0.0.1:3080/?token=abc123\u001b[0m\n';
expect(parseLaunchUrl(output)).toBe('http://127.0.0.1:3080/?token=abc123');
});
// dsh prints diagnostics under the same prefix before the banner. Taking the
// FIRST match made the real URL invisible and boot gave up 4 seconds later.
it('skips a diagnostic line and keeps scanning for the URL', () => {
expect(parseLaunchUrl('dsh web: loading profiles\ndsh web: http://127.0.0.1:3080/?token=abc\n')).toBe(
'http://127.0.0.1:3080/?token=abc'
);
});
it('skips a URL without a token and keeps scanning for the token one', () => {
expect(parseLaunchUrl('dsh web: http://127.0.0.1:3080/\ndsh web: http://127.0.0.1:3080/?token=abc\n')).toBe(
'http://127.0.0.1:3080/?token=abc'
);
});
it('returns null for a token-less banner, which is the older dsh', () => {
expect(parseLaunchUrl('dsh web: http://127.0.0.1:3080/\n')).toBeNull();
});
it('refuses anything that is not an http(s) URL carrying a token', () => {
expect(parseLaunchUrl('')).toBeNull();
expect(parseLaunchUrl('booting...')).toBeNull();
expect(parseLaunchUrl('dsh web: javascript:alert(1)?token=x')).toBeNull();
expect(parseLaunchUrl('dsh web: not a url?token=x')).toBeNull();
});
});
describe('launchUrlTargetsServer: the exchange must hit the spawned port', () => {
it('accepts only 127.0.0.1 on the port that was just spawned', () => {
expect(launchUrlTargetsServer('http://127.0.0.1:3080/?token=x', 3080)).toBe(true);
expect(launchUrlTargetsServer('http://127.0.0.1:3081/?token=x', 3080)).toBe(false);
expect(launchUrlTargetsServer('http://localhost:3080/?token=x', 3080)).toBe(false);
expect(launchUrlTargetsServer('http://evil.example:3080/?token=x', 3080)).toBe(false);
expect(launchUrlTargetsServer('not a url', 3080)).toBe(false);
});
});
describe('DeepSeek web supervisor: the launch-token cookie', () => {
let dir: string;
beforeEach(() => {
resetDeepSeekWebForTest();
dir = mkdtempSync(join(tmpdir(), 'codeman-dsh-web-'));
});
afterEach(async () => {
await stopDeepSeekWeb();
rmSync(dir, { recursive: true, force: true });
});
/**
* A stand-in for `dsh web` with the browser-auth gate: prints the banner,
* refuses `/` without a cookie, and trades the token for one 303.
*/
const FAKE_DSH = `#!/usr/bin/env node
const http = require('node:http');
const portArg = process.argv.indexOf('--port');
const port = Number(process.argv[portArg + 1]);
const token = 'test-launch-token';
const cookie = 'dsh-auth-test=v1.payload.sig';
process.stdout.write('dsh web: http://127.0.0.1:' + port + '/?token=' + token + '\\n');
http
.createServer((req, res) => {
const url = new URL(req.url, 'http://127.0.0.1:' + port);
if (url.pathname === '/' && url.searchParams.get('token') === token) {
res.writeHead(303, { location: './', 'set-cookie': cookie + '; Path=/; HttpOnly' });
res.end();
return;
}
if (req.headers.cookie === cookie) {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
res.end('<!doctype html><title>harness</title>');
return;
}
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1');
`;
it('trades the boot token for the cookie, scoped to its own port', async () => {
writeFileSync(join(dir, 'dsh'), FAKE_DSH, { mode: 0o755 });
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
// Before the exchange this page is exactly the blank tab being fixed: 401.
expect((await fetch(`http://127.0.0.1:${result.port}/`)).status).toBe(401);
expect(getDeepSeekWebCookie(result.port)).toBe('dsh-auth-test=v1.payload.sig');
// A credential minted for this authority must never travel to another port.
expect(getDeepSeekWebCookie(result.port + 1)).toBeNull();
const authed = await fetch(`http://127.0.0.1:${result.port}/`, {
headers: { cookie: getDeepSeekWebCookie(result.port) as string },
});
expect(authed.status).toBe(200);
}, 20_000);
// `managed` is a client-supplied field and the port is published by
// GET /api/deepseek/web, so the supervisor additionally binds the cookie to the
// identity whose request started the process: another user's tab must not be
// handed it, and their POST must not reuse bob's server either.
it('hands the cookie only to the identity that started the server', async () => {
writeFileSync(join(dir, 'dsh'), FAKE_DSH, { mode: 0o755 });
const bob = await startDeepSeekWeb(dir, 'localhost:3000', 'bob');
expect(bob.ok).toBe(true);
if (!bob.ok) return;
expect(getDeepSeekWebCookie(bob.port, 'bob')).toBe('dsh-auth-test=v1.payload.sig');
expect(getDeepSeekWebCookie(bob.port)).toBeNull();
expect(getDeepSeekWebCookie(bob.port, 'alice')).toBeNull();
// A different owner restarts rather than reusing bob's cookie.
const alice = await startDeepSeekWeb(dir, 'localhost:3000', 'alice');
expect(alice.ok).toBe(true);
if (!alice.ok) return;
expect(alice.reused).toBe(false);
expect(getDeepSeekWebCookie(alice.port, 'alice')).toBe('dsh-auth-test=v1.payload.sig');
expect(getDeepSeekWebCookie(alice.port, 'bob')).toBeNull();
}, 20_000);
// A failed exchange leaves a server that answers 401 to everything. Reuse used
// to hand that same server back on every POST, so the restart the warning asks
// for could never happen. The next start request must perform it.
it('restarts rather than reusing a server whose exchange failed', async () => {
writeFileSync(
join(dir, 'dsh'),
`#!/usr/bin/env node
const fs = require('node:fs');
const http = require('node:http');
const path = require('node:path');
const port = Number(process.argv[process.argv.indexOf('--port') + 1]);
const token = 'retry-token';
const cookie = 'dsh-auth-retry=v1.sig';
const marker = path.join(__dirname, '.exchange-failed');
const failedBefore = fs.existsSync(marker);
if (!failedBefore) fs.writeFileSync(marker, '1');
process.stdout.write('dsh web: http://127.0.0.1:' + port + '/?token=' + token + '\\n');
http
.createServer((req, res) => {
const url = new URL(req.url, 'http://127.0.0.1:' + port);
if (url.searchParams.get('token') === token) {
if (!failedBefore) {
res.writeHead(500, { 'content-type': 'text/plain' });
res.end('temporary failure');
return;
}
res.writeHead(303, { location: './', 'set-cookie': cookie + '; Path=/' });
res.end();
return;
}
if (req.headers.cookie === cookie) {
res.writeHead(200, { 'content-type': 'text/html' });
res.end('<html>ok</html>');
return;
}
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1');
`,
{ mode: 0o755 }
);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
const first = await startDeepSeekWeb(dir, 'localhost:3000');
expect(first.ok).toBe(true);
if (!first.ok) return;
expect(getDeepSeekWebCookie(first.port)).toBeNull();
expect(warn).toHaveBeenCalledWith(expect.stringContaining('could not be exchanged'));
} finally {
warn.mockRestore();
}
const second = await startDeepSeekWeb(dir, 'localhost:3000');
expect(second.ok).toBe(true);
if (!second.ok) return;
expect(second.reused).toBe(false);
expect(getDeepSeekWebCookie(second.port)).toBe('dsh-auth-retry=v1.sig');
// The recovered server is healthy again, so ordinary reuse resumes.
const third = await startDeepSeekWeb(dir, 'localhost:3000');
expect(third.ok).toBe(true);
if (!third.ok) return;
expect(third.reused).toBe(true);
}, 20_000);
// The exchange is a request made by the SERVER. A banner naming another local
// port would let captured child output aim it, so the URL is judged before it
// is fetched at all.
it('does not fetch a banner naming another port', async () => {
const hits: string[] = [];
const target = http.createServer((req, res) => {
hits.push(req.url ?? '');
res.writeHead(200, { 'content-type': 'text/plain' });
res.end('should never be reached');
});
await new Promise<void>((resolve) => target.listen(0, '127.0.0.1', resolve));
const address = target.address();
if (!address || typeof address === 'string') throw new Error('target has no address');
try {
writeFileSync(
join(dir, 'dsh'),
`#!/usr/bin/env node
const http = require('node:http');
const port = Number(process.argv[process.argv.indexOf('--port') + 1]);
process.stdout.write('dsh web: http://127.0.0.1:${address.port}/?token=stolen\\n');
http
.createServer((_req, res) => {
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1');
`,
{ mode: 0o755 }
);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(getDeepSeekWebCookie(result.port)).toBeNull();
expect(warn).toHaveBeenCalledWith(expect.stringContaining('not fetching it'));
} finally {
warn.mockRestore();
}
expect(hits).toEqual([]);
} finally {
await new Promise<void>((resolve) => target.close(() => resolve()));
}
}, 20_000);
it('leaves the old, ungated dsh working: no token means no cookie, not a failure', async () => {
writeFileSync(
join(dir, 'dsh'),
'#!/usr/bin/env node\nconst http = require("node:http");\nconst port = Number(process.argv[process.argv.indexOf("--port") + 1]);\nprocess.stdout.write("dsh web: http://127.0.0.1:" + port + "/\\n");\nhttp.createServer((_q, s) => s.end("ok")).listen(port, "127.0.0.1");\n',
{ mode: 0o755 }
);
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(getDeepSeekWebCookie(result.port)).toBeNull();
}, 20_000);
// The error-tail buffer is capped at 16 KB, and a chatty plugin tree can fill
// it before dsh prints its banner. Scanning that buffer alone lost the token
// and put the tab back on the 401 page, so the banner is matched on its own
// (larger) budget.
// The banner can arrive in two stdout writes: `capture()` sees two chunks and
// neither is a complete line. Scanning the raw buffer either missed it or, with
// a partial URL that happened to parse, exchanged a truncated token.
it('waits for a banner split across two output chunks', async () => {
writeFileSync(
join(dir, 'dsh'),
`#!/usr/bin/env node
const http = require('node:http');
const port = Number(process.argv[process.argv.indexOf('--port') + 1]);
const token = 'split-token';
const cookie = 'dsh-auth-split=v1.sig';
process.stdout.write('dsh web: loading profiles\\n');
http
.createServer((req, res) => {
const url = new URL(req.url, 'http://127.0.0.1:' + port);
if (url.searchParams.get('token') === token) {
res.writeHead(303, { location: './', 'set-cookie': cookie + '; Path=/' });
res.end();
return;
}
if (req.headers.cookie === cookie) {
res.writeHead(200, { 'content-type': 'text/html' });
res.end('<html>ok</html>');
return;
}
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1', () => {
const line = 'dsh web: http://127.0.0.1:' + port + '/?token=' + token + '\\n';
process.stdout.write(line.slice(0, 30));
setTimeout(() => process.stdout.write(line.slice(30)), 150);
});
`,
{ mode: 0o755 }
);
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(getDeepSeekWebCookie(result.port)).toBe('dsh-auth-split=v1.sig');
}, 20_000);
it('still finds a banner printed after more than the error-tail cap', async () => {
writeFileSync(
join(dir, 'dsh'),
`#!/usr/bin/env node
const http = require('node:http');
const port = Number(process.argv[process.argv.indexOf('--port') + 1]);
const token = 'late-banner-token';
const cookie = 'dsh-auth-late=v1.sig';
process.stdout.write('warn: plugin noise '.repeat(1100) + '\\n');
http
.createServer((req, res) => {
const url = new URL(req.url, 'http://127.0.0.1:' + port);
if (url.searchParams.get('token') === token) {
res.writeHead(303, { location: './', 'set-cookie': cookie + '; Path=/' });
res.end();
return;
}
if (req.headers.cookie === cookie) {
res.writeHead(200, { 'content-type': 'text/html' });
res.end('<html>ok</html>');
return;
}
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1');
setTimeout(() => process.stdout.write('dsh web: http://127.0.0.1:' + port + '/?token=' + token + '\\n'), 300);
`,
{ mode: 0o755 }
);
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(getDeepSeekWebCookie(result.port)).toBe('dsh-auth-late=v1.sig');
}, 20_000);
});
+68
View File
@@ -0,0 +1,68 @@
/**
* @fileoverview The Mac app's host shim refuses `document.execCommand('paste')`.
*
* Codeman's Cmd+V handler (`_handleImagePaste`, src/web/public/image-input.js)
* calls `document.execCommand('paste')` on its hidden paste trap. In a
* WKWebView WebKit answers that call with its "Paste" access menu and holds the
* page until it is picked, so the key's own paste, which carries a copied
* image, never reached the trap. The shim the app injects into every server
* page (`HOST_SHIM`, packages/desktop/src/assets.rs) answers the command with
* false, as Chromium does, and leaves every other command to WebKit.
*
* Runs the shim's real text, cut out of assets.rs, in a vm with a stub
* Document, so a change to the Rust string is what these tests see.
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { describe, expect, it, vi } from 'vitest';
const assetsRs = readFileSync(resolve(import.meta.dirname, '../packages/desktop/src/assets.rs'), 'utf8');
const shim = /pub const HOST_SHIM: &str = r#"([\s\S]*?)"#;/.exec(assetsRs)?.[1];
function load(protocol = 'https:') {
if (!shim) throw new Error('HOST_SHIM not found in assets.rs');
const nativeExec = vi.fn(function (this: unknown) {
return true;
});
function Document() {}
Document.prototype.execCommand = nativeExec;
const document = Object.create(Document.prototype) as { execCommand: (...args: unknown[]) => boolean };
const sandbox: Record<string, unknown> = {
Document,
document,
URL,
location: { protocol, href: `${protocol}//atlas.example/`, origin: `${protocol}//atlas.example` },
addEventListener: vi.fn(),
open: vi.fn(),
fetch: vi.fn(),
ipc: { postMessage: vi.fn() },
};
sandbox.window = sandbox;
vm.runInNewContext(shim, sandbox);
return { document, nativeExec, sandbox };
}
describe('desktop host shim: execCommand paste', () => {
it('answers paste with false and never asks WebKit', () => {
const { document, nativeExec } = load();
expect(document.execCommand('paste')).toBe(false);
expect(document.execCommand('Paste')).toBe(false);
expect(nativeExec).not.toHaveBeenCalled();
});
it('hands every other command to WebKit with its arguments and document', () => {
const { document, nativeExec } = load();
expect(document.execCommand('copy')).toBe(true);
expect(document.execCommand('insertText', false, 'hi')).toBe(true);
expect(nativeExec).toHaveBeenNthCalledWith(1, 'copy');
expect(nativeExec).toHaveBeenNthCalledWith(2, 'insertText', false, 'hi');
expect(nativeExec.mock.contexts[0]).toBe(document);
});
it('leaves a page that is not http(s) alone', () => {
const { document, nativeExec } = load('file:');
expect(document.execCommand('paste')).toBe(true);
expect(nativeExec).toHaveBeenCalledWith('paste');
});
});
+274
View File
@@ -0,0 +1,274 @@
/**
* @fileoverview Real-Chromium coverage for where a dialog hands the keyboard
* back to (`FocusTrap.focusToReturn`, keyboard-accessory.js).
*
* What the vm test in `test/dialog-focus-return.test.ts` cannot answer is the
* order a browser does things in: the rule reads `document.activeElement` in a
* `pointerdown` listener and relies on the engine moving focus only afterwards,
* as the default action of `mousedown`. Here a real mouse presses real controls
* and a real keyboard types, on a page that holds the shipping
* keyboard-accessory.js, a textarea standing in for the terminal's own, and a
* dialog built on `FocusTrap` the way App Settings and Session Options are.
*
* Four ways into the dialog: a button (Chromium gives it focus on a press), an
* element that cannot take focus (the press clears focus to `<body>`, which is
* what WebKit on macOS does for a button), a focusable element pressed on an
* icon inside it (a tab's gear), and an item of a menu opened by a press before
* it (a tile's menu button, then "Session options").
*
* Port: none (page.route on a fake origin, no server).
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
import { chromium, type Browser, type BrowserContext, type Page } from 'playwright';
const publicDir = resolve(import.meta.dirname, '../src/web/public');
const ORIGIN = 'http://codeman.test/';
const PAGE = `<!doctype html><html><body>
<textarea id="term" style="display:block;width:300px;height:80px"></textarea>
<button id="other">Other</button>
<button id="open">Open</button>
<div id="plain" style="display:inline-block;padding:8px;background:#ccc">Open, takes no focus</div>
<span id="gear" tabindex="0" style="display:inline-block;padding:8px">
<svg width="24" height="24"><rect id="gearIcon" width="24" height="24"></rect></svg>
</span>
<button id="menuButton">Menu</button>
<div id="modal" hidden style="position:fixed;left:40px;top:160px;padding:20px;background:#eee">
<button id="close">Close</button><input id="name">
</div>
</body></html>`;
const WIRING = `
const modal = document.getElementById('modal');
const focused = () => (document.activeElement === document.body ? 'body' : document.activeElement.id);
window.__focused = focused;
window.__focusAtClick = [];
let trap = null;
const open = () => {
window.__focusAtClick.push(focused());
modal.hidden = false;
trap = new FocusTrap(modal);
trap.activate();
};
const close = () => {
if (!trap) return;
modal.hidden = true;
trap.deactivate();
trap = null;
};
for (const id of ['open', 'plain', 'gear']) document.getElementById(id).addEventListener('click', open);
document.getElementById('close').addEventListener('click', close);
// A menu the way the rail's row menu is built: appended to <body>, its first
// item focused, removed by the item's click before the action runs.
document.getElementById('menuButton').addEventListener('click', () => {
const menu = document.createElement('div');
menu.id = 'menu';
menu.setAttribute('role', 'menu');
menu.style.cssText = 'position:fixed;left:400px;top:160px;padding:8px;background:#ddd';
for (const [id, action] of [['menuFirst', () => {}], ['menuOptions', open]]) {
const item = document.createElement('button');
item.id = id;
item.setAttribute('role', 'menuitem');
item.textContent = id;
item.addEventListener('click', () => {
menu.remove();
action();
});
menu.appendChild(item);
}
document.body.appendChild(menu);
menu.querySelector('button').focus();
});
document.addEventListener('keydown', (e) => { if (e.key === 'Escape') close(); }, true);
`;
describe('where a dialog hands the keyboard back to, in Chromium', () => {
let browser: Browser;
const contexts: BrowserContext[] = [];
let page: Page;
const errors: string[] = [];
async function newPage(options: { hasTouch?: boolean } = {}): Promise<Page> {
const context = await browser.newContext({ viewport: { width: 800, height: 500 }, ...options });
contexts.push(context);
const p = await context.newPage();
p.on('pageerror', (e) => errors.push(e.message));
await p.route(ORIGIN, (route) => route.fulfill({ contentType: 'text/html', body: PAGE }));
await p.goto(ORIGIN);
await p.addScriptTag({ content: readFileSync(resolve(publicDir, 'keyboard-accessory.js'), 'utf8') });
await p.addScriptTag({ content: WIRING });
return p;
}
const focused = (p: Page = page) => p.evaluate(() => (window as any).__focused());
const focusAtClick = (p: Page = page) => p.evaluate(() => (window as any).__focusAtClick);
const termText = (p: Page = page) => p.evaluate(() => (document.getElementById('term') as HTMLTextAreaElement).value);
/** Put the keyboard in the terminal stand-in and type, as a user in the middle of a prompt. */
async function typeInTerminal(p: Page = page) {
await p.click('#term');
await p.keyboard.type('a');
expect(await focused(p)).toBe('term');
}
/** The trap moves focus to the dialog's first control one frame after it opens. */
async function dialogOpen(p: Page = page) {
await p.waitForFunction(() => (window as any).__focused() === 'close');
}
beforeAll(async () => {
browser = await chromium.launch({ headless: true });
});
beforeEach(async () => {
errors.length = 0;
page = await newPage();
});
afterAll(async () => {
for (const context of contexts) await context.close();
await browser?.close();
});
it('a button pressed with the mouse: the keyboard is back in the terminal', async () => {
await typeInTerminal();
await page.click('#open');
await dialogOpen();
// The engine fact the rule exists for: the press gave the button focus.
expect(await focusAtClick()).toEqual(['open']);
await page.keyboard.press('Escape');
expect(await focused()).toBe('term');
await page.keyboard.type('b');
expect(await termText()).toBe('ab');
expect(errors).toEqual([]);
});
it('a control that takes no focus (a button in WebKit on macOS): the keyboard is back in the terminal', async () => {
await typeInTerminal();
await page.click('#plain');
await dialogOpen();
// The press cleared focus: before the fix this is what the dialog handed back.
expect(await focusAtClick()).toEqual(['body']);
await page.keyboard.press('Escape');
expect(await focused()).toBe('term');
await page.keyboard.type('b');
expect(await termText()).toBe('ab');
});
it("a press on the icon inside a focusable control (a tab's gear): the keyboard is back in the terminal", async () => {
await typeInTerminal();
await page.click('#gearIcon');
await dialogOpen();
expect(await focusAtClick()).toEqual(['gear']);
await page.keyboard.press('Escape');
expect(await focused()).toBe('term');
await page.keyboard.type('b');
expect(await termText()).toBe('ab');
});
it("two presses through a menu (a tile's menu, then Session options): the keyboard is back in the terminal", async () => {
await typeInTerminal();
await page.click('#menuButton');
expect(await focused()).toBe('menuFirst');
await page.click('#menuOptions');
await dialogOpen();
// The item's click removed the menu, so nothing had focus when the dialog opened.
expect(await focusAtClick()).toEqual(['body']);
await page.keyboard.press('Escape');
expect(await focused()).toBe('term');
await page.keyboard.type('b');
expect(await termText()).toBe('ab');
});
it('a menu walked with the keyboard keeps the keyboard pattern', async () => {
await typeInTerminal();
await page.click('#menuButton');
await page.keyboard.press('Tab');
expect(await focused()).toBe('menuOptions');
await page.keyboard.press('Enter');
await dialogOpen();
await page.keyboard.press('Escape');
// Nothing was remembered: the dialog hands back what had focus, and that was nothing.
expect(await focused()).not.toBe('term');
});
it('closing the dialog with the mouse instead of Escape changes nothing', async () => {
await typeInTerminal();
await page.click('#open');
await dialogOpen();
await page.click('#close');
expect(await focused()).toBe('term');
await page.keyboard.type('b');
expect(await termText()).toBe('ab');
});
it('typing in the dialog and opening it a second time still ends in the terminal', async () => {
await typeInTerminal();
await page.click('#open');
await dialogOpen();
await page.click('#name');
await page.keyboard.type('x');
await page.keyboard.press('Escape');
expect(await focused()).toBe('term');
await page.click('#open');
await dialogOpen();
await page.keyboard.press('Escape');
expect(await focused()).toBe('term');
await page.keyboard.type('b');
expect(await termText()).toBe('ab');
});
it('a keyboard user gets the control back that opened the dialog', async () => {
await typeInTerminal();
await page.keyboard.press('Tab');
await page.keyboard.press('Tab');
expect(await focused()).toBe('open');
await page.keyboard.press('Enter');
await dialogOpen();
await page.keyboard.press('Escape');
expect(await focused()).toBe('open');
});
it('a keyboard user gets the control back even after pressing it with the mouse earlier', async () => {
await typeInTerminal();
await page.click('#open');
await dialogOpen();
await page.keyboard.press('Escape');
expect(await focused()).toBe('term');
await page.keyboard.press('Tab');
await page.keyboard.press('Tab');
await page.keyboard.press('Enter');
await dialogOpen();
await page.keyboard.press('Escape');
expect(await focused()).toBe('open');
});
it('a press that began on a button returns to the pressed control, as before', async () => {
await typeInTerminal();
await page.click('#other');
expect(await focused()).toBe('other');
await page.click('#open');
await dialogOpen();
await page.keyboard.press('Escape');
expect(await focused()).toBe('open');
});
it('a finger changes nothing: focus returns to what had it when the dialog opened', async () => {
const touch = await newPage({ hasTouch: true });
await touch.tap('#term');
expect(await focused(touch)).toBe('term');
await touch.tap('#open');
await dialogOpen(touch);
const atClick = (await focusAtClick(touch))[0];
await touch.keyboard.press('Escape');
expect(await focused(touch)).toBe(atClick);
});
});
+360
View File
@@ -0,0 +1,360 @@
/**
* @fileoverview A dialog hands the keyboard back to the field the user was
* typing in when the mouse press that opened it began.
*
* Measured in Chromium against a real shell session before the change: App
* Settings opened from the header gear and closed left `activeElement` on the
* gear button, Session Options opened from a tab's gear left it on that gear,
* and nothing typed afterwards reached the terminal. With the press clearing
* focus (what WebKit on macOS does for a button) it was left on `<body>`.
*
* `FocusTrap` is loaded with `vm` against a fake document, like the other
* accessory-bar tests. A press is the two steps a browser takes: `pointerdown`
* reaches the page first, then the engine moves focus. The real event order is
* covered in `test/dialog-focus-return.browser.test.ts`.
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { describe, expect, it, vi } from 'vitest';
type Listener = (e: unknown) => void;
type Node = Record<string, any>;
const read = (name: string) => readFileSync(resolve(import.meta.dirname, '../src/web/public', name), 'utf8');
function node(tagName: string, extra: Node = {}): Node {
return { tagName, isConnected: true, focus: vi.fn(), contains: () => false, ...extra };
}
function loadPage({ panels = false } = {}) {
const listeners: Record<string, Listener[]> = {};
const body = node('BODY');
let active: Node | null = body;
const document = {
body,
get activeElement() {
return active;
},
addEventListener: (type: string, fn: Listener, capture?: boolean) => {
(listeners[`${type}:${capture === true}`] ||= []).push(fn);
},
createElement: () => node('DIV'),
querySelector: () => null,
getElementById: () => null,
};
const CodemanApp = function CodemanApp(this: unknown) {};
const context = vm.createContext({
console,
document,
CodemanApp,
MobileDetection: { isTouchDevice: () => false },
localStorage: { getItem: () => null, setItem: () => {} },
requestAnimationFrame: (fn: () => void) => fn(),
});
vm.runInContext(`${read('keyboard-accessory.js')}\nglobalThis.__FocusTrap = FocusTrap;`, context, {
filename: 'keyboard-accessory.js',
});
if (panels) vm.runInContext(read('panels-ui.js'), context, { filename: 'panels-ui.js' });
const FocusTrap = (context as unknown as { __FocusTrap: any }).__FocusTrap;
const fire = (type: string, event: unknown) => (listeners[`${type}:true`] ?? []).forEach((fn) => fn(event));
return {
FocusTrap,
listeners,
body,
app: panels ? new (CodemanApp as any)() : null,
setActive: (el: Node | null) => (active = el),
/** A press: the page hears `pointerdown`, then the engine moves focus to `focusAfter`. */
press(target: Node, focusAfter?: Node | null, pointerType = 'mouse') {
fire('pointerdown', { pointerType, target });
if (focusAfter !== undefined) active = focusAfter;
},
key: (key: string) => fire('keydown', { key }),
};
}
describe('FocusTrap.focusToReturn', () => {
it('answers the typing field when the pressed control took focus (Chromium, Firefox)', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const gear = node('BUTTON');
page.setActive(terminal);
page.press(gear, gear);
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
});
it('answers the typing field when the press cleared focus (a button in WebKit on macOS)', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
page.setActive(terminal);
page.press(node('BUTTON'), page.body);
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
});
it('answers the typing field when the press landed inside the control that took focus', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const icon = node('path');
const gear = node('BUTTON', { contains: (el: Node) => el === icon });
page.setActive(terminal);
page.press(icon, gear);
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
});
it('keeps the control for a keyboard user: any key forgets the press', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const gear = node('BUTTON');
page.setActive(terminal);
page.press(gear, gear);
// Later the same control is reached with Tab and opened with Enter.
page.key('Tab');
expect(page.FocusTrap.focusToReturn()).toBe(gear);
});
it('does not let a modifier held for the click forget the press', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const gear = node('BUTTON');
page.setActive(terminal);
page.press(gear, gear);
for (const key of ['Shift', 'Control', 'Alt', 'Meta']) page.key(key);
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
});
it('returns to the pressed control when the press came from a button (a dialog opened inside a dialog)', () => {
const page = loadPage();
const closeButton = node('BUTTON');
const row = node('BUTTON');
page.setActive(closeButton);
page.press(row, row);
expect(page.FocusTrap.focusToReturn()).toBe(row);
});
it('never carries the field of an earlier press over', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const gear = node('BUTTON');
const row = node('BUTTON');
page.setActive(terminal);
page.press(gear, gear);
// A dialog is open now and the terminal is behind it; the next press starts from a button.
page.press(row, row);
expect(page.FocusTrap.focusToReturn()).toBe(row);
});
it('keeps the field through a menu: the press on a menu item belongs to the press that opened the menu', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const menuButton = node('BUTTON');
const firstItem = node('BUTTON');
const item = node('BUTTON', { closest: (selector: string) => (selector === '[role="menu"]' ? {} : null) });
page.setActive(terminal);
// The menu focuses its first item when it opens.
page.press(menuButton, firstItem);
// The item's click removes the menu, which drops focus on <body>, and opens the dialog.
page.press(item, page.body);
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
});
it('keeps nothing through a menu that was opened from a button', () => {
const page = loadPage();
const closeButton = node('BUTTON');
const menuButton = node('BUTTON');
const item = node('BUTTON', { closest: (selector: string) => (selector === '[role="menu"]' ? {} : null) });
page.setActive(closeButton);
page.press(menuButton, menuButton);
page.press(item, page.body);
expect(page.FocusTrap.focusToReturn()).toBe(page.body);
});
it('spends the press when a dialog asks, so nothing pressed inside the dialog reaches the field behind it', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const gear = node('BUTTON');
page.setActive(terminal);
page.press(gear, gear);
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
expect(page.FocusTrap.focusToReturn()).toBe(gear);
// The dialog is open. A menu item in it is pressed directly, with a dialog control focused.
const dialogControl = node('BUTTON');
const item = node('BUTTON', { closest: (selector: string) => (selector === '[role="menu"]' ? {} : null) });
page.setActive(dialogControl);
page.press(item, page.body);
expect(page.FocusTrap.focusToReturn()).toBe(page.body);
});
it('leaves a finger alone, and a finger forgets an earlier mouse press', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const gear = node('BUTTON');
page.setActive(terminal);
page.press(gear, gear, 'touch');
expect(page.FocusTrap.focusToReturn()).toBe(gear);
page.setActive(terminal);
page.press(gear, gear, 'mouse');
page.press(gear, gear, 'touch');
expect(page.FocusTrap.focusToReturn()).toBe(gear);
page.setActive(terminal);
page.press(gear, gear, 'pen');
expect(page.FocusTrap.focusToReturn()).toBe(gear);
});
it('answers what has focus when the field is gone from the page', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const gear = node('BUTTON');
page.setActive(terminal);
page.press(gear, gear);
terminal.isConnected = false;
expect(page.FocusTrap.focusToReturn()).toBe(gear);
});
it('answers what has focus when the click itself moved it somewhere else', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const elsewhere = node('BUTTON');
page.setActive(terminal);
page.press(node('BUTTON'), elsewhere);
expect(page.FocusTrap.focusToReturn()).toBe(elsewhere);
});
it('answers what has focus when there was no press at all', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
page.setActive(terminal);
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
page.setActive(page.body);
expect(page.FocusTrap.focusToReturn()).toBe(page.body);
});
it('answers the field itself when the press left focus in it', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
page.setActive(terminal);
// An accessory key cancels the mousedown default, so the terminal keeps focus.
page.press(node('BUTTON'));
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
});
});
describe('FocusTrap.isTypingField', () => {
it('counts textareas, text-like inputs and editable regions, and nothing else', () => {
const { FocusTrap, body } = loadPage();
expect(FocusTrap.isTypingField(node('TEXTAREA'))).toBe(true);
expect(FocusTrap.isTypingField(node('textarea'))).toBe(true);
expect(FocusTrap.isTypingField(node('INPUT'))).toBe(true);
for (const type of ['text', 'search', 'number', 'password', 'email', 'url']) {
expect(FocusTrap.isTypingField(node('INPUT', { type }))).toBe(true);
}
for (const type of [
'button',
'checkbox',
'color',
'file',
'hidden',
'image',
'radio',
'range',
'reset',
'submit',
]) {
expect(FocusTrap.isTypingField(node('INPUT', { type }))).toBe(false);
}
expect(FocusTrap.isTypingField(node('DIV', { isContentEditable: true }))).toBe(true);
expect(FocusTrap.isTypingField(node('DIV'))).toBe(false);
expect(FocusTrap.isTypingField(node('BUTTON'))).toBe(false);
expect(FocusTrap.isTypingField(node('SELECT'))).toBe(false);
expect(FocusTrap.isTypingField(body)).toBe(false);
expect(FocusTrap.isTypingField(null)).toBe(false);
});
});
describe('the document listeners', () => {
it('are two capture listeners, installed once however often the page asks', () => {
const page = loadPage();
page.FocusTrap.watchPresses();
page.FocusTrap.watchPresses();
expect(Object.keys(page.listeners).sort()).toEqual(['keydown:true', 'pointerdown:true']);
expect(page.listeners['pointerdown:true']).toHaveLength(1);
expect(page.listeners['keydown:true']).toHaveLength(1);
});
it('are skipped on a page with no document to listen on', () => {
const context = vm.createContext({ console, document: { createElement: () => node('DIV') } });
vm.runInContext(`${read('keyboard-accessory.js')}\nglobalThis.__FocusTrap = FocusTrap;`, context);
expect((context as unknown as { __FocusTrap: any }).__FocusTrap._watching).toBe(false);
});
});
describe('a dialog built on FocusTrap', () => {
function dialog() {
return { addEventListener: vi.fn(), removeEventListener: vi.fn(), querySelectorAll: () => [] };
}
it('hands the keyboard back to the terminal after it was opened by a mouse press', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const gear = node('BUTTON');
page.setActive(terminal);
page.press(gear, gear);
const trap = new page.FocusTrap(dialog());
trap.activate();
expect(trap.previouslyFocused).toBe(terminal);
trap.deactivate();
expect(terminal.focus).toHaveBeenCalledTimes(1);
expect(gear.focus).not.toHaveBeenCalled();
});
it('still hands it back to the control it was opened from with the keyboard', () => {
const page = loadPage();
const gear = node('BUTTON');
page.setActive(gear);
page.key('Enter');
const trap = new page.FocusTrap(dialog());
trap.activate();
trap.deactivate();
expect(gear.focus).toHaveBeenCalledTimes(1);
});
it('is not misled by the press that closes it', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const gear = node('BUTTON');
const close = node('BUTTON');
page.setActive(terminal);
page.press(gear, gear);
const trap = new page.FocusTrap(dialog());
trap.activate();
page.setActive(close);
page.press(close, close);
trap.deactivate();
expect(terminal.focus).toHaveBeenCalledTimes(1);
});
});
describe('the command palette and the Session Manager', () => {
it('save the same answer, so an overlay opened by a mouse press returns to the terminal', () => {
const page = loadPage({ panels: true });
const terminal = node('TEXTAREA');
const headerButton = node('BUTTON');
page.setActive(terminal);
page.press(headerButton, headerButton);
page.app._rememberOverlayFocus('_sessionManagerPrevFocus');
expect(page.app._sessionManagerPrevFocus).toBe(terminal);
});
it('save what has focus when the overlay was opened with its shortcut', () => {
const page = loadPage({ panels: true });
const terminal = node('TEXTAREA');
page.setActive(terminal);
page.key('k');
page.app._rememberOverlayFocus('_commandPalettePrevFocus');
expect(page.app._commandPalettePrevFocus).toBe(terminal);
});
});
+69 -3
View File
@@ -448,6 +448,72 @@ describe('DiscordBridge', () => {
return b;
}
it('deduplicates replayed real gateway IDs across restart while new replies still work', async () => {
const b = await ready();
const m = reply({ id: '555555555555555555' });
await b.onGatewayMessage(m);
b.stop();
t += 10_000;
const next = await ready();
await next.onGatewayMessage(m);
expect(sendInput).toHaveBeenCalledTimes(1);
await next.onGatewayMessage(reply({ id: '555555555555555556', content: 'continue' }));
expect(sendInput).toHaveBeenCalledTimes(2);
next.stop();
});
it('claims rate-limited snowflake replies so replays remain refused across restart', async () => {
const b = await ready();
await b.onGatewayMessage(reply({ id: '555555555555555555' }));
t += 200;
const refused = reply({ id: '555555555555555556', content: 'too soon' });
await b.onGatewayMessage(refused);
expect(sendInput).toHaveBeenCalledTimes(1);
expect(posts.some((p) => p.path.includes(encodeURIComponent('⏳')))).toBe(true);
t += 5_000;
const count = posts.length;
await b.onGatewayMessage(refused);
expect(sendInput).toHaveBeenCalledTimes(1);
expect(posts).toHaveLength(count);
b.stop();
const next = await ready();
await next.onGatewayMessage(refused);
expect(sendInput).toHaveBeenCalledTimes(1);
await next.onGatewayMessage(reply({ id: '555555555555555557', content: 'new attempt' }));
expect(sendInput).toHaveBeenCalledTimes(2);
next.stop();
});
it('ignores an immediate replay without adding an hourglass to a successful reply', async () => {
const b = await ready();
const m = reply({ id: '555555555555555555' });
await b.onGatewayMessage(m);
t += 200;
await b.onGatewayMessage(m);
expect(sendInput).toHaveBeenCalledTimes(1);
expect(posts.filter((p) => p.method === 'PUT')).toHaveLength(1);
expect(posts.some((p) => p.path.includes(encodeURIComponent('⏳')))).toBe(false);
b.stop();
});
it('delivers replies and alerts when metadata is corrupt and recovers without restarting', async () => {
const b = await ready();
writeFileSync(join(dir, 'discord-reply-dedupe.json'), '{');
const log = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
await b.onGatewayMessage(reply({ id: '555555555555555555' }));
expect(sendInput).toHaveBeenCalledTimes(1);
t += 10_000;
expect((await b.notify(MSG))?.ok).toBe(true);
rmSync(join(dir, 'discord-reply-dedupe.json'));
await b.onGatewayMessage(reply({ id: '555555555555555556' }));
expect(sendInput).toHaveBeenCalledTimes(2);
expect(log).toHaveBeenCalledTimes(1);
} finally {
log.mockRestore();
b.stop();
}
});
it('types an allowed reply into the mapped session and ticks it', async () => {
const b = await ready();
await b.onGatewayMessage(reply());
@@ -1143,7 +1209,7 @@ describe('DiscordBridge files and startup hint', () => {
it('types a reply that waits on a download before a later text reply', async () => {
const b = await make();
const slow = b.onGatewayMessage(reply({ content: 'first' }));
await new Promise((r) => setTimeout(r, 0)); // the first reply is under way (gate passed) before the clock moves
await vi.waitFor(() => expect(downloads).toHaveLength(1)); // wait for the claim and rate-limit gate
t += 5_000;
const fast = b.onGatewayMessage(reply({ id: '555555555555555556', content: 'second', attachments: [] }));
await Promise.all([slow, fast]);
@@ -1157,11 +1223,11 @@ describe('DiscordBridge files and startup hint', () => {
await b.onGatewayMessage(reply({ content: '2', attachments: [] }));
expect(sent.at(-1)?.[1]).toBe('2');
t += 5_000;
await b.onGatewayMessage(reply({ content: 'yes', attachments: [] }));
await b.onGatewayMessage(reply({ id: '555555555555555556', content: 'yes', attachments: [] }));
expect(sent.at(-1)?.[1]).toBe('yes\r');
t += 5_000;
waiting = false;
await b.onGatewayMessage(reply({ content: '2', attachments: [] }));
await b.onGatewayMessage(reply({ id: '555555555555555557', content: '2', attachments: [] }));
expect(sent.at(-1)?.[1]).toBe('2\r');
b.stop();
});
+151
View File
@@ -0,0 +1,151 @@
import { lstat, mkdir, mkdtemp, readFile, rm, symlink, writeFile, stat } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { DiscordReplyDedupe } from '../src/discord-reply-dedupe.js';
import fs from 'node:fs/promises';
let dir: string;
const guild = '111111111111111111',
channel = '222222222222222222',
message = '333333333333333333';
beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), 'discord-replies-'));
});
afterEach(async () => {
await rm(dir, { recursive: true, force: true });
});
it('claims once across concurrent events and restarts, without storing message content', async () => {
const store = new DiscordReplyDedupe(dir);
expect(await Promise.all([store.claim(guild, channel, message), store.claim(guild, channel, message)])).toEqual([
true,
false,
]);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
expect((await stat(join(dir, 'discord-reply-dedupe.json'))).mode & 0o777).toBe(0o600);
expect(JSON.parse(await readFile(join(dir, 'discord-reply-dedupe.json'), 'utf8'))).toEqual([
[`${guild}:${channel}:${message}`, expect.any(Number)],
]);
});
it('falls back on corrupt metadata, logs once, retries after recovery, and retains memory claims', async () => {
const path = join(dir, 'discord-reply-dedupe.json');
await writeFile(path, '{');
const warn = vi.fn(),
store = new DiscordReplyDedupe(dir, Date.now, warn);
expect(await store.claim(guild, channel, message)).toBe(true);
expect(await store.claim(guild, channel, message)).toBe(false);
expect(warn).toHaveBeenCalledTimes(1);
await rm(path);
expect(await store.claim(guild, channel, '444444444444444444')).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
});
it('does not poison metadata with incomplete restored configuration', async () => {
const store = new DiscordReplyDedupe(dir);
expect(await store.claim('', channel, message)).toBe(true);
expect(await store.claim(guild, channel, message)).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
});
it('keeps accepting new replies during ENOSPC and persists memory claims when writes recover', async () => {
const warn = vi.fn();
const store = new DiscordReplyDedupe(dir, Date.now, warn);
const rename = vi.spyOn(fs, 'rename').mockRejectedValueOnce(Object.assign(new Error('full'), { code: 'ENOSPC' }));
try {
expect(await store.claim(guild, channel, message)).toBe(true);
expect(await store.claim(guild, channel, message)).toBe(false);
expect(await store.claim(guild, channel, '444444444444444444')).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
expect(warn).toHaveBeenCalledTimes(1);
} finally {
rename.mockRestore();
}
});
it('evicts old records rather than refusing replies at capacity', async () => {
await writeFile(
join(dir, 'discord-reply-dedupe.json'),
JSON.stringify(
Array.from({ length: 2048 }, (_, i) => [
`${guild}:${channel}:${String(100000000000000000n + BigInt(i))}`,
Date.now(),
])
)
);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(true);
expect(JSON.parse(await readFile(join(dir, 'discord-reply-dedupe.json'), 'utf8'))).toHaveLength(2048);
});
it.each(['{', '{}', '[null]'])(
'heals readable invalid metadata %s and keeps the claim across restart',
async (invalid) => {
const path = join(dir, 'discord-reply-dedupe.json');
await writeFile(path, invalid);
const warn = vi.fn(),
store = new DiscordReplyDedupe(dir, Date.now, warn);
expect(await store.claim(guild, channel, message)).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
expect(warn).toHaveBeenCalledTimes(1);
}
);
it('retains newer outage claims when disk recovery reaches capacity, without overwriting an unread file', async () => {
const path = join(dir, 'discord-reply-dedupe.json');
const rows = Array.from({ length: 2048 }, (_, i) => [
`${guild}:${channel}:${100000000000000000n + BigInt(i)}`,
Date.now(),
]);
const original = JSON.stringify(rows);
await writeFile(path, original);
const warn = vi.fn(),
store = new DiscordReplyDedupe(dir, Date.now, warn);
const read = vi
.spyOn(fs, 'readFile')
.mockRejectedValueOnce(Object.assign(new Error('descriptor limit'), { code: 'EMFILE' }));
expect(await store.claim(guild, channel, message)).toBe(true);
read.mockRestore();
expect(await readFile(path, 'utf8')).toBe(original);
expect(await store.claim(guild, channel, '444444444444444444')).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
const saved = JSON.parse(await readFile(path, 'utf8'));
expect(saved).toHaveLength(2048);
expect(saved.some((row: [string, number]) => row[0] === rows[0][0])).toBe(false);
});
it('heals an over-cap readable store rather than remaining memory-only until manual deletion', async () => {
const path = join(dir, 'discord-reply-dedupe.json');
await writeFile(
path,
JSON.stringify(
Array.from({ length: 2049 }, (_, i) => [`${guild}:${channel}:${100000000000000000n + BigInt(i)}`, Date.now()])
)
);
const warn = vi.fn();
expect(await new DiscordReplyDedupe(dir, Date.now, warn).claim(guild, channel, message)).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
expect(warn).toHaveBeenCalledTimes(1);
});
it('heals oversized regular metadata and persists replay protection across restart', async () => {
const path = join(dir, 'discord-reply-dedupe.json');
await writeFile(path, ' '.repeat(512 * 1024 + 1));
const warn = vi.fn();
expect(await new DiscordReplyDedupe(dir, Date.now, warn).claim(guild, channel, message)).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
expect((await stat(path)).size).toBeLessThan(512 * 1024);
expect(warn).toHaveBeenCalledTimes(1);
});
it('never replaces a symlink or a folder at the metadata path, and still accepts replies', async () => {
const path = join(dir, 'discord-reply-dedupe.json');
const target = join(dir, 'target');
await writeFile(target, 'keep');
await symlink(target, path);
const warn = vi.fn(),
store = new DiscordReplyDedupe(dir, Date.now, warn);
expect(await store.claim(guild, channel, message)).toBe(true);
expect(await store.claim(guild, channel, message)).toBe(false);
expect(await store.claim(guild, channel, '444444444444444444')).toBe(true);
expect((await lstat(path)).isSymbolicLink()).toBe(true);
expect(await readFile(target, 'utf8')).toBe('keep');
expect(warn).toHaveBeenCalledTimes(1);
await rm(path);
await mkdir(path);
expect(await new DiscordReplyDedupe(dir, Date.now, warn).claim(guild, channel, message)).toBe(true);
expect((await lstat(path)).isDirectory()).toBe(true);
});
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff. Show more