mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-12-03 17:19:33 +01:00
Compare commits
133
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
14e5320762 | ||
|
|
1cff252277 | ||
|
|
5f4951884f | ||
|
|
3994196341 | ||
|
|
15ea44e5c1 | ||
|
|
bc1a97eee2 | ||
|
|
63af255726 | ||
|
|
17e66d50c0 | ||
|
|
c3eb9cad22 | ||
|
|
4be36b0404 | ||
|
|
a117955490 | ||
|
|
d3d1f7cde1 | ||
|
|
3397d11859 | ||
|
|
ab5f197dcc | ||
|
|
01380d8b26 | ||
|
|
95ad7f2d00 | ||
|
|
ef730de240 | ||
|
|
7df0f11892 | ||
|
|
111fb323ee | ||
|
|
5374d020d7 | ||
|
|
85c0f35972 | ||
|
|
691ea6c87a | ||
|
|
5588a54e3f | ||
|
|
2ea593c2e2 | ||
|
|
e3c156e6e8 | ||
|
|
c51a7134eb | ||
|
|
d9fce03444 | ||
|
|
c6fff5e6a8 | ||
|
|
58b923f2e5 | ||
|
|
6db166f3f8 | ||
|
|
fd2b232efe | ||
|
|
b3e781696a | ||
|
|
854f316809 | ||
|
|
00552ac04a | ||
|
|
4936e07ca2 | ||
|
|
51852dbdbc | ||
|
|
fcccdd07c5 | ||
|
|
f2c03e6bf3 | ||
|
|
d5fe0adfe7 | ||
|
|
a4201b34a8 | ||
|
|
a69ceef4f0 | ||
|
|
029adccb83 | ||
|
|
992819ba98 | ||
|
|
70ee1312d4 | ||
|
|
9309500d40 | ||
|
|
dcfa76125f | ||
|
|
95918b80b4 | ||
|
|
64c8d1c8a5 | ||
|
|
b957eb8dea | ||
|
|
6824fe666c | ||
|
|
5672e47a2d | ||
|
|
03916d75a1 | ||
|
|
38c98529c4 | ||
|
|
063476ec55 | ||
|
|
7a3bbce7d5 | ||
|
|
eb40f4aaa5 | ||
|
|
dfd661f9d1 | ||
|
|
fc41bb5b13 | ||
|
|
76c5f1a99b | ||
|
|
f109bdc23a | ||
|
|
d466e5c3bf | ||
|
|
1d889468df | ||
|
|
0be4c154cc | ||
|
|
b7bb332338 | ||
|
|
babb55e4d9 | ||
|
|
891f3a19e9 | ||
|
|
ccf502b7a8 | ||
|
|
17b885f5da | ||
|
|
d620b7b194 | ||
|
|
aabd71ee98 | ||
|
|
79f85415d8 | ||
|
|
bb68915384 | ||
|
|
7e199f1fac | ||
|
|
3658dc516f | ||
|
|
8480bba908 | ||
|
|
9753ca9d70 | ||
|
|
dbf545ce8f | ||
|
|
d387cf8cdb | ||
|
|
ba61cfe4e6 | ||
|
|
d7c141e25f | ||
|
|
67aa28ac4f | ||
|
|
df494b21ce | ||
|
|
79f444a2fc | ||
|
|
b02816c1cc | ||
|
|
ac4ab8cf23 | ||
|
|
1835b39e2c | ||
|
|
6de846ba9a | ||
|
|
58a5ef51bc | ||
|
|
349d21f75e | ||
|
|
c52137a2ec | ||
|
|
e44d586f93 | ||
|
|
a92d512459 | ||
|
|
82071d47bd | ||
|
|
3f7d08e97e | ||
|
|
c22bbd70ac | ||
|
|
7d6e7fd411 | ||
|
|
4848886330 | ||
|
|
7794f74282 | ||
|
|
6f5b3aca23 | ||
|
|
99977ca022 | ||
|
|
e7f90cb3ec | ||
|
|
a692f9f193 | ||
|
|
1f9b17e29a | ||
|
|
193f220f5e | ||
|
|
6311e59412 | ||
|
|
b3698756a2 | ||
|
|
bc00ad4335 | ||
|
|
444f375ac7 | ||
|
|
5f0366c060 | ||
|
|
b4d729a054 | ||
|
|
9ef47aca6c | ||
|
|
fd6b392b4d | ||
|
|
b890ef3302 | ||
|
|
fd31315582 | ||
|
|
e91c62885a | ||
|
|
2d818e39bf | ||
|
|
cda5d96451 | ||
|
|
414dd51eb2 | ||
|
|
e4ac7728ba | ||
|
|
71c7d01d02 | ||
|
|
05fc2f990b | ||
|
|
5ff018772e | ||
|
|
cc2b7d9c25 | ||
|
|
ddb5a647ba | ||
|
|
ad08cb957d | ||
|
|
eb22f10fd4 | ||
|
|
db5ab5a701 | ||
|
|
c4b382b727 | ||
|
|
bee4948e1a | ||
|
|
363de086fc | ||
|
|
e4a85fabcd | ||
|
|
ab9c574ca4 | ||
|
|
4cedeec529 |
No files matched your search
@@ -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.1",
|
||||
"version": "1.52.1",
|
||||
"author": {
|
||||
"name": "Ark0N",
|
||||
"url": "https://github.com/Ark0N"
|
||||
|
||||
@@ -1,5 +1,69 @@
|
||||
# aicodeman
|
||||
|
||||
## 1.52.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 63af255: ### Thanks
|
||||
- @irisitymichaelgrundberg for the first part of the chat view (#859) and for the markdown table fix (#866), each with careful measurements in two browsers.
|
||||
- @zomby1 for single sign-on through a reverse proxy (#854, proposed in #846), run behind Caddy and oauth2-proxy for days before it landed.
|
||||
- @aakhter for Codex file previews (#850), three review rounds.
|
||||
- @ludovicfourrage for HTML uploads (#869, from #868).
|
||||
- @eltociear for the Japanese README (#860), a first contribution.
|
||||
|
||||
**Claude sessions start when Codeman runs as root (#863).** On a VPS or in a Proxmox LXC container the server often runs as root, and Claude Code refuses `--dangerously-skip-permissions` there, so every local Claude tab was a dead pane. A server running as root now starts Claude without the bypass (Claude asks for permission instead) and says so in the server log. Shell sessions, Docker cases and remote sessions are unchanged.
|
||||
|
||||
**Multi-user mode can sign people in through a reverse proxy (#854, experimental).** With `CODEMAN_TRUSTED_PROXY_SECRET_FILE` set, an authenticating proxy on the same host (oauth2-proxy behind Caddy or nginx, Authelia, Apache mod_auth_openidc) signs people in with Entra ID, Google Workspace, Keycloak and others. Codeman accepts the proxy's `X-Codeman-User` only from a loopback connection that also presents the secret, and only for an existing, enabled account. The headers are removed from every request before anything else sees them. Off by default. The wiki's Multi-User Mode page has a Caddy and oauth2-proxy walkthrough.
|
||||
|
||||
**A chat view for Claude sessions (#859, first part, opt-in).** A local or Docker Claude session can show its conversation as rendered text instead of the terminal. Alt+Shift+C switches a session between Chat and Terminal, and each session remembers its choice on the device. Answers fill in while the turn runs, long prompts fold, and a notice with a button to the terminal appears while Claude waits on a permission prompt or a question. You still type in the terminal for now; the message box follows in a later release. Nothing changes until you choose it: Settings > Header & Panels has "Open Claude sessions in Chat view" and "Show the Chat / Terminal switch" (a switch at the top right of the session), both off by default. Phones, remote and adopted sessions, tiles and the split's second pane keep the terminal.
|
||||
|
||||
**Codex sessions can open the files they link in Codeman's preview (#850, opt-in).** With the new per-device Codex files setting on (Settings > Header & Panels, off by default), clicking a file name Codex underlined in its answer, or a file tab in Codex's own sidebar, opens that file in the file preview when the conversation names exactly one such file; anything else still goes to Codex. The setting also adds a Response files button listing the files of the last answer, and a Dock button that places the preview beside the terminal on a wide screen. With it off, every click goes to Codex as before.
|
||||
|
||||
**Prompt uploads take `.html` and `.htm` (#869, from #868).** AI tools write specs and reports as HTML as often as Markdown, and attaching one is now the same as attaching a `.md`: paste, drop and every Attach picker take it, it is checked like the rest of the text family, and it is saved to `.codeman-uploads/`. It is stored to be read, never rendered on Codeman's own origin. Scripts (`.sh`, `.py`, `.js`) are still refused.
|
||||
|
||||
**Fixes.**
|
||||
- **Markdown table columns no longer shrink to one letter per line (#866).** In the response viewer and the file preview, a narrow column next to a long one wrapped its text a letter at a time. Cells now wrap between words, while inline code, links and paths in a cell still break where needed.
|
||||
- **The installer gets past sudo in a headless run (#863).** With a working passwordless sudo and no terminal (`su - user -c`, cron, a CI runner, cloud-init), the installer stopped at "Failed to obtain sudo privileges". It now checks that `/dev/tty` can be opened before reading from it.
|
||||
- **Mac app: a server tab can be dragged into the last place.** Dragging a tab as far right as it goes left it one place short of the end.
|
||||
|
||||
**Fixes applied while landing.** The proxy secret is also removed from Node's raw header list, not only from the parsed headers (#854). With a preview open, switching Codex files on or off now shows or hides its Dock button at once, and the click on an underlined file name is behind that setting too (#850). The Chat / Terminal switch is off by default (#859).
|
||||
|
||||
**Docs.** A Japanese README (#860), linked from the English and Chinese ones; an npm release moves every translated README aside so npmjs.com keeps showing the English one.
|
||||
|
||||
## 1.52.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 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
|
||||
|
||||
@@ -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.1 (must match `package.json`)
|
||||
**Version**: 1.52.1 (must match `package.json`)
|
||||
|
||||
## Project Overview
|
||||
|
||||
@@ -152,13 +152,13 @@ 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`.
|
||||
|
||||
@@ -186,7 +186,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
|
||||
**Docker Compose deployment** (`docker/`): Codeman runs in a container and spawns Docker cases as **SIBLING** containers via the host socket, never nested. `resolveDockerDaemonMountSource()` maps HOME bind sources into the daemon's namespace (`CODEMAN_DOCKER_HOST_HOME`); `CODEMAN_CASES_PATH` makes workspaces resolve to the same absolute path on both sides. ⚠️ `CODEMAN_CASES_PATH` must move every consumer: resolve it only via `config/cases-dir.ts`. ⚠️ `.dockerignore` matches whole paths: keep `**/.env` or `docker/.env` secrets ship in the image. ⚠️ Long-form binds create missing sources ROOT-OWNED: `Start-Codeman.sh` pre-creates them, and `docker/entrypoint.sh` (root, `cap_add: [CHOWN, DAC_OVERRIDE, KILL, SETGID, SETUID]` against `cap_drop: ALL`, `KILL` for tini; pinned by the test) fixes ownership then drops to `PUID:PGID` via `setpriv`, never re-owning foreign dirs. ⚠️ Append `/opt/codeman-cli` and `~/.local/bin` to `PATH`, never prepend. ⚠️ `server.Dockerfile`, the compose file and `.env.example` feed the self-updater's environment gate (`docs/docker-self-update.md`). → [architecture-invariants#docker-compose-deployment](docs/architecture-invariants.md#docker-compose-deployment), `docs/docker-compose.md`
|
||||
|
||||
**CLI registry** (`src/config/cli-registry/`): every run mode is a `CliEntry` (discovery, launch argv template, env handling, `capabilities`, and the `overlays` behind remote/docker pane commands). **No code outside `stock.ts` may branch on a CLI id**: use a capability field or a NAMED PROFILE (`profiles.ts`); `test/cli-registry-no-id-branching.test.ts` and `test/frontend-cli-no-id-branching.test.ts` enforce it. ⚠️ Config holds typed argv tokens, never shell text; literals are validated at LOAD time and a bad one rejects the whole entry. ⚠️ Keep `external`, `hooks` and `altScreen` independent; never derive one from another. ⚠️ Config regexes (`discovery.version.regex`, `capabilities.workDetect.workingLine`, `capabilities.workDetect.watchingLine`, `capabilities.workDetect.awaitingLine`, `capabilities.workDetect.blockedLine`, `capabilities.workDetect.composerFooterLine`, `capabilities.workDetect.composerPopupLine`, `capabilities.modelDetect.screenLine`) must compile through `compileVersionRegex()`. ⚠️ `privilegedParams[].param` names a LAUNCH PARAM, not the legacy `<Mode>Config` field (bridged only by `launch.legacyConfigAliases`); a wrong name silently clamps nothing. ⚠️ Resolve the registry AT CALL TIME, never in a module-level const. ⚠️ Remote claude/omp arms of `buildRemoteLaunchCommand` are not covered by the pane-command golden. `~/.codeman/clis.json` overrides entries. It is WRITTEN only by the opt-in CLI management routes (`cliManagementEnabled`, default OFF; `/api/clis`, `cli-registry-routes.ts`), and only through `mutateRegistryFile()` in `registry-writer.ts` (the one exception: a config-backup restore of `clis.json`, which then calls `reloadCliRegistry()`), which serializes mutations and refuses (409) a file that does not parse or has group/world permission bits rather than overwriting it. Importing the registry still writes nothing. → [architecture-invariants#cli-registry](docs/architecture-invariants.md#cli-registry), `docs/cli-registry.md`
|
||||
**CLI registry** (`src/config/cli-registry/`): every run mode is a `CliEntry` (discovery, launch argv template, env handling, `capabilities`, and the `overlays` behind remote/docker pane commands). **No code outside `stock.ts` may branch on a CLI id**: use a capability field or a NAMED PROFILE (`profiles.ts`); `test/cli-registry-no-id-branching.test.ts` and `test/frontend-cli-no-id-branching.test.ts` enforce it. ⚠️ Config holds typed argv tokens, never shell text; literals are validated at LOAD time and a bad one rejects the whole entry. ⚠️ Keep `external`, `hooks` and `altScreen` independent; never derive one from another. ⚠️ Config regexes (`discovery.version.regex`, `capabilities.workDetect.workingLine`, `capabilities.workDetect.watchingLine`, `capabilities.workDetect.awaitingLine`, `capabilities.workDetect.blockedLine`, `capabilities.workDetect.composerFooterLine`, `capabilities.workDetect.composerPopupLine`, `capabilities.modelDetect.screenLine`) must compile through `compileVersionRegex()`. ⚠️ `privilegedParams[].param` names a LAUNCH PARAM, not the legacy `<Mode>Config` field (bridged only by `launch.legacyConfigAliases`); a wrong name silently clamps nothing. ⚠️ Resolve the registry AT CALL TIME, never in a module-level const. ⚠️ Remote claude/omp arms of `buildRemoteLaunchCommand` are not covered by the pane-command golden. ⚠️ A server that runs as root (uid 0) starts a LOCAL claude without the bypass flag, which Claude Code refuses under root (a dead pane on every session): the swap is the enum param's `rootValue` (`root-launch.ts`, pure), asked through `serverRunsAsRoot()` at call time by `serverRootSpawnOptions()` (both tmux launches) and `buildPermissionArgs()` (direct PTY, one-shot) only, logged once per launch; never an id branch, never `IS_SANDBOX`, never for a remote or Docker launch, and not root stays byte-identical (`test/root-launch.test.ts`). `~/.codeman/clis.json` overrides entries. It is WRITTEN only by the opt-in CLI management routes (`cliManagementEnabled`, default OFF; `/api/clis`, `cli-registry-routes.ts`), and only through `mutateRegistryFile()` in `registry-writer.ts` (the one exception: a config-backup restore of `clis.json`, which then calls `reloadCliRegistry()`), which serializes mutations and refuses (409) a file that does not parse or has group/world permission bits rather than overwriting it. Importing the registry still writes nothing. → [architecture-invariants#cli-registry](docs/architecture-invariants.md#cli-registry), `docs/cli-registry.md`
|
||||
|
||||
**External CLI modes (OpenCode, Codex, Gemini, Antigravity, Pi, Grok, DeepSeek, OMP, Copilot, jcode)**: `isExternalCliMode()` in `session.ts` gates Claude-specific behavior off (Ralph tracker, BashToolParser, token parsing, ❯ readiness; readiness is output stabilization); work detection is per-CLI `capabilities.workDetect` data, not this gate. All ten **require tmux, no direct PTY fallback** (secrets go via socket-scoped `tmux setenv`, never the command line). ⚠️ `run*()` in `session-ui.js` MUST unwrap the `{success,data}` envelope. ⚠️ **Codex uses predictive write-through echo, never the buffer overlay**: `_predictHookOnData` must never `return` (wire path stays byte-identical), and flushed text and a bracketed paste must go out as separate delayed writes. ⚠️ **Pi**: no bypass flag, never invent one; `approveProjectTrust` executes repo code, so it is in the clamp's **materialize** branch; never wire `--api-key`. ⚠️ **Grok**: `alwaysApprove` is stripped for non-granted owners (only-if-sent). ⚠️ **DeepSeek**: the agent is a PROFILE (Run gates on `isDeepSeekRunnable()`); the permission switch is the `DSH_PERMISSION_MODE` env var, so `clampEnvOverridesForOwner()` must DROP `DSH_PERMISSION_MODE`, `DSH_HOME` and `DEEPSEEK_BASE_URL` for non-granted owners; `hooksAvailableForMode()` is per-SESSION for it (pass `sessionHookOptions(session)`) and is never a stand-in for `mode === 'claude'`; answers come from `deepseek-transcript.ts`, paired by header `cwd` + boot window, never newest-mtime. ⚠️ **OMP**: `OMP_AUTH_BROKER_URL`/`_TOKEN` are clamped the same way. ⚠️ **Copilot**: `allowAll` (`--yolo`) is a `privilegedParam` and `COPILOT_HOME`/`COPILOT_ALLOW_ALL`/`COPILOT_PROVIDER_*`/`COPILOT_MODEL` are privileged env keys, and so is every other `COPILOT_*` variable the CLI reads that switches approvals, runs code with no approval row or sends its sign-in token elsewhere (the 1.0.98 list is in `stock.ts`; the prefix admits whatever a later release adds, so re-read the bundle whenever the measured version moves); the resume id must start with a letter or digit (`path-segment`), since `--resume`'s value is optional and `--resume --yolo` would otherwise make `--yolo` its own flag; `--name` is dropped next to `--resume`/`--continue` (Copilot refuses the pair); its mouse DECSETs are stripped (`strip-mux-and-mouse`) so a drag selects and the wheel is forwarded by `_shouldForwardWheelToApp` while `cliMouseTracking` is on; `composerReadyMark` is the footer hint `/ commands · ? help`, NOT `❯` (the folder-trust dialog draws `❯ 1. Yes`); `last-response` reads the pane's visible screen (`transcriptNeedsScreenCapture`) through a per-CLI `PANE_DIALECTS` row, because its stream is cursor moves, not lines (a prompt row scrolled off by a tall answer reads as the answer's tail unless a banner/trust dialog is on screen, and typed composer text is not a prompt); Docker seeds no Copilot credential (`config.json` holds a plain-text token without a keyring). ⚠️ **jcode**: every pane is a client of ONE shared per-user daemon and the tools run in the daemon with ITS env, so jcode gets no agent skill and no `JCODE_*` envOverrides prefix (a per-session value would act as another session or reach every one); `last-response` is an honest empty (external + `transcript: 'none'`, never the segmenter or the Claude scan); ⚠️ that daemon is a descendant of whichever pane started it, so `capabilities.sharedDaemon` makes `killSession` spare descendants outside the pane's process group (`descendantsInPaneGroup()`, `proc-tree.ts`), or closing that one tab cuts every other jcode session off; it resolves through the generic registry resolver, with no per-CLI resolver module (`docs/jcode-integration.md`). → [architecture-invariants#external-cli-modes-opencode-codex-gemini-antigravity-pi-grok-deepseek-omp](docs/architecture-invariants.md#external-cli-modes-opencode-codex-gemini-antigravity-pi-grok-deepseek-omp)
|
||||
|
||||
@@ -206,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)
|
||||
|
||||
@@ -228,7 +228,7 @@ 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**. 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)
|
||||
@@ -239,7 +239,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
|
||||
**Attachments** (live external document references; all wiring in `file-routes.ts`): a **registry** maps a stable `attachmentId` to a realpath-resolved, extension-allowlisted absolute path, so browser requests never carry arbitrary absolute paths. ⚠️ The **magic-link scanner** (`codeman://attach?...` in terminal output) is **prompt-injectable**, so its scan path is force-confined to the session workspace; a hostile prompt could otherwise exfiltrate arbitrary host files over SSE. The security gate is an extension **allowlist**, not a blocklist. `document-conversion-limiter.ts` caps converter spawns globally: without it, N large docs detected at once fork N multi-minute processes, which is a resource-exhaustion vector. → [architecture-invariants#attachments](docs/architecture-invariants.md#attachments)
|
||||
|
||||
**Prompt uploads** (`POST /api/sessions/:id/paste-image`: clipboard paste, drop, the Compose Attach key and the phone toolbar's Attach button; client wiring in `image-input.js` and `keyboard-accessory.js`): a pick is written to `<workspace>/.codeman-uploads/` and its path lands on the prompt as unsent text. The folder is IN the workspace because that is the only path identical for a local and a container agent, FLAT because `<workspace>/.codeman/` would BE the data dir when the workspace is the home directory, and self-ignoring through a `.gitignore` of `*` written ONCE with `wx` (a file already there is the user's and is never overwritten; the user's own ignore file is never touched). ⚠️ The directory names live ONLY in `paste-image-gc.ts` (`UPLOAD_DIR_NAMES`): the pre-move `.claude-images/` receives nothing but stays readable for one release, so the GC sweep and the delete cleanup (through `uploadDirs()`) and the image watcher's ignore filter (reading the names) cover BOTH; retire the legacy entry there, never by hand elsewhere. ⚠️ `uploadDirs()` is async and probes the workspace BOUNDED first (`probePathKind()`, the #516 rule: an `unknown` path is skipped, never touched; the sweep keeps the stall cap and the delete passes `pastCap`), then returns only REAL directories (lstat, so a planted symlink is never one), none that is or contains `getDataDir()` (one strictly inside it only holds uploads and is listed), and none for a remote session, since both consumers delete; the check is made at list time, and the same-user race after it is accepted. Images are buffered in memory under `MAX_PASTE_IMAGE_BYTES` (50MB) after a client-side canvas re-encode; a DOCUMENT (pdf, docx, pptx, xlsx, zip and the text family txt/md/csv/tsv/json/log/yaml/yml/xml; the curated `ALLOWED_DOCUMENT_EXTS`, never `SUPPORTED_ATTACHMENT_EXTENSIONS` or `EDITABLE_EXTENSIONS`, which carry sh/py/js/html) is admitted by its name's extension alone, buffered like an image, judged on its bytes by the same fail-closed `imageMagicMatchesExt` (`%PDF-`, `PK\x03\x04` for the OOXML trio and zip, UTF-8 without a NUL byte for text: a SIGNATURE or ENCODING check, never a structure or content check, so generic zip bytes pass as `.docx` and a script renamed `.txt` is text; the sh/py/js/html exclusion is a SCOPE choice by extension, keeping the server from storing what it would serve or run, not a content filter: the agent can already write any of those) and saved as `paste-<ts>-<hex>-<stem><ext>` with a sanitized stem (`[A-Za-z0-9._-]`, 40 chars, a wholly non-ASCII name leaves no stem; the `paste-` prefix is what the GC matches). A VIDEO is never buffered: `?kind=video` streams it to disk under `MAX_PASTE_VIDEO_BYTES` (1GB, env `CODEMAN_MAX_PASTE_VIDEO_BYTES`), judges the container on the first 12 bytes as they arrive (ISO BMFF / QuickTime atom, EBML for webm, Ogg for ogv; a mislabeled body is drained unwritten from there, never parked on disk first) and unlinks on any failure, a dead transfer included. ⚠️ The flag is the ONLY way onto that path and admits video types alone (the registry's `VIDEO_ATTACHMENT_EXTENSIONS`, single-sourced: mp4/webm/mov/m4v/ogv, so an uploaded video is one the file viewer can also play; 3gp/mkv are out, since a phone's camera roll produces neither and neither previews), so an image can never ride the larger cap through memory; without it the route is byte-identical to the image-only version. Busboy takes its size limit before the part is seen, which is why the choice rides the URL and not the file. ⚠️ A video draws on its OWN per-(IP, session) rate bucket (`consumeVideoToken`, 3/min) beside the image bucket (`consumePasteToken`, 30/min): at 1GB each, 30/min would be 30GB of disk a minute, so the lower rate bounds it to 3GB; the image path keeps the 30/min bucket and is unchanged without the flag. A remote (SSH) session is refused (400) before any disk touch: its `workingDir` is the remote path, so the file would land on THIS host where the agent cannot read it (Docker is fine, the workspace is bind-mounted at the same absolute path). ⚠️ A live session's workspace can still sit on a network mount that stopped answering, so the route probes it BOUNDED (`probePathKind(session.workingDir, { pastCap: true })`, the #516 rule) before the first disk touch and refuses an `unknown` mount through `describeUnknownPath()` (OPERATION_FAILED), the way session create does, so a mount already unreachable cannot freeze a libuv worker on every upload (a mount that dies after the probe is the same residual race create accepts). ⚠️ Dispatch mirrors the client: an `image/*` MIME takes the IMAGE path whatever the name says (a GIF named `animation.txt` stays a GIF), a document extension takes the document branch, and anything else takes the image path exactly as before, where the HEIC sniff still recovers a HEIC under a generic name; a foreign extension with no image MIME gets its `Unsupported file type` 400 only AFTER that sLine truncated
|
||||
**Prompt uploads** (`POST /api/sessions/:id/paste-image`: clipboard paste, drop, the Compose Attach key and the phone toolbar's Attach button; client wiring in `image-input.js` and `keyboard-accessory.js`): a pick is written to `<workspace>/.codeman-uploads/` and its path lands on the prompt as unsent text. The folder is IN the workspace because that is the only path identical for a local and a container agent, FLAT because `<workspace>/.codeman/` would BE the data dir when the workspace is the home directory, and self-ignoring through a `.gitignore` of `*` written ONCE with `wx` (a file already there is the user's and is never overwritten; the user's own ignore file is never touched). ⚠️ The directory names live ONLY in `paste-image-gc.ts` (`UPLOAD_DIR_NAMES`): the pre-move `.claude-images/` receives nothing but stays readable for one release, so the GC sweep and the delete cleanup (through `uploadDirs()`) and the image watcher's ignore filter (reading the names) cover BOTH; retire the legacy entry there, never by hand elsewhere. ⚠️ `uploadDirs()` is async and probes the workspace BOUNDED first (`probePathKind()`, the #516 rule: an `unknown` path is skipped, never touched; the sweep keeps the stall cap and the delete passes `pastCap`), then returns only REAL directories (lstat, so a planted symlink is never one), none that is or contains `getDataDir()` (one strictly inside it only holds uploads and is listed), and none for a remote session, since both consumers delete; the check is made at list time, and the same-user race after it is accepted. Images are buffered in memory under `MAX_PASTE_IMAGE_BYTES` (50MB) after a client-side canvas re-encode; a DOCUMENT (pdf, docx, pptx, xlsx, zip and the text family txt/md/csv/tsv/json/log/yaml/yml/xml/html/htm; the curated `ALLOWED_DOCUMENT_EXTS`, never `SUPPORTED_ATTACHMENT_EXTENSIONS` or `EDITABLE_EXTENSIONS`, which carry sh/py/js) is admitted by its name's extension alone, buffered like an image, judged on its bytes by the same fail-closed `imageMagicMatchesExt` (`%PDF-`, `PK\x03\x04` for the OOXML trio and zip, UTF-8 without a NUL byte for text: a SIGNATURE or ENCODING check, never a structure or content check, so generic zip bytes pass as `.docx` and a script renamed `.txt` is text; the sh/py/js exclusion is a SCOPE choice by extension, keeping the server from storing what an agent could run, not a content filter: the agent can already write any of those; html/htm are admitted as AI-written specs and reports, the same job as a .md, and stay inert because file-raw serves them as `application/octet-stream` + `nosniff` and html-view refuses a page under a dot-directory such as `.codeman-uploads`) and saved as `paste-<ts>-<hex>-<stem><ext>` with a sanitized stem (`[A-Za-z0-9._-]`, 40 chars, a wholly non-ASCII name leaves no stem; the `paste-` prefix is what the GC matches). A VIDEO is never buffered: `?kind=video` streams it to disk under `MAX_PASTE_VIDEO_BYTES` (1GB, env `CODEMAN_MAX_PASTE_VIDEO_BYTES`), judges the container on the first 12 bytes as they arrive (ISO BMFF / QuickTime atom, EBML for webm, Ogg for ogv; a mislabeled body is drained unwritten from there, never parked on disk first) and unlinks on any failure, a dead transfer included. ⚠️ The flag is the ONLY way onto that path and admits video types alone (the registry's `VIDEO_ATTACHMENT_EXTENSIONS`, single-sourced: mp4/webm/mov/m4v/ogv, so an uploaded video is one the file viewer can also play; 3gp/mkv are out, since a phone's camera roll produces neither and neither previews), so an image can never ride the larger cap through memory; without it the route is byte-identical to the image-only version. Busboy takes its size limit before the part is seen, which is why the choice rides the URL and not the file. ⚠️ A video draws on its OWN per-(IP, session) rate bucket (`consumeVideoToken`, 3/min) beside the image bucket (`consumePasteToken`, 30/min): at 1GB each, 30/min would be 30GB of disk a minute, so the lower rate bounds it to 3GB; the image path keeps the 30/min bucket and is unchanged without the flag. A remote (SSH) session is refused (400) before any disk touch: its `workingDir` is the remote path, so the file would land on THIS host where the agent cannot read it (Docker is fine, the workspace is bind-mounted at the same absolute path). ⚠️ A live session's workspace can still sit on a network mount that stopped answering, so the route probes it BOUNDED (`probePathKind(session.workingDir, { pastCap: true })`, the #516 rule) before the first disk touch and refuses an `unknown` mount through `describeUnknownPath()` (OPERATION_FAILED), the way session create does, so a mount already unreachable cannot freeze a libuv worker on every upload (a mount that dies after the probe is the same residual race create accepts). ⚠️ Dispatch mirrors the client: an `image/*` MIME takes the IMAGE path whatever the name says (a GIF named `animation.txt` stays a GIF), a document extension takeLine truncated
|
||||
|
||||
**File-path links (terminal + chat)**: a path an agent prints is clickable on BOTH surfaces and opens the file-preview overlay. ⚠️ ONE pattern (`FILE_PATH_LINK_PATTERN` / `absoluteFilePathPattern()` in constants.js) feeds the xterm link provider AND `_linkifyFilePaths()`, a fresh instance per call (`lastIndex`). Both call `findFilePathLinks()`, which reserves spaced-path spans first (an unlinkable one only while its last word holds a `/`; any label, before an absolute or relative path, must be an explicit path label, prose after that label stays out, and an earlier connective or verb such as `and` or `has` (`SPACED_PATH_PROSE_WORD`) makes any candidate prose; rules and trade-offs in the architecture-invariants paragraph linked below), then adds rooted, `~/`, relative and folder paths without overlapping a reservation, earlier match or URL; a relative path resolves against the pane's live directory `SessionState.paneCwd` when known, else `workingDir` (`relativeResolutionBase()` + `resolveLinkedFilePath`; `paneCwd` is only a BASE, never a confinement root: routing and the file routes still judge against `workingDir`, or against a followed worktree for an absolute path inside it, and remote/docker/direct-PTY/rediscovered sessions never get one, scoped by `paneExitApplies`), `~/` only server-side on the session's host (attachment route), and `terminalPathLine()` joins a path a program hard-wrapped short of the edge. ⚠️ A folder link opens the **folder grid**: `POST /api/sessions/:id/folders` guards + GRANTS the folder (`folder-listing.ts`, own registry, never the 200-capped attachment registry), files come by bare name via `…/folders/:folderId/files/:name/*` through `resolveServableAttachmentPath` plus the same extension/regular-file gate on the symlink's resolved target, so no browser request carries a path; `~/` is refused in a Docker case (the container's home is not this host's). The chat linkifier walks TEXT NODES with DOM APIs, never rebuilds sanitized markup as a string. ⚠️ An out-of-workspace path goes through the ATTACHMENT routes (`POST /api/sessions/:id/attachments` with `notify: false`), never by widening `file-content`/`file-raw` or `file-stream-manager`'s `tail -f` allowlist. The one exception is an absolute path inside a followed worktree outside `workingDir` (`SessionState.outsideWorktree`), which the file routes serve as a second root (see Files panel in a worktree). An ambiguous parenthesised hard wrap is checked only on activation, original first: only a 404 permits a spaced-path lookup, and only a registered alternative is opened; every other original result uses the normal opener, never an attachment-policy gate on workspace files, and hover performs no lookup. ⚠️ `TEXT_ATTACHMENT_EXTENSIONS` IS `EDITABLE_EXTENSIONS` (never a second list), and widening READ must never widen RUN: `html`/`htm`/`svg` stay download-only, other text is inert `text/plain`+`nosniff`. ⚠️ The ONE place HTML renders is `/html-view/<cap>/...` (`html-view-routes.ts`, `html-view-capabilities.ts`): `POST /api/sessions/:id/html-view` mints a capability for the file's own directory, every response carries `Content-Security-Policy: sandbox` WITHOUT `allow-same-origin` (opaque origin even as a top-level tab, so the page can never read Codeman or drive its API) and with NO fetch directive (open network, owner decision 2026-10-13: never restrict it or add `allow-same-origin` without the owner), and only non-dot, asset-allowlisted files under that directory are served (GET/HEAD only; capabilities revoked with the web-tab ones on logout). That tree is served recursively, so minting is refused for a hidden directory or a broad root (`isBroadHtmlViewRoot`); the preview renders by default and the **Page** pill (or a refused mint) falls through to the source view and its Edit button. Never serve HTML same-origin anywhere else. Tests: `test/routes/html-view-routes.test.ts`. Media extensions are single-sourced in `attachment-registry.ts`. ⚠️ **XLSX previews parse in the BROWSER**, never on the server; the admission limits that keep a hostile workbook from freezing the worker live in `src/web/CLAUDE.md` (Spreadsheet preview). → [architecture-invariants#file-path-links-terminal--response-viewer](docs/architecture-invariants.md#file-path-links-terminal--response-viewer)
|
||||
|
||||
@@ -251,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)
|
||||
|
||||
@@ -273,7 +273,7 @@ The terminal provider scans `terminalLinkLine()`, which extends `terminalPathLin
|
||||
|
||||
**Web tabs** (dashboard URLs as tabs): a saved URL renders as a tab beside sessions, **NOT a `SessionMode`**, and is proxied through Codeman's own origin (`/webview/<cap>/...`). ⚠️ The proxy is NOT an API surface: its capability-based auth exemption stays fenced to safe methods and non-route paths (`test/webview-auth-exemption.test.ts`). ⚠️ Iframes omit `allow-same-origin` unless `trusted`, and `Authorization`/`codeman_session` are stripped upstream in both modes. ⚠️ **Egress guard**: link-local and cloud-metadata targets are refused at save time, by a sync hostname check at each connect (IP literals skip DNS), AND on the resolved address (`webview-egress.ts`); use the `undici` package's own `fetch` + `Agent`, never Node's global fetch. ⚠️ Loopback links in agent output auto-open as proxied web tabs (`openLinkThroughWebTabIfLoopback`), but never auto-route `*.localhost` (prompt-injectable DNS). Capabilities are revoked on logout (`revokeOwner`). → [architecture-invariants#web-tabs](docs/architecture-invariants.md#web-tabs), `docs/web-tabs.md`
|
||||
|
||||
**Multi-user mode** (opt-in `--multiuser` / `CODEMAN_MULTIUSER=1`, OFF by default): named users with scrypt-hashed passwords in `~/.codeman/users.json`. Gated everywhere by `isMultiUserMode()`; when OFF, behavior is byte-identical to single-user because every scoping helper short-circuits. ⚠️ **Not a security boundary at the agent layer**: every session still runs as the SAME OS account. This separates WORKSPACES; it does not sandbox users (Docker cases are the isolation story). Ownership threads through `Session.owner` and is enforced in `findSessionOrFail`, list endpoints, SSE routing (fail-closed), WS, search, and file-preview. ⚠️ `settings.json` is ONE server-wide file, so every write to it is admin-only (`PUT /api/settings`, `/api/execution/model-config`, `/api/cases/order`, plus `PUT /api/config`: 403 `FORBIDDEN` before parsing), a non-admin's quick-start/Ralph start skips `lastUsedCase`, its GET hides `voiceSettings.apiKey`/`caseOrder`/`lastUsedCase`/`lastPickedCase`/`caseSettings` from a non-admin (`settingsForNonAdmin`), and the browser skips those writes for a non-admin via `_settingsReadOnly()` (settings-ui.js; also true once a write came back 403 `FORBIDDEN`, since `/api/me` can be slow or fail; their run mode and respawn presets stay per-device, `_applyOwnSettings`) (`test/routes/system-routes-settings-admin-only.test.ts`). System ops are admin-only too (`/api/system/update`, `/api/system/span-displays`, `/api/tunnel/qr/regenerate`, `/api/cleanup-state`), and a non-admin's `/api/auth/revoke` revokes only their own logins (`test/routes/system-routes-system-ops-admin-only.test.ts`). → [architecture-invariants#multi-user-mode](docs/architecture-invariants.md#multi-user-mode), `docs/multi-user-plan.md`
|
||||
**Multi-user mode** (opt-in `--multiuser` / `CODEMAN_MULTIUSER=1`, OFF by default): named users with scrypt-hashed passwords in `~/.codeman/users.json`. Gated everywhere by `isMultiUserMode()`; when OFF, behavior is byte-identical to single-user because every scoping helper short-circuits. ⚠️ **Not a security boundary at the agent layer**: every session still runs as the SAME OS account. This separates WORKSPACES; it does not sandbox users (Docker cases are the isolation story). Ownership threads through `Session.owner` and is enforced in `findSessionOrFail`, list endpoints, SSE routing (fail-closed), WS, search, and file-preview. ⚠️ `settings.json` is ONE server-wide file, so every write to it is admin-only (`PUT /api/settings`, `/api/execution/model-config`, `/api/cases/order`, plus `PUT /api/config`: 403 `FORBIDDEN` before parsing), a non-admin's quick-start/Ralph start skips `lastUsedCase`, its GET hides `voiceSettings.apiKey`/`caseOrder`/`lastUsedCase`/`lastPickedCase`/`caseSettings` from a non-admin (`settingsForNonAdmin`), and the browser skips those writes for a non-admin via `_settingsReadOnly()` (settings-ui.js; also true once a write came back 403 `FORBIDDEN`, since `/api/me` can be slow or fail; their run mode and respawn presets stay per-device, `_applyOwnSettings`) (`test/routes/system-routes-settings-admin-only.test.ts`). System ops are admin-only too (`/api/system/update`, `/api/system/span-displays`, `/api/tunnel/qr/regenerate`, `/api/cleanup-state`), and a non-admin's `/api/auth/revoke` revokes only their own logins (`test/routes/system-routes-system-ops-admin-only.test.ts`). **Trusted reverse-proxy sign-in** (experimental, opt-in `CODEMAN_TRUSTED_PROXY_SECRET_FILE`, `src/config/trusted-proxy.ts`): a same-host authenticating proxy signs requests in via `X-Codeman-Proxy-Secret` + `X-Codeman-User`. ⚠️ Never read or forward request headers ahead of the first auth hook (it deletes those two from every request), and never re-read the secret from the environment (the settings are read once and both variables deleted, since sessions inherit Codeman's env; a setup that cannot be used stops the start). → [architecture-invariants#multi-user-mode](docs/architecture-invariants.md#multi-user-mode), `docs/multi-user-plan.md`
|
||||
|
||||
**Away digest**: `GET /api/away-digest` aggregates what happened while you were away from the lifecycle log, run-summary events, live sessions, token stats, and recent subagents. Pure aggregator in `web/away-digest.ts`. ⚠️ Returns `{success:true,digest}`, a legacy raw-ish shape consistent with the other raw GET handlers in `system-routes.ts`; frontend and tests read `.digest`. → [architecture-invariants#away-digest](docs/architecture-invariants.md#away-digest)
|
||||
|
||||
@@ -303,7 +303,7 @@ The terminal provider scans `terminalLinkLine()`, which extends `terminalPathLin
|
||||
| **CSRF / Origin** | Always-on cross-site Origin guard on state-changing requests. **A missing Origin is allowed** so curl/CLI and hooks keep working. ⚠️ The body parser keeps `text/plain` RAW; auto-JSON-parsing it enabled simple-request CSRF |
|
||||
| **QR Auth** | Single-use 6-char tokens (60s TTL) for tunnel login. See `docs/qr-auth-plan.md` |
|
||||
| **Sessions** | 24h cookie (`codeman_session`), auto-extend, device context audit |
|
||||
| **Rate limit** | 10 failed auth/IP → 429 (15min decay). Multi-user mode instead checks 50/IP (`AUTH_IP_FAILURE_MAX`) and 10 per (username, IP) BEFORE the password, so past either even a correct password from that IP waits (the account still logs in from another IP), plus 10 per username AFTER it (429 to wrong guesses from any IP, never to a correct password). QR and hook-secret have separate buckets, so neither can lock out login |
|
||||
| **Rate limit** | 10 failed auth/IP → 429 (15min decay). Multi-user mode instead checks 50/IP (`AUTH_IP_FAILURE_MAX`) and 10 per (username, IP) BEFORE the password, so past either even a correct password from that IP waits (the account still logs in from another IP), plus 10 per username AFTER it (429 to wrong guesses from any IP, never to a correct password). A request with NO `Authorization` header (or an empty one, which carries no guess either) is never counted and always gets the 401 challenge (a 429 never re-prompts a browser); a malformed one is counted. QR, hook-secret and the trusted-proxy secret (multi-user, opt-in) have separate buckets, so none of them can lock out login |
|
||||
| **Hook bypass** | `/api/hook-event` + `/api/status-telemetry` skip Basic auth (localhost-only, schema-validated), but when auth is active the loopback bypass requires `X-Codeman-Hook-Secret` **unconditionally** (Codeman cannot detect a user's own loopback reverse proxy) |
|
||||
| **Lost-frame page** | The THIRD unauthenticated 200, beside the two hook routes, and the only one decided by request headers alone: a `GET`/`HEAD` carrying `Sec-Fetch-Dest: iframe\|frame`, `Accept: text/html` and mode `navigate` (or none), for a path that is NOT a registered route (never `/api/`, `/ws/`, `/q/`), is answered BEFORE the credential checks with the static web-tab recovery page (`lostWebviewFramePage`: no reflected input, `default-src 'none'` plus its own script hash, `no-store`). `/` is the one registered route also admitted, only when the request carries neither `codeman_session` nor `Authorization` (nothing in Codeman frames its own root; a sandboxed frame has neither), since the landing page masks to exactly `/` and its reload otherwise rendered Codeman inside the web tab. ⚠️ A non-browser client can set those headers, so an unauthenticated caller can tell a registered route (401) from a non-route (200) and enumerate the route table; accepted, the routes are public in `docs/api-reference.md`. Pinned by `test/webview-auth-exemption.test.ts` + `test/webview-lost-root-frame.test.ts` |
|
||||
| **Tunnel** | Enabling a tunnel **refuses** without a login (`CODEMAN_PASSWORD` or multi-user mode) unless exposure is acknowledged via `CODEMAN_ALLOW_UNAUTHENTICATED_TUNNEL=1` / `--allow-unauthenticated-tunnel` or the per-request `acknowledgeUnauthTunnel:true` action field (never persisted). `CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK` acknowledges the BIND only and never satisfies this guard (#706: `install.sh` writes it for every passwordless LAN install). The authorization is decided ONCE per request, running or not, and required again at the `start()` site: the settings-file awaits between them let a concurrent stop land, and an unauthorized enable never writes `tunnelEnabled:true`. With no login the browser asks before every enable (welcome link, tunnel panel, App Settings save that turns it on) through ONE helper, `_confirmTunnelEnable()` (settings-ui.js), which reads `loginConfigured` from `GET /api/tunnel/status` (computed in the route by the guard's own test, never in `TunnelManager`); the 403 handler is the fallback when that read fails |
|
||||
@@ -355,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
|
||||
@@ -373,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.
|
||||
|
||||
|
||||
+1323
File diff suppressed because it is too large.
Load diff
@@ -26,7 +26,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<strong>English</strong> • <a href="README.zh-CN.md">简体中文</a>
|
||||
<strong>English</strong> • <a href="README.zh-CN.md">简体中文</a> • <a href="README.ja.md">日本語</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -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)
|
||||
@@ -765,6 +765,7 @@ The web UI remains the primary surface; see **[docs/tui.md](docs/tui.md)** for t
|
||||
| `Alt/Option+[` / `Alt/Option+]` | Previous / next session |
|
||||
| `Alt/Option+1`-`Alt/Option+9` | Switch to tab N (physical keys, so macOS Option layouts work) |
|
||||
| `Alt/Option+B` | Collapse / expand the session sidebar (sidebar layout only) |
|
||||
| `Alt/Option+Shift+C` | Switch a local or Docker Claude session between Chat and Terminal view (not on phones; see [Settings Reference](docs/wiki/Settings-Reference.md)) |
|
||||
| `Ctrl+Shift+{` / `Ctrl+Shift+}` | Move active tab left / right |
|
||||
| `Ctrl/Cmd+C` | Copy selection, or interrupt when nothing is selected |
|
||||
| `Ctrl+Shift+C` | Copy selection (never interrupts) |
|
||||
|
||||
+2
-1
@@ -15,7 +15,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">English</a> • <strong>简体中文</strong>
|
||||
<a href="README.md">English</a> • <strong>简体中文</strong> • <a href="README.ja.md">日本語</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -762,6 +762,7 @@ Web UI 仍是主要界面;完整指南见 **[docs/tui.md](docs/tui.md)**(英
|
||||
| `Alt/Option+[` / `Alt/Option+]` | 上一个 / 下一个会话 |
|
||||
| `Alt/Option+1`–`Alt/Option+9` | 切换到第 N 个标签(按物理键位,macOS Option 布局也适用) |
|
||||
| `Alt/Option+B` | 折叠 / 展开会话侧边栏(仅侧边栏布局) |
|
||||
| `Alt/Option+Shift+C` | 在聊天视图和终端视图之间切换本地或 Docker 的 Claude 会话(手机上不可用;见 [Settings Reference](docs/wiki/Settings-Reference.md)) |
|
||||
| `Ctrl+Shift+{` / `Ctrl+Shift+}` | 将当前标签左移 / 右移 |
|
||||
| `Ctrl/Cmd+C` | 复制选中内容;未选中时中断代理 |
|
||||
| `Ctrl+Shift+C` | 复制选中内容(永不中断) |
|
||||
|
||||
@@ -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.1",
|
||||
"version": "1.52.1",
|
||||
"websiteUrl": "https://getcodeman.com",
|
||||
"repository": {
|
||||
"url": "https://github.com/Ark0N/Codeman",
|
||||
@@ -13,7 +13,7 @@
|
||||
{
|
||||
"registryType": "npm",
|
||||
"identifier": "aicodeman",
|
||||
"version": "1.51.1",
|
||||
"version": "1.52.1",
|
||||
"transport": {
|
||||
"type": "stdio"
|
||||
},
|
||||
|
||||
@@ -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',
|
||||
@@ -63,6 +66,7 @@ export const BROWSER_TEST_GLOBS = [
|
||||
'test/terminal-touch-swipe-axis.browser.test.ts',
|
||||
'test/phone-press-feedback.browser.test.ts',
|
||||
'test/desktop-connect-page.browser.test.ts', // no server: the page is served by request interception
|
||||
'test/desktop-tabs-pages.browser.test.ts', // no server: the pages are served by request interception
|
||||
'test/local-model-ui.browser.test.ts',
|
||||
'test/home-breakpoint-swap.browser.test.ts',
|
||||
'test/log-viewer-reconnect.browser.test.ts',
|
||||
|
||||
+102
-8
@@ -59,10 +59,13 @@ payload return `{ "success": true, "data": {} }`.
|
||||
> to 600 s. Proxy operators and HTTP clients with a global read timeout need to know
|
||||
> that before pointing them at Codeman.
|
||||
|
||||
⚠️ **A `401` is the one status that is not an envelope.** Authentication is rejected
|
||||
⚠️ **A `401` is not an envelope.** Authentication is rejected
|
||||
in a request hook, before any handler runs, and it replies with the bare string
|
||||
`Unauthorized` (`Unauthorized: hook secret required` on the hook path) plus
|
||||
`WWW-Authenticate: Basic realm="Codeman"`. There is no `success`, no `error`, and no
|
||||
`Unauthorized` plus `WWW-Authenticate: Basic realm="Codeman"` (on the hook path it is
|
||||
`Unauthorized: hook secret required`, without that header). With trusted-proxy sign-in on (experimental,
|
||||
see [Authentication](#authentication)) the same hook has more plain-text replies: a `401`
|
||||
without `WWW-Authenticate`, a `403` and a `503` for a refused proxy identity, and a `403`
|
||||
or `404` for a `/webview/` or `/html-view/` path without a live capability. There is no `success`, no `error`, and no
|
||||
`errorCode`, because the wrapping hook only wraps object payloads. So a client that
|
||||
pipes every response straight into a JSON parser dies with a parse error rather than
|
||||
reporting an auth failure, which is a confusing way to discover that a password is
|
||||
@@ -601,6 +604,26 @@ request returns. The capture runs synchronous tmux calls on the server; the
|
||||
| `lines=<n>` | With `full=1` only: read at most `<n>` lines of tmux history above the visible frame. An integer of at least 1, clamped to the configured history limit; absent or malformed, the whole limit (100,000 lines by default), as before. When a bound below the configured limit left older lines in tmux (its `history_size` is deeper), `truncated` is true with `truncationReason: 'tail'`; a byte cap still reports `'capped'`. Without it a full capture reads all of that history before `tail` cuts it, so a client that keeps a fixed number of lines (the tile grid sends its xterm's scrollback plus its rows) should send it. |
|
||||
| `alt=recording` | With `full=1` only: if the pane is in the alternate screen (a nested tmux, where tmux keeps no history, or any full-screen app such as vim or less while it is open), answer with the visible frame over the byte recording instead (`source: 'mux-visible'`, `tail` applied as without `full=1`). Shells' automatic loads send it. |
|
||||
|
||||
## Conversation reads for the chat view
|
||||
|
||||
### `GET /api/v1/sessions/:id/last-response?context=full`
|
||||
|
||||
With `context=full`, the response carries the whole conversation as `messages`. Each
|
||||
message read from a Claude transcript has `kind`, `label`, `role`, `text`, `turn` and,
|
||||
when known, `timestamp`. A prompt the user typed while Claude was working also carries
|
||||
`queued: true`. That reader also marks the turns that Codeman's prompt-cache
|
||||
keep-warm sent. The nudge prompt and the reply to it both carry `keepAlive: true`, so a
|
||||
client can leave them out as the chat view does. A prompt the user queued during that
|
||||
turn makes the turn theirs, and its later messages carry no flag.
|
||||
|
||||
A full read of a Claude transcript also starts a transcript watcher when none runs for
|
||||
the session. A watcher normally starts at the session's first hook or statusline report,
|
||||
so a session picked up after a server restart has none until one of those arrives. The
|
||||
read starts one from the file it found, and the session's `transcript:*` events then flow
|
||||
mid-turn. After a `/clear`, a read moves a watcher it started itself to the conversation's
|
||||
new file. It never replaces or moves a watcher that a hook or a statusline report started,
|
||||
and it starts none for a remote SSH session, whose transcript is not on this host.
|
||||
|
||||
## Experimental bounded agent inspection and guarded input
|
||||
|
||||
**Experimental:** `codeman agent inspect`, `stage` and `submit`, and their
|
||||
@@ -892,18 +915,63 @@ Beyond images, the route also accepts documents a user hands an agent to read,
|
||||
admitted by the name's extension (the Content-Type a phone attaches to a `.md`
|
||||
or `.csv` is unreliable): the office formats `.pdf`, `.docx`, `.pptx`, `.xlsx`,
|
||||
`.zip` and the text family `.txt`, `.md`, `.csv`, `.tsv`, `.json`, `.log`,
|
||||
`.yaml`, `.yml`, `.xml`. A document is buffered under the same 50 MB image cap,
|
||||
`.yaml`, `.yml`, `.xml`, `.html`, `.htm`. A document is buffered under the same 50 MB image cap,
|
||||
its bytes are checked against the extension (a magic-number signature, or UTF-8
|
||||
with no NUL byte for text) and answered 415 on a mismatch (for text, an `error`
|
||||
saying the file is not UTF-8 text, or UTF-16 text when it opens with a UTF-16
|
||||
byte order mark, and to save it as UTF-8), and it is saved under
|
||||
a sanitized stem of its name, so `Q3 report.pdf` is findable as
|
||||
`paste-<ms>-<hex>-Q3-report.pdf`. A named type that is neither an image nor a
|
||||
document (a script, an HTML page, a `.sh`) is refused 400 `Unsupported file
|
||||
document (a script: `.sh`, `.py`, `.js`) is refused 400 `Unsupported file
|
||||
type`. That refusal is a scope choice, not a security property: `file-raw`
|
||||
already serves non-media text inert (`text/plain`, `nosniff`), so this just
|
||||
keeps the server from storing what it would serve or an agent could run, and
|
||||
html and svg are the ones deliberately kept out.
|
||||
keeps the server from storing what an agent could run. `.html` and `.htm` are
|
||||
admitted and stay inert: `file-raw` serves them as `application/octet-stream`
|
||||
with `nosniff`, and `html-view` refuses a page under a dot-directory such as
|
||||
`.codeman-uploads`. That leaves svg as the markup type still kept out.
|
||||
|
||||
## Listing a directory (`GET /api/v1/sessions/:id/files?lazy=1`)
|
||||
|
||||
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=`)
|
||||
|
||||
@@ -976,7 +1044,8 @@ by the owner's decision the page may load from and send requests to any host), `
|
||||
`Referrer-Policy: no-referrer` and `Access-Control-Allow-Origin: *`. A `Range`
|
||||
request is answered with `206` + `Content-Range` (`416` past the end), like
|
||||
`file-raw`. Every refusal is a plain-text `404 Not found`; with a password set, an
|
||||
unknown or revoked capability is the auth hook's `401` instead.
|
||||
unknown or revoked capability is the auth hook's `401` instead. With trusted-proxy sign-in
|
||||
on it is the hook's plain-text `404`, with no challenge.
|
||||
|
||||
## Session lineage (`parentSessionId`)
|
||||
|
||||
@@ -1894,6 +1963,24 @@ Optional HTTP Basic (`CODEMAN_USERNAME`/`CODEMAN_PASSWORD`) → opaque
|
||||
`401 UNAUTHORIZED`; rate-limited requests get `429 RATE_LIMITED`. See
|
||||
[`security-architecture.md`](security-architecture.md).
|
||||
|
||||
**Trusted-proxy sign-in (experimental, multi-user mode, off unless a secret is
|
||||
configured).** An authenticating reverse proxy on the same host sends
|
||||
`X-Codeman-Proxy-Secret` and `X-Codeman-User` over loopback, and the request runs as that
|
||||
existing, enabled account. No cookie is issued, and `GET /api/me` reports
|
||||
`viaTrustedProxy: true`. The hook's refusals on this path are plain text, not envelopes:
|
||||
|
||||
| Status | When |
|
||||
|---|---|
|
||||
| `401`, no `WWW-Authenticate` | the secret is wrong, or the request did not arrive over loopback |
|
||||
| `403` | the secret is right, but there is no username or no enabled account with that name |
|
||||
| `503` | the user store cannot be read |
|
||||
| `429` | too many wrong secrets from one address |
|
||||
|
||||
With the feature on, a path under `/webview/` or `/html-view/` without a live capability is
|
||||
answered by the hook before any credential is looked at: plain-text `403` for a web tab,
|
||||
`404` for an HTML view, no challenge. See
|
||||
[`security-architecture.md` §10a](security-architecture.md).
|
||||
|
||||
## SSE event channel
|
||||
|
||||
`GET /api/events` is a Server-Sent Events stream (`text/event-stream`); each
|
||||
@@ -1903,6 +1990,13 @@ the stable contract — event names are not renamed without a major bump. An
|
||||
optional `?sessions=<id,...>` filter suppresses only the high-volume terminal
|
||||
stream; lifecycle/metadata events are delivered to all clients regardless.
|
||||
|
||||
### `transcript:update` (the chat view's re-read)
|
||||
|
||||
The server broadcasts `transcript:update` (`{ sessionId, timestamp }`) for a session whose
|
||||
transcript watcher runs, whenever new lines arrive in its transcript. It throttles the event
|
||||
to one per 750 ms per session. The first update after a quiet spell goes out at once, and a
|
||||
burst after it collapses into one trailing event.
|
||||
|
||||
### `sse:heartbeat` (liveness)
|
||||
|
||||
Every 15s the server writes a `sse:heartbeat` frame to every connected client:
|
||||
|
||||
@@ -20,6 +20,8 @@ Implementation detail extracted from `CLAUDE.md` so that file stays small enough
|
||||
|
||||
**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
|
||||
|
||||
**Reverse-proxy base path** (`--base-url` / `CODEMAN_BASE_URL`, default `/`; `src/config/base-path.ts` is the pure single-source, normalized to `''` for root or `/foo`): lets Codeman be mounted under a sub-path behind a proxy that **forwards the prefix unchanged** (does NOT strip it). Deliberately few choke points, mirrored ingress/egress:
|
||||
@@ -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`.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -636,6 +640,8 @@ Further detail: the refused egress targets are `169.254.0.0/16`, `fe80::/10`, `f
|
||||
|
||||
**Multi-user mode** (opt-in `--multiuser` / `CODEMAN_MULTIUSER=1`, OFF by default; shipped 1.5.0 via PR #161, design `docs/multi-user-plan.md`): named users with individually scrypt-hashed passwords in `~/.codeman/users.json` (via `src/user-store.ts`: atomic 0600 write, short-TTL cache, SERIALIZED read-modify-write so a fire-and-forget `touchLastLogin` can't clobber a concurrent route write, last-admin invariants). Gated everywhere by `isMultiUserMode()` (`src/config/multiuser.ts`); when OFF, behavior is byte-identical to single-user (all scoping helpers short-circuit). ⚠️ **Not a security boundary at the agent layer** — every session still runs as the SAME OS account; this separates WORKSPACES, it does not sandbox users (Docker cases are the isolation story). Auth: a PARALLEL async branch in `middleware/auth.ts` (single-user branch untouched) verifies `username:password` against the store, mints identity-carrying cookies (`AuthSessionRecord` gains `username`/`role`/`mustChangePassword`), decorates `req.authUser` (Fastify augmentation; single-user leaves it undefined and the ownership helpers default to a synthetic admin), enforces a per-username failure bucket + the `mustChangePassword` lockbox. Ownership threads through `Session.owner` (stamped from `req.authUser`/`job.owner` at every `new Session()`, round-tripped via `MuxSession.owner` on recovery); `findSessionOrFail(ctx,id,req)` does a NOT_FOUND owner check; list endpoints + `getLightState` + SSE (`deriveSseHint` routes session-scoped events by owner, fail-closed; machine-level + host-plan telemetry admin-only) + WS + search + file-preview all filter by owner. §6.3 permission policy: non-granted users are forced to `--permission-mode auto` (via `resolveClaudeModeForUser` at all spawn sites, incl. one-shots because `buildPromptArgs` now respects the session mode), and shell mode / cron `launchCommand` require the `canBypassPermissions` grant. Cases live in per-user `~/codeman-users/<name>/cases` (`resolveCasesDir`); a non-admin's `workingDir` is realpath-confined there; host CRUD is admin-only. Admin API `src/web/routes/admin-routes.ts` (`/api/admin/users*`, one-time passwords, audit log `admin-audit.jsonl`) + self-service `/api/me` + `/api/me/password` (`me-routes.ts`); frontend `public/admin-ui.js` (identity boot, change-password modal + interceptor, admin Users tab, and the header **Admin Panel** button `#adminPanelBtn`: ships `btn-admin-panel--hidden`, revealed for admins in multi-user mode, phone-hidden via mobile.css; opens the full Admin Panel modal with user CRUD, per-user permission toggles, and case-folder list/delete via `GET/DELETE /api/admin/users/:username/cases[/:caseName]`; live-refreshes on SSE `admin:usersChanged`, wired in app.js). CLI `codeman users add|passwd|list|rm`. Per-user session cap via `sessionCapacityState`/`sessionCapacityMessage`. Tests: `test/user-store.test.ts`, `test/multiuser-auth.test.ts`, `test/ownership-scoping.test.ts`, `test/admin-routes.test.ts`, `test/admin-ui.test.ts`.
|
||||
|
||||
**Trusted reverse-proxy sign-in** (experimental per `docs/versioning-policy.md`; opt-in `CODEMAN_TRUSTED_PROXY_SECRET_FILE` / `CODEMAN_TRUSTED_PROXY_SECRET`, multi-user only; `src/config/trusted-proxy.ts`, `registerTrustedProxyHeaderStrip` + `checkTrustedProxyIdentity` in `middleware/auth.ts`, full rules in `docs/security-architecture.md` §10a): a same-host authenticating proxy (oauth2-proxy, mod_auth_openidc, ...) presents `X-Codeman-Proxy-Secret` + `X-Codeman-User` and the request signs in as that EXISTING, enabled account. ⚠️ The headers are read and DELETED from every request by the first auth hook (right after the Host guard, every auth mode), before any exemption or route: the web-tab relay copies request headers, and must never see the secret. ⚠️ The secret is read ONCE at auth setup (before sessions are restored) and both variables are deleted from `process.env`, since every session inherits Codeman's env; don't add a code path that re-reads them from the env later (the secret file's path is kept in the module for `isSensitivePath`). ⚠️ A configured setup that cannot be used (unreadable, empty or group/other-readable file, short or non-ASCII secret, both variables, single-user mode, rejected header name) STOPS THE START; it is never silently off. The check is step 0 of the multi-user hook, BEFORE the cookie, and fail-closed: once the secret header is present (even empty), a wrong secret / non-loopback `req.ip` (401) or a missing, invalid, unknown or disabled username (403, no challenge) is refused and never falls through to cookie or Basic. The username is matched exactly (`normalizeUsername()` + the username rule, no other transformation); the loopback test is `isLoopbackIp`, shared with the hook-secret bypass. The secret is compared BEFORE the failure bucket (own per-IP `proxySecretFailures`), so a correct secret always passes and only failures are throttled. No cookie is minted. `req.authUser.viaTrustedProxy` skips the `mustChangePassword` lockbox and makes `GET /api/me` report `mustChangePassword: false`. ⚠️ The username header is removed from EVERY request, so `CODEMAN_TRUSTED_PROXY_USER_HEADER` is validated by shape (`X-…` or `Remote-User`, reserved names refused) and a rejected name stops the start; the configured name is also on the web-tab relay's drop list. With the feature configured, a `/webview/` or `/html-view/` request the capability exemptions don't let through is refused with the route's own 403/404 BEFORE the credential checks (`serveRefusedCapabilityPath`), by prefix on a normalised path (`capabilityPrefixOf`), not by token shape: the proxy lets those paths through without its sign-in, so they must never reach the Basic check, prompt or failure bucket. The configured secret file is on the `isSensitivePath` blocklist. Tests: `test/trusted-proxy-auth.test.ts`, `test/sensitive-path.test.ts`.
|
||||
|
||||
### Agent-created case marker
|
||||
|
||||
**Agent-created case marker** (`src/agent-case-marker.ts`): a case directory `POST /api/quick-start` **creates** for an agent-driven spawn gets a `.codeman-agent-case.json` marker, so the scratch workspaces a long orchestration leaves behind (one per worker, and deleting the session does not remove them) can still be told apart from the user's real projects months later. `GET /api/cases` publishes it as `agentCreated`; `GET /api/cases/agent-created` is the read-only cleanup listing, adding `inUse` (a live session's `workingDir` is that case) and `modifiedAt`; Add Case → Manage badges each one and offers a review-then-delete sweep. The signal is the skill preamble's `X-Codeman-Agent-Origin` header (or an `agentOrigin` body field), falling back to a RESOLVED `parentSessionId` — nothing in the browser UI sets lineage, so a create request naming its spawning session came from an agent by construction, and that fallback is what still labels workers spawned by a stale skill copy.
|
||||
@@ -824,6 +830,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.
|
||||
@@ -888,7 +920,7 @@ Two surfaces do not move with a worktree inside `workingDir`. The Git panel keep
|
||||
|
||||
⚠️ **Reads only on request, opt-in all the way down.** `server.ts` builds the `EditHistorySync` and hands it to the routes; its only own calls are `remove` (through `forgetEditHistory`, when the session's persisted record goes), `sweep` (startup) and `flushAll` (shutdown). No hook, no timer, no second watcher. The panel drives every read: `?sync=1` when it opens, and while it is open on that session a debounced (600 ms) re-read after a `transcript:tool_end` of an edit-capable tool (Edit, Write, MultiEdit, NotebookEdit, Bash, Agent, Task, SendUserFile), which the existing `TranscriptWatcher` already broadcasts, or the session's `session:idle` (the end of a turn, via `_onSessionIdle`; it also catches a background subagent that writes after the tool end that started it). Not `transcript:complete`: it fires on a `result` line, which claude's interactive transcript never has. A closed panel reads nothing and keeps no badge. Guarded by the "reads only on request" wiring test in `test/edit-history-sync.test.ts`.
|
||||
|
||||
⚠️ **Which transcript** (`resolveClaudeTranscript`). The main transcript is the path the session's `TranscriptWatcher` follows (the hook-reported `transcript_path`), so a session is read from where its claude really writes, whatever its `CLAUDE_CONFIG_DIR`. Without a watcher (server restarted, no hook since), `findClaudeTranscript()` looks for `<claudeSessionId|id>.jsonl` under `claudeProjectsDir(session.claudeConfigDir())`: the session's own override (#255, the same dir the relaunch pin checks), else the server's. A config dir set outside Codeman (a shell profile, a wrapper) is never guessed: until the next hook such a session answers `unavailable` / `no-transcript`, and the panel says so. Subagents are `<main path without .jsonl>/subagents/agent-<id>.jsonl`. A different main file (`/clear`, resume): the previous one, next to it in the same directory, is first read to its end with its subagents (over as many syncs as that takes), then the new one from its end with fresh cursors; the stored entries stay. "Load older" reaches back within the current conversation only, and reads the stored conversation's transcript while the switch is still pending.
|
||||
⚠️ **Which transcript** (`resolveClaudeTranscript`). The main transcript is the path the session's `TranscriptWatcher` follows (the `transcript_path` a hook or the statusline reported, or the file a full `last-response?context=full` read found, which the chat view and the Response Viewer's More button both make), so a session is read from where its claude really writes, whatever its `CLAUDE_CONFIG_DIR`. Without a watcher (server restarted, and no hook, statusline report or full read since), `findClaudeTranscript()` looks for `<claudeSessionId|id>.jsonl` under `claudeProjectsDir(session.claudeConfigDir())`: the session's own override (#255, the same dir the relaunch pin checks), else the server's. A config dir set outside Codeman (a shell profile, a wrapper) is never guessed: until the next hook or statusline report such a session answers `unavailable` / `no-transcript`, and the panel says so. Subagents are `<main path without .jsonl>/subagents/agent-<id>.jsonl`. A different main file (`/clear`, resume): the previous one, next to it in the same directory, is first read to its end with its subagents (over as many syncs as that takes), then the new one from its end with fresh cursors; the stored entries stay. "Load older" reaches back within the current conversation only, and reads the stored conversation's transcript while the switch is still pending.
|
||||
|
||||
⚠️ **Bounded reads.** A sync is at most `MAX_FORWARD_PASSES` (3) reads, each at most `READ_BUDGET_BYTES` (8 MiB) shared by the main transcript and all subagents (main first), plus up to 8 KiB of `meta.json` per subagent seen for the first time; a first read starts that far before the end. A file whose chunk the shared budget cut short is not applied but read in a later pass (the store would take a chunk with no line end for one line longer than the budget). "Load older" reads a full-budget block of up to `MAX_OLDER_SOURCES` (3) transcripts per click; with more, they take turns. A line longer than the budget is skipped, going forward and going back, and the line after (before) it is read whole. A subagent transcript that vanished loses its cursor, not its entries. Parsing happens in the request, line by line; nothing runs on the PTY data path. One sync per session at a time, and requests during a run fold into one more run. At most `MAX_LOADED_STORES` (3) stores stay in memory: past that the least recently used one without a run in flight is written (only if it changed) and dropped, and a later request loads it again after that write.
|
||||
|
||||
@@ -1083,7 +1115,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
|
||||
|
||||
@@ -1211,7 +1243,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).
|
||||
|
||||
@@ -1285,7 +1317,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.
|
||||
|
||||
@@ -1345,7 +1377,7 @@ Tests: `test/mobile-prompt-composer.test.ts` (in the CI gate, deliberately not u
|
||||
|
||||
### Z-index layers
|
||||
|
||||
**Z-index layers**: subagent windows (1000), split picker menu (1000, `.split-picker-menu`), Tiles count menu (1000, `.tile-count-menu`), the closing grid's still copy (`.tile-grid-ghosts`, z-index 3 inside `.main`, over the single view coming back; hidden under `.main.webview-active`), mobile/tablet fixed header (1200, `mobile.css`), modals on ≤768px (1300 — must beat the fixed header or the modal close button is buried), log viewers (2000), connection-loss overlay (2500, above the fixed header and modals), image popups (3000), response viewer (5000, backdrop 4999), folder grid (5090, `#folderGridOverlay` — above the response viewer a folder link opens it from, below the file preview its tiles open, so a tile's preview and its ←/→ paging sit on top of the grid), file-preview overlay (5100 — must outrank the response viewer, which can launch it; at its old 2000 a path clicked in the chat opened BEHIND the chat), toasts/path picker (10000+, deliberately above the preview), the custom-model center-status banner (10001, `.center-status-banner` — `[hidden]` must re-assert `display: none` over its own `display: flex`, same trap as `.home-sessions[hidden]`, or `dismiss()` leaves an invisible click-blocker dead centre on screen), the swap-confirm and context-warning modals (10010, `#customModelSwapConfirmModal`/`#customModelContextWarningModal` — must clear both the plain `.modal` z-index of 1000 and the center-status banner it can appear over), terminal touch-selection bar (900 — above terminal content and the local-echo overlay, deliberately BELOW floating agent windows so it can never cover their controls), local echo overlay (7), iOS IME composition preview (EFFECTIVE layer depends on its home: with local echo on it is part of the local echo overlay at 7, drawn by `setComposition()` as an underlined tail after the pending text; with local echo off it is a span at z-index 6 inside `.xterm-helpers`, but `.xterm-helpers` is its own z-index 5 stacking context, so the span's effective layer is 5. That is below the overlay's 7, which is why the span cannot be used while the overlay holds text: typed text never reaches the PTY before Enter, the PTY cursor that places the span stays at the prompt start, and the overlay's opaque line div covers it).
|
||||
**Z-index layers**: subagent windows (1000), split picker menu (1000, `.split-picker-menu`), Tiles count menu (1000, `.tile-count-menu`), the closing grid's still copy (`.tile-grid-ghosts`, z-index 3 inside `.main`, over the single view coming back; hidden under `.main.webview-active`), mobile/tablet fixed header (1200, `mobile.css`), modals on ≤768px (1300 — must beat the fixed header or the modal close button is buried), log viewers (2000), connection-loss overlay (2500, above the fixed header and modals), image popups (3000), response viewer (5000, backdrop 4999), folder grid (5090, `#folderGridOverlay` — above the response viewer a folder link opens it from, below the file preview its tiles open, so a tile's preview and its ←/→ paging sit on top of the grid), file-preview overlay (5100 — must outrank the response viewer, which can launch it; at its old 2000 a path clicked in the response viewer opened BEHIND the response viewer; DOCKED beside the terminal (the Codex files setting) it is `z-index: auto`, page content, since with nothing above it making a stacking context its 5100 would sit over every modal backdrop and the response viewer sheet), toasts/path picker (10000+, deliberately above the preview), the custom-model center-status banner (10001, `.center-status-banner` — `[hidden]` must re-assert `display: none` over its own `display: flex`, same trap as `.home-sessions[hidden]`, or `dismiss()` leaves an invisible click-blocker dead centre on screen), the swap-confirm and context-warning modals (10010, `#customModelSwapConfirmModal`/`#customModelContextWarningModal` — must clear both the plain `.modal` z-index of 1000 and the center-status banner it can appear over), chat view (20, `.chat-view`, covering the terminal inside `.terminal-wrap`) and its Chat / Terminal switch (21, `.chat-view-toggle`, above it), terminal touch-selection bar (900 — above terminal content and the local-echo overlay, deliberately BELOW floating agent windows so it can never cover their controls), local echo overlay (7), iOS IME composition preview (EFFECTIVE layer depends on its home: with local echo on it is part of the local echo overlay at 7, drawn by `setComposition()` as an underlined tail after the pending text; with local echo off it is a span at z-index 6 inside `.xterm-helpers`, but `.xterm-helpers` is its own z-index 5 stacking context, so the span's effective layer is 5. That is below the overlay's 7, which is why the span cannot be used while the overlay holds text: typed text never reaches the PTY before Enter, the PTY cursor that places the span stays at the prompt start, and the overlay's opaque line div covers it).
|
||||
|
||||
## Security layers
|
||||
|
||||
@@ -1359,7 +1391,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_*`) |
|
||||
@@ -1369,7 +1401,7 @@ Tests: `test/mobile-prompt-composer.test.ts` (in the CI gate, deliberately not u
|
||||
|
||||
### Buffers, uploads, and terminal history
|
||||
|
||||
Target: 20 sessions, 50 agent windows at 60fps. Limits in `src/config/`: terminal 32MB (see below), text 1MB, messages 1000, max agents 500, max sessions 50 (env `CODEMAN_MAX_SESSIONS`, 1 to 462), max SSE clients 100. **Terminal history** (`src/config/terminal-history.ts`, COD-80): tmux history-limit 100k lines, PTY buffer 32MB max / 24MB trim (env `CODEMAN_MAX_TERMINAL_BUFFER`/`CODEMAN_TRIM_TERMINAL_TO`; the env-derived trim is clamped ≤75% of max — trim ≥ max would disable `BufferAccumulator` trimming entirely = unbounded memory); browser xterm scrollback stays a separate hardcoded 50k (`DEFAULT_SCROLLBACK` in constants.js — 100k/tab is a mobile-memory hazard). tmux <3.7 allocates history at pane creation, so `createSession()` sets the global default in the same command queue immediately before `new-session`; tmux 3.7+ instead creates the session and targets only that pane, because changing the global option can resize and trim unrelated live panes. A settings change resizes tracked panes only on 3.7+ and otherwise affects future panes; no version can recover lines already evicted. Settings keys `terminalScrollbackLines`/`terminalBufferMaxBytes`/`terminalBufferTrimBytes` are schema-validated but inert (only `tmuxHistoryLimit` is wired); `buffer-limits.ts` re-exports the defaults. Text/message limits are env-overridable too (`CODEMAN_MAX_TEXT_OUTPUT`/`CODEMAN_TRIM_TEXT_TO`/`CODEMAN_MAX_MESSAGES`). **Image upload** (`image-input.js` / `config/buffer-limits.ts`): up to `_maxBatchImages` 20 images/batch (bounded concurrency 3), per-file `MAX_PASTE_IMAGE_BYTES` 50MB (env `CODEMAN_MAX_PASTE_IMAGE_BYTES`); the mobile camera-roll picker auto-downscales to fit before upload. A camera-roll VIDEO (`?kind=video` on the same route, set by the client from the file's MIME type) is never buffered: it streams to disk under `MAX_PASTE_VIDEO_BYTES` 1GB (env `CODEMAN_MAX_PASTE_VIDEO_BYTES`), sniffed from the stream's first bytes (ISO BMFF / QuickTime atom, EBML for webm, Ogg for ogv) and unlinked on any failure. The client keys the flag on the MIME type, falling back to the name's extension because some Android file managers hand over a File with none; that classifier (`_promptAttachKind()`, image-input.js) is the ONE filter every pick and paste surface reads: Attach, drop, the Compose and paste-dialog pickers and the clipboard handlers. They reach it through `_admitPromptAttachments()` (same file), which also toasts what a pick skipped: the count of a mixed pick's refused files, `Unsupported file type` when none pass, and nothing for a text paste. A new surface admits through that helper, never by filtering on `_promptAttachKind()` directly, or it silently drops files with no word to the user. ⚠️ The flag is the ONLY way onto that path and admits video types alone (the registry's `VIDEO_ATTACHMENT_EXTENSIONS`, single-sourced so an uploaded video also previews: mp4/webm/mov/m4v/ogv; 3gp/mkv are out), so an image can never ride the larger cap through memory; without it the route is byte-identical to the image-only version. A DOCUMENT (the office formats pdf/docx/pptx/xlsx/zip plus the text family txt/md/csv/tsv/json/log/yaml/yml/xml, the curated `ALLOWED_DOCUMENT_EXTS`, never `SUPPORTED_ATTACHMENT_EXTENSIONS` or `EDITABLE_EXTENSIONS`) is admitted by its name's extension and buffered like an image, judged on its bytes by the same fail-closed `imageMagicMatchesExt` (a magic-number signature, or UTF-8 without a NUL byte for the text family) and saved under a sanitized `[A-Za-z0-9._-]` stem of its name; sh/py/js/html are a deliberate SCOPE exclusion by extension (the server declines to store what `file-raw` would serve or an agent could run), not a content filter, since the agent can already write any of them. `_promptAttachKind()` returns `image`, `video` or `document`, and the server's dispatch mirrors it: an image MIME wins whatever the name says, a document extension takes the document branch, and a foreign extension with no image MIME is refused `Unsupported file type` only after the image sniff fails, so nothing the image path accepted by its bytes is lost. **HEIC paste uploads** (#151): converted server-side to JPEG in a `worker_threads` worker (`web/heic-jpeg-worker.ts`, resourceLimits + 30s timeout) gated by `runWithConversionLimit()`; detection is magic-byte based (covers Android/MIUI HEIFs mislabeled as JPEG); headers declaring > 64MP are rejected 415 BEFORE decode (decompression-bomb guard). Deps: `heic-decode` + `jpeg-js`. Use `LRUMap` for bounded caches, `StaleExpirationMap` for TTL cleanup. Anti-flicker pipeline: `docs/terminal-anti-flicker.md`.
|
||||
Target: 20 sessions, 50 agent windows at 60fps. Limits in `src/config/`: terminal 32MB (see below), text 1MB, messages 1000, max agents 500, max sessions 50 (env `CODEMAN_MAX_SESSIONS`, 1 to 462), max SSE clients 100. **Terminal history** (`src/config/terminal-history.ts`, COD-80): tmux history-limit 100k lines, PTY buffer 32MB max / 24MB trim (env `CODEMAN_MAX_TERMINAL_BUFFER`/`CODEMAN_TRIM_TERMINAL_TO`; the env-derived trim is clamped ≤75% of max — trim ≥ max would disable `BufferAccumulator` trimming entirely = unbounded memory); browser xterm scrollback stays a separate hardcoded 50k (`DEFAULT_SCROLLBACK` in constants.js — 100k/tab is a mobile-memory hazard). tmux <3.7 allocates history at pane creation, so `createSession()` sets the global default in the same command queue immediately before `new-session`; tmux 3.7+ instead creates the session and targets only that pane, because changing the global option can resize and trim unrelated live panes. A settings change resizes tracked panes only on 3.7+ and otherwise affects future panes; no version can recover lines already evicted. Settings keys `terminalScrollbackLines`/`terminalBufferMaxBytes`/`terminalBufferTrimBytes` are schema-validated but inert (only `tmuxHistoryLimit` is wired); `buffer-limits.ts` re-exports the defaults. Text/message limits are env-overridable too (`CODEMAN_MAX_TEXT_OUTPUT`/`CODEMAN_TRIM_TEXT_TO`/`CODEMAN_MAX_MESSAGES`). **Image upload** (`image-input.js` / `config/buffer-limits.ts`): up to `_maxBatchImages` 20 images/batch (bounded concurrency 3), per-file `MAX_PASTE_IMAGE_BYTES` 50MB (env `CODEMAN_MAX_PASTE_IMAGE_BYTES`); the mobile camera-roll picker auto-downscales to fit before upload. A camera-roll VIDEO (`?kind=video` on the same route, set by the client from the file's MIME type) is never buffered: it streams to disk under `MAX_PASTE_VIDEO_BYTES` 1GB (env `CODEMAN_MAX_PASTE_VIDEO_BYTES`), sniffed from the stream's first bytes (ISO BMFF / QuickTime atom, EBML for webm, Ogg for ogv) and unlinked on any failure. The client keys the flag on the MIME type, falling back to the name's extension because some Android file managers hand over a File with none; that classifier (`_promptAttachKind()`, image-input.js) is the ONE filter every pick and paste surface reads: Attach, drop, the Compose and paste-dialog pickers and the clipboard handlers. They reach it through `_admitPromptAttachments()` (same file), which also toasts what a pick skipped: the count of a mixed pick's refused files, `Unsupported file type` when none pass, and nothing for a text paste. A new surface admits through that helper, never by filtering on `_promptAttachKind()` directly, or it silently drops files with no word to the user. ⚠️ The flag is the ONLY way onto that path and admits video types alone (the registry's `VIDEO_ATTACHMENT_EXTENSIONS`, single-sourced so an uploaded video also previews: mp4/webm/mov/m4v/ogv; 3gp/mkv are out), so an image can never ride the larger cap through memory; without it the route is byte-identical to the image-only version. A DOCUMENT (the office formats pdf/docx/pptx/xlsx/zip plus the text family txt/md/csv/tsv/json/log/yaml/yml/xml/html/htm, the curated `ALLOWED_DOCUMENT_EXTS`, never `SUPPORTED_ATTACHMENT_EXTENSIONS` or `EDITABLE_EXTENSIONS`) is admitted by its name's extension and buffered like an image, judged on its bytes by the same fail-closed `imageMagicMatchesExt` (a magic-number signature, or UTF-8 without a NUL byte for the text family) and saved under a sanitized `[A-Za-z0-9._-]` stem of its name; sh/py/js are a deliberate SCOPE exclusion by extension (the server declines to store what an agent could run), not a content filter, since the agent can already write any of them; html/htm are admitted as AI-written specs and reports, the same job as a .md, and stay inert because file-raw serves them as `application/octet-stream` + `nosniff` and html-view refuses a page under a dot-directory such as `.codeman-uploads`. `_promptAttachKind()` returns `image`, `video` or `document`, and the server's dispatch mirrors it: an image MIME wins whatever the name says, a document extension takes the document branch, and a foreign extension with no image MIME is refused `Unsupported file type` only after the image sniff fails, so nothing the image path accepted by its bytes is lost. **HEIC paste uploads** (#151): converted server-side to JPEG in a `worker_threads` worker (`web/heic-jpeg-worker.ts`, resourceLimits + 30s timeout) gated by `runWithConversionLimit()`; detection is magic-byte based (covers Android/MIUI HEIFs mislabeled as JPEG); headers declaring > 64MP are rejected 415 BEFORE decode (decompression-bomb guard). Deps: `heic-decode` + `jpeg-js`. Use `LRUMap` for bounded caches, `StaleExpirationMap` for TTL cleanup. Anti-flicker pipeline: `docs/terminal-anti-flicker.md`.
|
||||
|
||||
**Prompt uploads live in `<workspace>/.codeman-uploads/`** (`POST /api/sessions/:id/paste-image`; the names live ONLY in `src/web/paste-image-gc.ts`): IN the workspace because that is the only path that resolves identically for a local agent and a container (only the workspace is bind-mounted, at the same absolute path; `~/.codeman` is not); hidden so it stays out of `git status` and the agent's view of the repository; FLAT because a nested `<workspace>/.codeman/` IS the data dir (`join(homedir(), '.codeman')`, `src/config/instance.ts`) when the workspace is the home directory, which nothing refuses; and self-ignoring through a `.gitignore` of `*` written once with `wx`, so a file already there is the user's and stays. The pre-move `.claude-images/` receives nothing but stays readable for one release: `UPLOAD_DIR_NAMES` lists both, the hourly sweep and the delete cleanup in `cleanupSession()` go through `uploadDirs()`, and the image watcher's ignore filter reads the names. ⚠️ `uploadDirs()` is async: the working directory is a user-chosen path, so it is probed BOUNDED first (`probePathKind()`, the #516 rule; `unknown` is skipped and never touched, the hourly sweep keeps the stall cap and `cleanupSession()` passes `pastCap`, since it acts on one path at the user's request), and the lstat and realpath after it are `fs.promises` calls, never sync, because the sweep runs 30 s after boot and hourly over every live session and a linked case on a dead mount would otherwise freeze the whole server. It returns only REAL directories (lstat at the leaf, so a planted `.codeman-uploads -> /other-case/.codeman-uploads` is never listed: `readdir` follows a link to a directory, and the sweep would otherwise age out the other case's uploads through it), none that is or contains `getDataDir()` (contrived, `CODEMAN_INSTANCE=uploads` makes `~/.codeman-uploads` the data dir of a home workspace and `CODEMAN_DATA_DIR` can point inside one, but it is one check next to a recursive delete; one strictly INSIDE the data dir is listed, since it only ever holds uploads and a workspace like the `~/.codeman/app` that `install.sh` clones would otherwise never have its uploads collected), and nothing for a remote (SSH) session, whose `workingDir` is the remote path and would otherwise name a same-named LOCAL directory for the sweep and the delete. The check is made when the directories are listed: a same-user process that swaps a listed directory for a link during the sweep's awaits is accepted (Node has no `openat()`, and that actor already writes anywhere this process can). The route refuses a remote (SSH) session with 400 before any disk touch: its `workingDir` is the remote path, so the file would land on THIS host where the agent cannot read it. ⚠️ And because a live session's workspace can go onto a network mount that later stops answering, the route probes `session.workingDir` BOUNDED (`probePathKind(..., { pastCap: true })`) before the first disk touch, refusing an `unknown` mount through `describeUnknownPath()` (OPERATION_FAILED) exactly as `POST /api/sessions` does, so a mount already unreachable cannot freeze a libuv worker on every upload (`ensureUploadDir()`'s own lstat/mkdir then start on a reachable path; a mount that dies between the probe and that write is the same residual race `POST /api/sessions` accepts, since a pre-check cannot bound the write that follows it). Tests: `test/paste-image-gc.test.ts`, `test/paste-image-dir-shared.test.ts`, the paste-image block of `test/routes/session-routes.test.ts`, `test/routes/session-create-unreachable-path.test.ts`.
|
||||
|
||||
@@ -1385,6 +1417,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
|
||||
@@ -1423,7 +1457,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.
|
||||
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
# Chat view: a rendered conversation as the main session view
|
||||
|
||||
## Goal
|
||||
|
||||
A Claude session should be readable the way the Claude Code web and desktop apps
|
||||
are: prose in a proportional font, markdown rendered, code in boxed blocks, and the
|
||||
page's own light or dark colours. Codeman should keep managing the session exactly
|
||||
as it does today. The agent still runs in its tmux pane, and only the way the
|
||||
browser shows that pane changes.
|
||||
|
||||
The Response Viewer already renders a conversation this way, and its output is the
|
||||
look to keep. Its problem is placement: it is a sheet the user opens on demand,
|
||||
it does not update while the agent works, and it cannot send a prompt. The chat
|
||||
view moves that same rendering into the main area, keeps it live, and puts a
|
||||
message box under it.
|
||||
|
||||
## What the user sees
|
||||
|
||||
Each Claude session gets two views of the same pane:
|
||||
|
||||
- **Chat** shows the conversation rendered by the Response Viewer's markdown
|
||||
pipeline, newest message at the bottom, with a message box underneath.
|
||||
- **Terminal** is today's xterm.js pane, unchanged.
|
||||
|
||||
A toggle switches between them, and a keyboard shortcut does the same. The choice
|
||||
is remembered per session on this device. The toggle floats at the top right of the
|
||||
terminal. A second per-device setting shows or hides it. It is hidden by default
|
||||
(owner decision for 1.52.1), so nobody sees the toggle without choosing it, and a user
|
||||
who wants it turns it on. The shortcut still switches views while the toggle is hidden. A per-device setting picks the view for every session
|
||||
this browser has no choice for yet, so a user who prefers chat never has to switch by
|
||||
hand. The setting defaults to Terminal. Chat replaces the main view and still sends
|
||||
some dialogs to the terminal in phase 1, so nobody gets it without choosing it.
|
||||
|
||||
Your own prompts show in full when they are short. A prompt longer than about 12
|
||||
lines, typically a pasted log or spec, shows its first 6 lines followed by
|
||||
"Show all (N lines)", so a long paste does not fill the screen between two
|
||||
answers. Keep-warm nudges are hidden, as Read My Mind already drops them, because
|
||||
Codeman sent them and you did not.
|
||||
|
||||
While the agent works, the chat view shows a status line under the last message.
|
||||
It names what the running tool works on, such as "Reading src/session.ts" or
|
||||
"Running npm test". A Bash call with a description shows the description, with the
|
||||
command on a second `$ …` line, as the CLI does. The status line can say this because
|
||||
`transcript:tool_start` carries `detail` and `command`, which `summarizeToolCall()` and
|
||||
`toolCallCommand()` in `src/tool-call-summary.ts` pick out of the call's input. Each
|
||||
block of Claude's answer appears as a rendered message as soon as Claude writes it to
|
||||
the transcript, so a long turn fills in while it runs.
|
||||
|
||||
While Claude Code compacts the conversation, the status line says "Compacting
|
||||
conversation". A compaction runs for a minute or more and writes nothing to the
|
||||
transcript until it ends. Claude Code then draws `✻ Compacting conversation… (12s)` as
|
||||
its working line, for `/compact` and for its own auto-compaction alike. The terminal
|
||||
stays attached under the chat view, so the chat view reads that line from the
|
||||
terminal's own buffer on each tick of the status line. Only Claude's newest row above
|
||||
its message box counts, so an answer that quotes the line does not.
|
||||
|
||||
Between turns, Claude can still run work in the background, such as a background
|
||||
shell or a monitor. The server reads that off Claude's screen as the session's
|
||||
`watching` value, and the status line then says so, for example "1 shell still
|
||||
running".
|
||||
|
||||
The chat view always shows the session's current conversation. After `/clear` it
|
||||
starts empty, as Claude itself does. Claude Code runs the statusline command about a
|
||||
second after a `/clear`, and its input names the new conversation and its transcript
|
||||
file. The statusline exporter posts that input to the server, which moves the session
|
||||
to the new conversation, so the chat view follows before the next prompt. A session
|
||||
without the exporter, such as a Docker session or any session while Plan Usage Limits
|
||||
is off, moves with its next prompt's hook. A session with neither moves when the chat
|
||||
view next reads its conversation, as described under How the view stays live.
|
||||
|
||||
## Where the conversation comes from
|
||||
|
||||
Claude Code writes every session to a transcript file, one JSON object per line.
|
||||
`GET /api/sessions/:id/last-response?context=full` already reads that file and
|
||||
returns the whole conversation as prompt and response messages, each tagged with
|
||||
its turn number. The Response Viewer's "More" button uses it today, so the chat
|
||||
view needs no new reader for its first version.
|
||||
|
||||
That reader keeps only text. It drops tool calls, tool results and thinking blocks,
|
||||
so in phase 1 the conversation shows prompts and answers only.
|
||||
|
||||
Phase 2 adds a turn's tool activity as one muted summary line, such as
|
||||
"Read 9 files · edited 2 · ran 3 commands". A busy turn makes dozens of calls, and
|
||||
a line per call would push the answer far down the page. Clicking the summary
|
||||
expands it to one line per call ("Read src/session.ts", "Ran npm test"), and each
|
||||
of those expands to show the call's input. For edits, the Edit history panel also
|
||||
shows the diffs.
|
||||
|
||||
The summary needs every call, so in phase 2 the parser emits a `tool` message for
|
||||
each `tool_use` block. The message type already exists: the DeepSeek transcript
|
||||
reader and the readers for the CLIs whose conversation Codeman reads from the pane
|
||||
emit it.
|
||||
|
||||
Parsing the whole file on every update would hold the server's event loop for over a
|
||||
second on a long conversation. So the server keeps each transcript's parse and the
|
||||
byte offset it reached, and a read parses only the bytes appended since the last one
|
||||
(`src/web/claude-response-transcript.ts`). Phase 3 adds a cursor, so the browser asks
|
||||
only for messages after the last one it has.
|
||||
|
||||
## How the view stays live
|
||||
|
||||
The server watches a Claude session's transcript. A watcher starts at the session's
|
||||
first hook or statusline report, and either one reports the transcript's path.
|
||||
Codeman installs those hooks in every Claude workspace unless `workspaceHooksEnabled`
|
||||
is off.
|
||||
|
||||
A session that sends neither a hook nor a statusline report has no watcher:
|
||||
|
||||
- a session the server picked up after a restart, until either one arrives;
|
||||
- a session with hooks switched off and no statusline exporter;
|
||||
- a Docker case whose hooks cannot reach the server.
|
||||
|
||||
For those, any full read of the conversation starts a watcher from the transcript that
|
||||
read found. A full read is `GET /api/sessions/:id/last-response?context=full`, which
|
||||
both the chat view and the Response Viewer's More button make. So these sessions
|
||||
also update mid-turn. After a `/clear`, a read moves a watcher it started itself to
|
||||
the conversation's new file, because no hook or statusline report will move it. The
|
||||
read never replaces or moves a watcher that a hook or a statusline report started,
|
||||
and it starts none for a remote session.
|
||||
|
||||
The watcher emits `transcript:update` whenever new lines arrive. The server
|
||||
broadcasts it as an SSE event, throttled to one per 750 ms per session, so the
|
||||
browser learns of each new message while a turn is still running.
|
||||
|
||||
The chat view also listens for these events:
|
||||
|
||||
- `transcript:tool_start` drives the status line, because it carries the tool's
|
||||
`detail` and, for a described Bash call, its `command`. With parallel tool calls,
|
||||
the matching `transcript:tool_end` fires once, so the status line shows the most
|
||||
recent tool rather than counting calls.
|
||||
- `session:working` and `session:idle` mark the start and end of a turn. They come
|
||||
from Codeman's idle detection, not from hooks, so they also work where no
|
||||
transcript watcher runs.
|
||||
|
||||
`transcript:complete` does not help here. It fires only for a `result` row, and an
|
||||
interactive Claude transcript has none.
|
||||
|
||||
A Docker case reports the transcript's path inside the container
|
||||
(`/home/agent/.claude/projects/...`), which does not exist on the host. The case mounts the
|
||||
host's `~/.claude/projects` at that folder, so `hostTranscriptPath()`
|
||||
(`claude-conversation-report.ts`) maps the reported path to the host's copy before the
|
||||
watcher starts, and such a session gets the same mid-turn `transcript:update` events as a
|
||||
local one. A reported path outside that folder, or one with a `..` segment, is kept as
|
||||
reported. The host cannot open it, so that session refetches on `session:working` and
|
||||
`session:idle` alone and updates only at the start and end of each turn.
|
||||
|
||||
## How the user sends a prompt
|
||||
|
||||
The message box is a multiline text area. On a desktop, Enter sends and
|
||||
Shift+Enter adds a line. On a touch device the Send button sends, and so does
|
||||
Ctrl+Enter or Cmd+Enter from a hardware keyboard. Plain Enter adds a line there, as
|
||||
in the phone's Compose dialog.
|
||||
|
||||
A send posts the text and its Enter as one input to `POST /api/sessions/:id/input`
|
||||
with `useMux: true`. The server then pastes the text through tmux, presses Enter,
|
||||
and arms its submit check. That check re-presses Enter while the prompt still sits
|
||||
in Claude's composer, which Claude 2.1.277 and later cause by ignoring Enter for 30
|
||||
to 50 seconds after the composer appears.
|
||||
|
||||
The browser's WebSocket input channel cannot do this. It writes raw bytes straight
|
||||
into the pane and never reaches the tmux path, whatever the frame asks for. So the
|
||||
chat view does not use it for prompts, even though that channel queues input
|
||||
across a dropped connection.
|
||||
|
||||
Each request carries a client id, made once per page load, and a sequence number.
|
||||
A request that fails on the network, or that the server answers with a 5xx error,
|
||||
is retried with the same pair, so the server applies it once. A request the server
|
||||
refuses with a 4xx status is not retried, and the text stays in the message box.
|
||||
|
||||
The submit check cannot always recognise a multi-line prompt in the composer. So a
|
||||
long paste sent in the 30 to 50 seconds after Claude's composer appears can still
|
||||
strand.
|
||||
|
||||
Claude Code stores a pasted prompt inside a `<pasted_content>` tag, and every
|
||||
multi-line prompt sent through tmux is a paste. The chat view unwraps that tag
|
||||
before rendering, or the markdown renderer would run the lines together.
|
||||
|
||||
The box also gets these controls:
|
||||
|
||||
- A stop button sends Esc, which interrupts the current turn.
|
||||
- An attach button, drag-and-drop and pasting a screenshot or file into the message
|
||||
box all reuse the existing prompt upload route. The uploaded files' paths go into
|
||||
the chat message box, using the upload code's existing option to return paths
|
||||
instead of typing them into the pane. A paste that carries no file the attach rules
|
||||
admit stays a plain text paste.
|
||||
- A slash command is sent as text, and the conversation shows it as typed
|
||||
(`/dual-review`), not as the tags Claude Code records it with. A skill's body,
|
||||
which Claude Code adds as a hidden row, stays out. Claude Code records `/compact`
|
||||
only when its turn ends, so the sent copy stays drawn while that turn runs. A
|
||||
skill's row arrives as its turn starts, followed at once by the hidden body row,
|
||||
and that row takes the sent copy's place then. A command that runs no turn and is
|
||||
never recorded goes from the thread after four seconds.
|
||||
- Some slash commands typed with nothing after them get special handling in the chat view:
|
||||
- `/quit` and `/exit` close the session at once, as the tab's close button does,
|
||||
rather than waiting for the agent to exit and the server to notice.
|
||||
- `/clear` empties the thread at once. Claude Code starts a new conversation file,
|
||||
and the server moves to it when the statusline reports it, about a second later.
|
||||
A session without the exporter moves later, as described at the end of What the
|
||||
user sees. Until then the chat view leaves out every message no newer than the
|
||||
newest one it drew before `/clear`.
|
||||
- A built-in that opens a picker or a panel inside Claude's interface, such as a
|
||||
bare `/model` or `/config`, shows the terminal, with a note that Alt+Shift+C
|
||||
goes back. The session's remembered choice of view does not change. The server
|
||||
marks those commands (`opensTerminal` in the `/` menu's list).
|
||||
|
||||
The terminal stays mounted and attached while Chat shows. The chat view is a layer
|
||||
over the terminal's area, so the terminal keeps its size and switching views never
|
||||
resizes the pane. The stop button uses the terminal's connection to send Esc. Any
|
||||
focus that lands on the hidden terminal moves to the message box, so keys never
|
||||
reach the pane unseen.
|
||||
|
||||
## What else the message box shows
|
||||
|
||||
The message box also carries three things the terminal shows around Claude's
|
||||
composer.
|
||||
|
||||
- **A `/` menu.** Typing `/` at the start of the box opens a menu of slash commands,
|
||||
fed by `GET /api/sessions/:id/slash-commands`. The list merges three sources:
|
||||
Claude Code's built-in commands, the skills and prompt commands that the
|
||||
transcript's `skill_listing` rows name, and the skills and commands on disk. The server reads those files from
|
||||
the workspace's `.claude` folder and the user's Claude config folder, and every
|
||||
read is bounded. For a Docker session it reads only the workspace's `.claude`
|
||||
folder, because that session's config folder is the container's. Picking a row
|
||||
puts `/<name> ` in the box and sends nothing.
|
||||
- **The statusline.** Claude Code draws the user's statusline under its composer,
|
||||
and the chat view draws the same text under the message box. Codeman's statusline
|
||||
exporter wraps the user's own statusline command. Its V5 script prints that
|
||||
command's output unchanged and posts a base64 copy of it as `rendered`. The server
|
||||
keeps only the text, line breaks and colours, and broadcasts each change as
|
||||
`session:statusLine`. A user without a statusline of their own sees Codeman's footer.
|
||||
Claude Code does not run the statusline command while a session sits idle, so the
|
||||
server restores the last text after a restart, and an idle session keeps its statusline.
|
||||
- **The suggested next prompt.** After a turn ends, Claude Code may draw a predicted
|
||||
next prompt, faint, in its empty composer. It writes that prediction nowhere else,
|
||||
so `src/web/prompt-suggestion-reader.ts` reads it off the pane three times, at
|
||||
about 1.5, 4 and 10 seconds after the turn ends. It reads nothing while no browser
|
||||
is connected to the server. The chat view shows it as the box's placeholder, and Tab in
|
||||
the empty box fills it in. A suggestion is never sent without the user.
|
||||
Each read is a synchronous tmux capture that blocks the server's event loop, and
|
||||
so are the reads of the submit verifier, the idle probe and keep-warm. Moving every
|
||||
one of those screen reads to an async capture is a follow-up.
|
||||
|
||||
## Dialogs and questions
|
||||
|
||||
Claude sometimes stops to ask: a permission prompt, an AskUserQuestion with
|
||||
options, a plan approval. The question appears in the transcript as a tool call,
|
||||
but the dialog that answers it exists only in the pane.
|
||||
|
||||
Codeman's Approvals Inbox already detects these through Claude's hooks, reads the
|
||||
options from the pane, and answers them with `POST /api/approvals/:id/answer`.
|
||||
Its store runs even while the inbox setting is off. In phase 2 the chat view shows a
|
||||
pending item for its session as a card at the bottom of the conversation, with one
|
||||
button per option. A click goes through the same answer route, which re-reads the pane
|
||||
before it types anything.
|
||||
|
||||
The pane can also need attention in ways the inbox cannot parse. For those, the
|
||||
chat view shows a notice that says "Claude is waiting for your answer in the
|
||||
terminal." and offers a button that switches to the terminal view.
|
||||
|
||||
In phase 1, the `permission_prompt` and `elicitation_dialog` hooks raise that notice,
|
||||
and the answer cards follow in phase 2. While the notice shows, the message box sends
|
||||
nothing and keeps its text. A send then would type into the dialog, and its Enter could
|
||||
pick the highlighted option. A session without working hooks gets neither the notice
|
||||
nor the send block: its hooks are switched off, or it is a Docker case whose hooks
|
||||
cannot reach the server. A send there can still type into a dialog. Covering those
|
||||
sessions needs a read of the screen, because the Approvals Inbox behind the phase 2
|
||||
cards is fed by the same hooks. Dialogs are rare enough for this order. Codeman starts
|
||||
Claude with `--dangerously-skip-permissions` by default, so a session stops only for
|
||||
Claude's own questions and plan approvals. A session started in another
|
||||
permission mode stops for every permission prompt and sends each one to the
|
||||
terminal until phase 2.
|
||||
|
||||
## Scope
|
||||
|
||||
The first version covers local and Docker Claude sessions in the single main view.
|
||||
Remote (SSH) and adopted sessions keep the terminal, even an adopted session that
|
||||
runs on this machine, because Codeman cannot name an adopted session's transcript.
|
||||
Tiles in the tile grid and the second pane of a split stay terminals. Phones keep
|
||||
the terminal until phase 3. The chat view is not offered on a handheld device, whatever
|
||||
its orientation, so a phone turned to landscape keeps the terminal too.
|
||||
|
||||
Docker Claude sessions read their transcripts through the same route, because
|
||||
the container bind-mounts the host's `~/.claude/projects`. That works only when the
|
||||
folder existed when the container was created. It also works only while the server
|
||||
runs without `CLAUDE_CONFIG_DIR`. With that variable set, the route reads
|
||||
`$CLAUDE_CONFIG_DIR/projects`, which the container does not mount. A Docker session
|
||||
whose hooks cannot reach the server updates mid-turn once a full read has started its
|
||||
watcher. That read comes from the chat view or the Response Viewer's More button, as
|
||||
described under "How the view stays live".
|
||||
|
||||
Remote SSH sessions are not covered. The route reads the local projects folder,
|
||||
and a remote session's transcript lives on the remote host. The Edit history panel
|
||||
already reads remote transcripts over its bounded ssh path, and phase 3 can reuse
|
||||
it.
|
||||
|
||||
Codex and DeepSeek Harness also write structured transcripts, which Codeman
|
||||
already reads, so they can follow in phase 3. OMP writes a structured transcript as
|
||||
well, and Codeman reads it for the session history list. The conversation route has
|
||||
no OMP reader yet, so OMP can follow once that route reads its transcript. Every
|
||||
other CLI keeps the terminal view for now, and its toggle is hidden. For the CLIs without a structured transcript, Codeman reads the conversation
|
||||
off the screen, which is too coarse for a main view, or cannot read it at all.
|
||||
|
||||
The agent keeps running in its tmux pane, and respawn, Ralph, auto-compact and the
|
||||
other server features work as they do now. The chat view adds no hook to the
|
||||
workspaces Codeman installs hooks in, and changes nothing in a session whose chat view
|
||||
is off.
|
||||
|
||||
## Phases
|
||||
|
||||
1. **Live chat view**, in five steps that each work on their own:
|
||||
1. **Read.** Add the Chat/Terminal toggle, the setting that hides it and the
|
||||
default-view setting. Broadcast transcript updates as a throttled SSE event,
|
||||
render the full conversation with the Response Viewer's pipeline, and refetch it
|
||||
on transcript and session events. Show a working status line, the "waiting for
|
||||
your answer in the terminal" notice with its switch button, and follow `/clear`
|
||||
through the statusline. Typing still happens in the terminal.
|
||||
2. **Write.** Add the message box with send, stop and attach.
|
||||
3. **Slash commands.** Add the `/` menu, draw a typed slash command as typed, and
|
||||
handle `/clear`, `/quit`, `/exit` and the picker commands.
|
||||
4. **What Claude is doing.** Name the running tool in the status line, say when
|
||||
Claude compacts or still runs background work, and show the suggested next
|
||||
prompt as the message box's placeholder.
|
||||
5. **The statusline** under the message box.
|
||||
2. **Dialogs and tool activity.** Show approval cards inline. Extend the transcript
|
||||
parser with tool messages and render each turn's calls as one expandable
|
||||
summary line.
|
||||
3. **Scale and reach.** Add incremental fetching with a cursor. Extend the view to
|
||||
remote SSH sessions, Codex and DeepSeek Harness, and lay it out for phones,
|
||||
where the chat view could replace the terminal and accessory bar entirely.
|
||||
@@ -298,6 +298,12 @@ The allowlist is not a formality. If a branch is about what a CLI can DO it belo
|
||||
|
||||
This matters because it is invisible when it is wrong. `capabilities.privilegedParams[].param` is the multi-user bypass clamp's only handle on a CLI's privilege switch, and a name from the wrong namespace clamps **nothing**: no load error, no failing test, the clamp simply stops running. Codex is the entry where the two names differ (`bypassApprovals` as the param, `dangerouslyBypassApprovals` on the wire), so it is the one that catches a regression. `schema.ts` rejects any entry naming a param it never declared, on both `configSetenv.fromParam` and `privilegedParams.param`.
|
||||
|
||||
## A server that runs as root (`rootValue`)
|
||||
|
||||
An `enum` launch param may declare `rootValue`: a map from a value to the value it takes instead when the Codeman **server process** runs as uid 0 and the launch is **local**, where the CLI is the server's child and so runs as root too. Claude declares the one entry there is, `claudeMode: { 'dangerously-skip-permissions': 'normal' }`, because Claude Code exits on `--dangerously-skip-permissions` under root and that mode is the default: on a server installed as root (a VPS, an LXC container) every local Claude session was a dead pane. It is the host-level form of `overlays.docker.rootCommand`, which answers the same refusal by the container's uid.
|
||||
|
||||
`applyRootValues()` (`root-launch.ts`, pure) rewrites the param values before the argv engine sees them and hands back the object it was given when nothing changes, so a launch that is not root is byte-identical. The uid is asked at call time through `serverRunsAsRoot()` (`utils/server-uid.ts`; under vitest it answers `false` unless a test stubs it), and only by the local launch sites: `serverRootSpawnOptions()` for the two tmux launches (`createSession`, `respawnPane`) and `buildPermissionArgs()` for the direct-PTY fallback and the one-shot run. Remote and Docker pane commands never read it. Each swap is logged once per launch. The schema requires every key and every replacement to be one of the param's `values`, and refuses a replacement that is itself replaced. Tests: `test/root-launch.test.ts`.
|
||||
|
||||
## Fields declared for later
|
||||
|
||||
`accent`, `capabilities.echo`, `capabilities.keyboardAccessory` and `capabilities.maxFrameBytes` are **declared but not yet read**. (`shortBadge` was on this list until the CLI management list in Settings started showing it, and `capabilities.wheelForward` until the browser's wheel gate started reading it, see below.) They all describe frontend behaviour, and the frontend is deliberately untouched here: `app.js`, `terminal-ui.js` and `styles.css` keep their own hand-authored per-CLI rules, and moving them is its own piece of work verified by a browser/mobile suite the CI gate cannot see.
|
||||
|
||||
@@ -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).
|
||||
@@ -184,11 +184,11 @@ All handlers: multi-user mode only (404 otherwise), `requireAdmin`, Zod schemas
|
||||
| `GET /api/admin/users` | List users + stats: role, disabled, createdAt, lastLoginAt, live session count, case count, space disk usage (best-effort async walk, cached 60s), active cookie-session count |
|
||||
| `POST /api/admin/users` | Create: `{ username, role, password? }`. No password given: generate a one-time password, return it ONCE in the response, set `mustChangePassword` |
|
||||
| `PATCH /api/admin/users/:username` | `{ role?, disabled?, canBypassPermissions? }`. Demoting/disabling the last enabled admin: 409 `LAST_ADMIN`. Disable also revokes cookie sessions. `canBypassPermissions` is the section 6.3 grant (default false) |
|
||||
| `POST /api/admin/users/:username/reset-password` | Generates one-time password (returned once), sets `mustChangePassword`, revokes cookie sessions |
|
||||
| `POST /api/admin/users/:username/logout` | Revoke all cookie sessions for that user. Honest limit under Basic auth: the browser silently re-sends cached credentials and gets a fresh cookie on the next request, so logout only truly ends QR-issued sessions; to actually lock someone out, disable the account or reset the password. Say so in the panel tooltip until Phase 6 |
|
||||
| `POST /api/admin/users/:username/reset-password` | Generates one-time password (returned once), sets `mustChangePassword`, revokes cookie sessions. Does not end a trusted-proxy sign-in, which uses no password and holds no cookie |
|
||||
| `POST /api/admin/users/:username/logout` | Revoke all cookie sessions for that user. Honest limit under Basic auth: the browser silently re-sends cached credentials and gets a fresh cookie on the next request, so logout only truly ends QR-issued sessions; to actually lock someone out, disable the account or reset the password. For a person who signs in through a trusted reverse proxy, neither logout nor a reset ends access (no cookie, no password): disable or delete the account. Say so in the panel tooltip until Phase 6 |
|
||||
| `DELETE /api/admin/users/:username` | `{ deleteSpace?: boolean }` (default false). Refuses last admin. Kills the user's live sessions first (normal kill flow, incl. docker/remote teardown per case), revokes cookies, removes from store. With `deleteSpace`: guarded recursive delete of `~/codeman-users/<username>` (realpath must be inside `USER_SPACES_DIR`, top-level dir must not be a symlink), plus their registry entries and push subscriptions |
|
||||
| `POST /api/admin/cases/assign` | Move a legacy `~/codeman-cases/<case>` into a user's space (`fs.rename`) |
|
||||
| Self-service `GET /api/me` | `{ username, role, mustChangePassword }` (works in single-user mode too: synthetic admin; the frontend uses it to decide whether to render admin UI) |
|
||||
| Self-service `GET /api/me` | `{ username, role, mustChangePassword, multiUser, viaTrustedProxy }` (works in single-user mode too: synthetic admin without `viaTrustedProxy`; the frontend uses it to decide whether to render admin UI). For a trusted-proxy sign-in `viaTrustedProxy` is `true` and `mustChangePassword` is reported as `false` |
|
||||
| Self-service `POST /api/me/password` | `{ currentPassword, newPassword }`, verifies current, min length 8, revokes other sessions, clears `mustChangePassword` |
|
||||
|
||||
**Audit log**: append-only `~/.codeman/admin-audit.jsonl` (same idiom as `session-lifecycle.jsonl`): timestamp, acting admin, action, target, request IP. User management without an audit trail is not acceptable even for a homelab tool.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -590,6 +600,156 @@ Full feature guide: [`docker-cases.md`](docker-cases.md).
|
||||
- **Clone Repo does not lend the server's git sign-in to non-admins.** A clone writes only inside the caller's own case space, so it is not admin-gated, but the server account's git credential helpers (the Docker image's opt-in `gh`/`az` helpers, or any `gh auth setup-git`) are shared by every user. A non-admin's clone and preflight therefore run with `git -c credential.helper=`, which empties the helper list including the URL-scoped entries (`cloneWithoutCredentialHelpers` in `case-routes.ts`, argv pinned in `test/git-clone.test.ts`). This closes the Clone Repo path only: the account's SSH keys still apply to an `ssh://` URL, and a non-admin's agent sessions run as the same account, consistent with the first bullet above. Docker cases are a second route to the same sign-in: with `CODEMAN_AGENT_IMAGE_INSTALL_GH`/`_AZ` on, a non-admin's Docker case with credential seeding on (the default) receives a copy of the server account's `gh`/`az` sign-in, exactly as it receives the Claude and Codex credentials.
|
||||
- **Admin actions are audited** append‑only to `~/.codeman/admin-audit.jsonl` (acting admin, action, target, IP). Passwords set by an admin create/reset are one‑time (returned once, force change). Under Basic auth, `logout` only truly ends QR‑issued sessions — to lock someone out, disable the account or reset the password (a proper login form is a deferred Phase 6).
|
||||
|
||||
### Trusted reverse‑proxy sign‑in (opt‑in, multi‑user only)
|
||||
|
||||
A shared secret lets an authenticating reverse proxy on the same host (oauth2‑proxy behind
|
||||
Caddy or nginx, Apache `mod_auth_openidc`, Authelia, …) sign people in through an identity
|
||||
provider such as Entra ID, Google or Keycloak, in place of the Basic prompt. Source:
|
||||
`src/config/trusted-proxy.ts`, `checkTrustedProxyIdentity` and
|
||||
`registerTrustedProxyHeaderStrip` in `middleware/auth.ts`; tests in
|
||||
`test/trusted-proxy-auth.test.ts`; a worked Caddy + oauth2‑proxy setup in
|
||||
[`docs/wiki/Multi-User-Mode.md`](wiki/Multi-User-Mode.md#single-sign-on-through-a-reverse-proxy).
|
||||
|
||||
**Experimental** ([versioning-policy.md](versioning-policy.md)): the three settings, the two
|
||||
headers and the `viaTrustedProxy` field of `GET /api/me` may change until they are promoted
|
||||
by an explicit decision.
|
||||
|
||||
"Trusted proxy" names this sign-in only. It is not forwarded-address trust: Codeman still
|
||||
does not read `X-Forwarded-For`, `trustProxy` stays `false`, and `req.ip` stays the socket
|
||||
peer (§3).
|
||||
|
||||
- **What the proxy sends.** After it has authenticated the person, the proxy adds
|
||||
`X-Codeman-Proxy-Secret: <secret>` and `X-Codeman-User: <codeman username>`. It must
|
||||
delete both headers from the incoming client request first. The username header can be
|
||||
renamed with `CODEMAN_TRUSTED_PROXY_USER_HEADER`, but only to an `X-…` extension header
|
||||
or `Remote-User`, never a reserved one (`X-Forwarded-For/Host/Proto/…`, `X-Real-IP`,
|
||||
`X-Codeman-*`, CSRF/method-override headers; `X-Forwarded-User/Email/Preferred-Username`
|
||||
are allowed): the header is removed from every request, so it must not be one anything
|
||||
else needs. A rejected name stops the start (see below), so it is never removed.
|
||||
- **The secret.** At least 32 printable ASCII characters, from
|
||||
`CODEMAN_TRUSTED_PROXY_SECRET_FILE` (preferred: a 0600 file, so only a path is in the
|
||||
environment, like the hook secret's `CODEMAN_HOOK_SECRET_FILE`) or
|
||||
`CODEMAN_TRUSTED_PROXY_SECRET`. It is read once at auth setup, before any session is
|
||||
spawned or restored, and both variables are then deleted from `process.env`, because
|
||||
every session inherits Codeman's environment. That keeps them out of child processes
|
||||
and nothing more: an inline secret stays visible in `/proc/<pid>/environ` for the life
|
||||
of the server. A tmux server
|
||||
that an earlier Codeman started with the variable set keeps its own copy of that
|
||||
environment until it is restarted. A configured setup that cannot be used stops the start
|
||||
with a message that says why, as the first boot without users does: a secret file that
|
||||
is unreadable, empty, or readable by group or others (the mode is not checked on
|
||||
Windows); a short or non-ASCII secret; both
|
||||
variables set; a secret set in single-user mode; a rejected username header name. The
|
||||
length floor matters because a correct secret is never refused, so the limiter only
|
||||
turns a `401` into a `429` and the secret's entropy is what slows a guesser. The configured file (any name) and
|
||||
`~/.codeman*/proxy-secret` are on the `isSensitivePath` blocklist, so downloads and
|
||||
attachments refuse them.
|
||||
- **What the secret separates.** Every local process reaches the loopback port, so
|
||||
loopback alone proves nothing; the secret is what a local process lacks. It is not a
|
||||
boundary against code that can read the secret file or Codeman's memory, i.e. anything
|
||||
running as Codeman's OS account, which includes every agent session (the multi‑user
|
||||
threat model at the top of §10a: sessions share that account). Said plainly: any session that
|
||||
runs as Codeman's OS account can read the secret and sign in as anyone, an admin
|
||||
included, over loopback. That is the same class as editing `users.json`, which that
|
||||
account can also do.
|
||||
- **When Codeman believes it.** Only when ALL hold: multi‑user mode is on; a valid secret
|
||||
is configured; the request arrives on a **loopback socket** (`req.ip`, which ignores
|
||||
`X‑Forwarded‑For`, §3); and the presented secret matches
|
||||
(`timingSafeEqual` on equal lengths, like the hook secret). The loopback test is one
|
||||
function, `isLoopbackIp`, shared with the hook-secret bypass, so the two secret-gated
|
||||
loopback paths cannot drift apart.
|
||||
- **The headers never travel further.** The first auth hook, right after the Host guard
|
||||
and in every auth mode, reads both headers and deletes them from the request, before
|
||||
any exemption (QR, web‑tab and HTML‑view capabilities) or route runs. They go from all
|
||||
three views Node keeps of a request: `headers`, the raw `rawHeaders` list and
|
||||
`headersDistinct`. So the web‑tab
|
||||
relay cannot forward the secret to a dashboard (as a second layer the relay also drops both default names and
|
||||
the configured username header; its WebSocket leg sends only `origin` and `cookie`).
|
||||
- **No auto‑provisioning.** The username must name an existing, enabled account, so an
|
||||
admin still decides who has an account. Unknown or disabled → `403`. The value is matched
|
||||
exactly: `normalizeUsername()` (trimmed, lower-cased, as for Basic logins), then the
|
||||
username rule, and nothing else. No domain is cut off and no character replaced, so an
|
||||
email address names no account, and a header that arrives twice (Node joins it as
|
||||
`admin, bob`) is refused, never split. Mapping the IdP's identity onto a Codeman
|
||||
username is the proxy's job.
|
||||
- **Fails closed once the secret header is present, even empty.** A wrong or empty secret,
|
||||
a non‑loopback source, or a missing username is refused outright and never falls
|
||||
through to the cookie or Basic paths, so a misconfigured proxy cannot degrade into
|
||||
another identity. A username header WITHOUT the secret header is ignored, and normal
|
||||
auth applies. With a valid secret, a missing username or an unknown or disabled account
|
||||
gets a plain `403` with no `WWW-Authenticate`.
|
||||
- **Rate limiting.** The secret is compared first, like the hook secret: a correct secret
|
||||
always passes, so junk requests from other local processes (which share `127.0.0.1`
|
||||
with the proxy) cannot lock sign‑in out. Only failures are counted, per IP, in their
|
||||
own bucket (`AUTH_FAILURE_MAX` per `AUTH_FAILURE_WINDOW_MS`, then `429`), separate from
|
||||
the Basic and hook buckets.
|
||||
- **Precedence and lifetime.** Checked before the session cookie (the proxy's identity is
|
||||
authoritative on that request; a stale cookie from an earlier Basic login in the same
|
||||
browser does not override it, and is neither read nor refreshed). No `codeman_session` cookie is minted: the proxy
|
||||
authorizes every new request and WebSocket upgrade. A terminal WebSocket or SSE stream
|
||||
that is already open stays open until it disconnects: neither ending the proxy session
|
||||
nor disabling the account closes it. Disabling the account refuses new authenticated
|
||||
requests and upgrades; it does NOT revoke the account's web‑tab / HTML‑view
|
||||
capabilities, which behind the proxy are reachable without its sign‑in, so to cut
|
||||
someone off also use the Admin Panel **Logout** for them (it revokes both capability
|
||||
stores) or delete the account. A password reset or Logout alone does not
|
||||
cut off a proxy sign-in: it uses no password and holds no cookie, so the next request the
|
||||
proxy vouches for signs the person in again. Proxy sign-ins update the account's
|
||||
last-login time at most every 15 minutes, throttled in memory before the user store is
|
||||
touched.
|
||||
- **`mustChangePassword`** does not gate a proxy sign‑in (no Codeman password was used),
|
||||
and `GET /api/me` reports `mustChangePassword: false` plus `viaTrustedProxy: true`, so
|
||||
the browser does not force a password change. The account's Codeman password still
|
||||
works wherever the loopback port is reachable without the proxy (an SSH tunnel, the
|
||||
managed tunnel), and such a request is not covered by the identity provider's MFA.
|
||||
Password sign-in has to stay: Codeman's own clients (`codeman agent`, `mcp`, `notify`,
|
||||
`attach`, `tui`, the skill) sign in with Basic on loopback. For an account used only
|
||||
through the proxy, create it without a password; the generated one-time password can be
|
||||
discarded, and the pending `mustChangePassword` then only shows as a label. A user's own logout / "Revoke all" ends Codeman cookies, not the
|
||||
proxy's session (`/oauth2/sign_out` does that).
|
||||
- **Web tabs and rendered HTML files** authenticate by the capability in their URL,
|
||||
because their sandboxed frames send no cookies, not even the proxy's. The proxy must
|
||||
therefore let `/webview/*` and `/html-view/*` through without its own sign‑in (and
|
||||
without adding the secret, and without forwarding `Authorization`); the wiki example
|
||||
does. With trusted‑proxy sign‑in configured, a request under those prefixes that the
|
||||
capability exemptions do not let through, whatever its token looks like, is refused with
|
||||
the route's own answer
|
||||
(`403` web tab, `404` HTML view) BEFORE the credential checks: no Basic challenge, no
|
||||
password check, no failure count (`serveRefusedCapabilityPath`). Two requests under a
|
||||
dead web‑tab capability have no route status to copy and get the hook's `403` as well: a
|
||||
WebSocket upgrade is refused at the handshake (the route alone accepts it and closes
|
||||
with `4003`), and `GET /webview/<cap>` without the trailing slash is not redirected
|
||||
(the route alone answers `302`). The prefix is judged
|
||||
the way a proxy's path matcher would (`capabilityPrefixOf`: case‑insensitive,
|
||||
percent‑decoded, dot segments and doubled slashes resolved), since the proxy forwards
|
||||
every such spelling without its sign‑in. Under a base path (`CODEMAN_BASE_URL`) the
|
||||
mount prefix is judged the same way: the server strips only its literal spelling, so
|
||||
the refusal looks for the capability prefix in the normalised path as it arrives and,
|
||||
when that path starts with the mount prefix, once more with the mount prefix removed.
|
||||
A match in either form is refused. The path as it arrives comes first, because under
|
||||
a mount named like a capability prefix (`/webview`) the literal mount is already gone.
|
||||
Otherwise anonymous
|
||||
requests through the proxy could probe passwords and fill the per‑IP bucket, which
|
||||
behind the proxy is always `127.0.0.1`, locking out Basic sign‑in from loopback.
|
||||
Without a proxy configured these paths keep the normal `401` challenge. One limit
|
||||
follows from the exemption being by prefix: a sandboxed frame's request that lands
|
||||
outside its prefix goes through the proxy's sign-in without a cookie and fails there,
|
||||
so the `Referer` form and the lost-frame recovery page (§10b) are not reachable for
|
||||
sandboxed frames behind the proxy.
|
||||
- **The proxy's own session cookie.** A cookie-based proxy's session cookie is a sign-in
|
||||
for the whole site. Codeman does not know its name, and the web-tab relay forwards
|
||||
browser cookies (all but `codeman_session`) to a dashboard opened in trusted mode. The
|
||||
proxy must remove its cookie from every request it forwards to Codeman, on the
|
||||
capability paths and after its own sign-in check; the wiki example does.
|
||||
- **Unchanged:** the Host allowlist and Origin guard (set `CODEMAN_ALLOWED_HOSTS` to the
|
||||
proxy's hostname), the hook‑secret loopback bypass (a proxy should still refuse
|
||||
`/api/hook-event`, `/api/status-telemetry` and their `/api/v1/` aliases from outside;
|
||||
local hooks call the loopback port directly), and Basic sign‑in for requests without
|
||||
the secret header. Admin actions through the proxy are audited with IP `127.0.0.1`, as
|
||||
with any reverse proxy.
|
||||
- **Not supported:** Docker Compose installs where Codeman runs in a container and the
|
||||
proxy on the host; the proxy then connects from the bridge address, not loopback.
|
||||
|
||||
---
|
||||
|
||||
## 10b. Web tabs (dashboard proxy)
|
||||
@@ -629,6 +789,8 @@ Opt-in by a click, macOS only, admin-only in multi-user mode on every verb. The
|
||||
| Env / flag | Effect |
|
||||
|------------|--------|
|
||||
| `CODEMAN_PASSWORD` (+ `CODEMAN_USERNAME`) | Enable HTTP Basic auth |
|
||||
| `CODEMAN_TRUSTED_PROXY_SECRET_FILE` / `CODEMAN_TRUSTED_PROXY_SECRET` | Multi‑user only: trust a same‑host authenticating reverse proxy that presents this secret (≥ 32 printable ASCII chars; the file variant is preferred; both variables are removed from the environment once read; a setup that cannot be used stops the start) and a username header. Experimental — see §10a |
|
||||
| `CODEMAN_TRUSTED_PROXY_USER_HEADER` | Header the trusted proxy puts the Codeman username in (default `X-Codeman-User`) |
|
||||
| `--host` / `CODEMAN_HOST` | Bind host (default `127.0.0.1`) |
|
||||
| `CODEMAN_ALLOWED_HOSTS` | Extra `Host`/`Origin` allowlist entries for reverse proxies (comma‑separated; exact host, or leading‑dot `.suffix` for subdomains) — see §3 |
|
||||
| `--base-url` / `CODEMAN_BASE_URL` | Sub‑path prefix Codeman is mounted under behind a reverse proxy, e.g. `/codeman` (default `/`); the proxy must forward the prefix unchanged. Independent of `CODEMAN_ALLOWED_HOSTS` |
|
||||
@@ -650,6 +812,7 @@ Opt-in by a click, macOS only, admin-only in multi-user mode on every verb. The
|
||||
| Bind‑host classification, env‑flag parsing, Host/Origin allowlist (`buildHostPolicy` / `isAllowedRequestHost` / `isAllowedRequestOrigin`) | `src/web/network-auth-policy.ts` |
|
||||
| Start‑and‑warn policy | `src/web/server.ts` (`WebServer.start()`) |
|
||||
| Auth pipeline, rate limiting, security headers, CORS, Host/Origin guard (`registerHostGuard`) | `src/web/middleware/auth.ts` |
|
||||
| Trusted reverse‑proxy sign‑in: secret loading, header names, header stripping | `src/config/trusted-proxy.ts` |
|
||||
| File‑path containment (realpath‑before‑check) | `src/web/route-helpers.ts` (`validateSessionFilePath`) |
|
||||
| File routes, caps, SVG handling, download blocklist | `src/web/routes/file-routes.ts` |
|
||||
| Instance/socket/data‑dir scoping | `src/config/instance.ts` |
|
||||
|
||||
+15
@@ -216,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
|
||||
|
||||
@@ -110,6 +110,25 @@ any other endpoint. On-disk state (`local-model.json`, the `local-model/` folder
|
||||
internal, as for every other file in the data directory. Promotion to stable requires
|
||||
an explicit documented decision.
|
||||
|
||||
### Experimental trusted-proxy sign-in
|
||||
|
||||
Sign-in through an authenticating reverse proxy in multi-user mode
|
||||
([security-architecture.md](security-architecture.md) §10a) is labeled experimental, so
|
||||
item 3 above applies to all of its surface: the environment variables
|
||||
`CODEMAN_TRUSTED_PROXY_SECRET_FILE`, `CODEMAN_TRUSTED_PROXY_SECRET` and
|
||||
`CODEMAN_TRUSTED_PROXY_USER_HEADER`, the request headers `X-Codeman-Proxy-Secret` and
|
||||
`X-Codeman-User`, the `viaTrustedProxy` field of `GET /api/v1/me` (and its `/api` alias),
|
||||
the status codes and messages of its refusals, and the conditions under which a
|
||||
configured setup stops the start. They may change or be removed in a MINOR or PATCH
|
||||
release.
|
||||
|
||||
It is off unless a secret is configured. With it off, sign-in works as before. Three
|
||||
things still apply: the identity headers (the two above and a configured username
|
||||
header) are dropped on arrival, downloads and attachments refuse the secret file, and a
|
||||
trusted-proxy setting that cannot be used stops the start. The other fields
|
||||
of `GET /api/v1/me` keep their existing guarantees. Promotion to stable requires an
|
||||
explicit documented decision.
|
||||
|
||||
## Deprecation policy
|
||||
|
||||
When we need to change a covered surface:
|
||||
|
||||
+6
-1
@@ -107,7 +107,12 @@ similar). The sandboxed frame is opaque-origin, so its stylesheet, script, and A
|
||||
requests do not carry the proxy's authentication cookie; the proxy redirects them to
|
||||
the login provider, where CORS/CSP kills them, and the embedded app renders
|
||||
unstyled or broken while the Codeman page around it works fine. Trusted mode
|
||||
(**Open sandboxed** off) keeps a real origin and the cookie, so it works. The
|
||||
(**Open sandboxed** off) keeps a real origin and the cookie, so it works. ⚠️ In trusted
|
||||
mode the relay forwards the browser's cookies to the dashboard, all but
|
||||
`codeman_session`, and that includes the proxy's own session cookie unless the proxy
|
||||
removes it from the requests it forwards to Codeman (the Caddy example in
|
||||
[`docs/wiki/Multi-User-Mode.md`](wiki/Multi-User-Mode.md#single-sign-on-through-a-reverse-proxy)
|
||||
does). The
|
||||
**Test** button cannot catch this: it checks that the Codeman *server* can reach the
|
||||
upstream, not that a sandboxed *browser* frame can load assets through the public
|
||||
authentication layer.
|
||||
|
||||
@@ -110,7 +110,9 @@ approve those steps. With nothing else said, that also installs the first agent
|
||||
catalogue when none is found; `--ai-cli` (or `CODEMAN_AI_CLI`) says which one, or none.
|
||||
`CODEMAN_TAILSCALE=1` preselects the Tailscale answer, and never
|
||||
installs Tailscale itself non-interactively; a non-interactive run never renames the
|
||||
machine and never starts a service. Everything the unattended steps print goes to
|
||||
machine and never starts a service. With no terminal there is nowhere to type a password,
|
||||
so a step that needs `sudo` works only where `sudo` asks for none (a `NOPASSWD` entry, as
|
||||
cloud images and CI runners have). Everything the unattended steps print goes to
|
||||
`~/.codeman/install.log`, and the last lines of it are shown when a step fails.
|
||||
|
||||
### Without administrator rights
|
||||
|
||||
@@ -14,6 +14,7 @@ Press `Ctrl+?` in the app for the same list in a floating overlay.
|
||||
| `Alt+1` to `Alt+9` | Switch to tab N. Physical keys, so macOS Option layouts work. |
|
||||
| `Ctrl+Shift+{` / `Ctrl+Shift+}` | Move the active tab left / right. |
|
||||
| `Alt+B` | Collapse / expand the session sidebar, when that layout is on. |
|
||||
| `Alt+Shift+C` | Switch a Claude session between Chat and Terminal view, when [the chat view](Settings-Reference#header--panels) applies to it. |
|
||||
|
||||
`Ctrl+W` is not a Codeman shortcut: it goes to the terminal, where shells and agent CLIs
|
||||
use it to delete the previous word. **Close Session** has no key by default; close a session
|
||||
@@ -89,9 +90,20 @@ The terminal sees keystrokes before the app does. Any chord the app claims has t
|
||||
swallowed at the terminal layer, or xterm writes the control byte into the session as well
|
||||
as triggering the action. A chord **you** rebind an action to is kept out of the terminal
|
||||
too, so rebinding Previous Session to `Alt+J` switches the session and sends nothing to the
|
||||
CLI. The built-in defaults are deliberately not held back this way: `Ctrl+L` clears the
|
||||
screen and also reaches the CLI, which redraws on it. Binding an action back onto its own
|
||||
default behaves like the default.
|
||||
CLI. Several built-in defaults are held back too, each by a check of its own:
|
||||
|
||||
- the tab switches (`Alt+1` to `Alt+9`, `Alt+[` and `Alt+]`) and the session finder
|
||||
(`Ctrl+K`, `Alt+K`);
|
||||
- `Alt+B`, while the sidebar layout is on;
|
||||
- `Alt+Shift+C`, while the active session can show the chat view;
|
||||
- Copy Selection, whose `Ctrl+Shift+C` never reaches the CLI and whose `Ctrl+C` does not
|
||||
while text is selected;
|
||||
- the tile grid chords.
|
||||
|
||||
None of those chords types anything into the CLI when it acts as its shortcut; `Ctrl+C`
|
||||
with nothing selected is the interrupt and reaches the CLI. The other defaults still
|
||||
reach it: `Ctrl+L` clears the screen and also reaches the CLI, which redraws on it.
|
||||
Binding an action back onto its own default behaves like the default.
|
||||
|
||||
`Alt+1` through `Alt+9` are matched on **physical key position** rather than the character
|
||||
produced, so macOS Option layouts that produce `¡™£` still switch tabs.
|
||||
|
||||
@@ -112,7 +112,370 @@ casually; they do not make the account a sandbox.
|
||||
|
||||
Each user authenticates with their own name and password rather than the shared
|
||||
`CODEMAN_PASSWORD`. Logins are individually revocable: disable, reset, or delete an account
|
||||
at any time, and existing browser sessions can be revoked.
|
||||
at any time, and existing browser sessions can be revoked. A person who signs in through a
|
||||
reverse proxy (next section) uses no Codeman password and holds no browser session, so a
|
||||
password reset or a logout does not end their access: disable or delete the account.
|
||||
|
||||
## Single sign-on through a reverse proxy
|
||||
|
||||
Instead of Codeman passwords, people can sign in through your identity provider (Entra ID,
|
||||
Google Workspace, Keycloak, Okta, ...). An authenticating reverse proxy on the same host
|
||||
does the sign-in and tells Codeman who the person is. Codeman still decides who has an
|
||||
account: the username must name an existing, enabled user, or the request gets `403`.
|
||||
|
||||
**Experimental.** The settings, the two headers and the `viaTrustedProxy` field of
|
||||
`GET /api/me` may still change (see
|
||||
[`docs/versioning-policy.md`](https://github.com/Ark0N/Codeman/blob/master/docs/versioning-policy.md)).
|
||||
|
||||
"Trusted proxy" here means only this sign-in. It does not make Codeman read
|
||||
`X-Forwarded-For` or any other forwarded address: the client address stays the address of
|
||||
the socket, which behind the proxy is `127.0.0.1`.
|
||||
|
||||
```
|
||||
browser --HTTPS--> Caddy --forward_auth--> oauth2-proxy (127.0.0.1:4180) --> identity provider
|
||||
\--reverse_proxy--> Codeman (127.0.0.1:3000, multi-user mode)
|
||||
```
|
||||
|
||||
On every request the proxy adds two headers:
|
||||
|
||||
| Header | Value |
|
||||
|---|---|
|
||||
| `X-Codeman-Proxy-Secret` | the shared secret |
|
||||
| `X-Codeman-User` | the Codeman username (another name can be set with `CODEMAN_TRUSTED_PROXY_USER_HEADER`: an `X-…` header such as `X-Forwarded-User`, or `Remote-User`; standard and reserved headers are refused, because the header is removed from every request) |
|
||||
|
||||
Codeman believes them only from a loopback connection (`127.0.0.1`, `::1` or
|
||||
`::ffff:127.0.0.1`) with the matching secret, so keep Codeman bound to `127.0.0.1` and the
|
||||
proxy on the same host. It removes both headers from
|
||||
every request before anything else sees them. The exact rules are in
|
||||
[`docs/security-architecture.md` §10a](https://github.com/Ark0N/Codeman/blob/master/docs/security-architecture.md).
|
||||
|
||||
The secret keeps other local processes from claiming an identity. It does not protect
|
||||
against anything that runs as Codeman's own OS account, which includes every agent session:
|
||||
such a process can read the secret and sign in as anyone, an admin included, over loopback.
|
||||
That is the same exposure as editing `users.json`, which the same account can also do (see
|
||||
[Read this before enabling it](#read-this-before-enabling-it)).
|
||||
|
||||
### Codeman
|
||||
|
||||
```bash
|
||||
install -m 600 /dev/null ~/.codeman/proxy-secret
|
||||
openssl rand -hex 32 > ~/.codeman/proxy-secret # the shared secret, also given to the proxy
|
||||
codeman users add alice --admin # accounts still come from Codeman
|
||||
CODEMAN_MULTIUSER=1 \
|
||||
CODEMAN_ALLOWED_HOSTS=codeman.example.com \
|
||||
CODEMAN_TRUSTED_PROXY_SECRET_FILE=~/.codeman/proxy-secret \
|
||||
codeman web # stays on 127.0.0.1:3000
|
||||
```
|
||||
|
||||
The startup log says `Trusted-proxy sign-in enabled (experimental)`. A setup that cannot be
|
||||
used stops the start, with a message that says why:
|
||||
|
||||
- the secret file cannot be read, is empty, or can be read by group or others (`chmod 600`
|
||||
it; the mode is not checked on Windows);
|
||||
- the secret is shorter than 32 characters or not printable ASCII;
|
||||
- both `CODEMAN_TRUSTED_PROXY_SECRET_FILE` and `CODEMAN_TRUSTED_PROXY_SECRET` are set;
|
||||
- a secret is set without multi-user mode;
|
||||
- `CODEMAN_TRUSTED_PROXY_USER_HEADER` names a header that is not allowed.
|
||||
|
||||
In a systemd unit, give the file as an absolute path (systemd does not expand `~`; `%h`
|
||||
works in a user unit; in a system unit write the full path). Codeman's downloads and
|
||||
attachments refuse the configured secret file.
|
||||
|
||||
`CODEMAN_TRUSTED_PROXY_SECRET` (the value itself) works too. Codeman reads the settings
|
||||
once and removes both variables from its environment, so sessions started later don't
|
||||
inherit them. That is all it does: the value stays visible in `/proc/<pid>/environ` for as
|
||||
long as the server runs, and a tmux server started earlier with it set keeps its own copy
|
||||
until restarted. Prefer the file.
|
||||
|
||||
Password sign-in stays available for requests that reach Codeman without the proxy.
|
||||
Codeman's own tools need it: `codeman agent`, `mcp`, `notify`, `attach` and `tui` and the
|
||||
Codeman skill sign in on loopback with `CODEMAN_USERNAME` / `CODEMAN_PASSWORD`. Such a
|
||||
request is not checked by the identity provider, so its MFA does not apply to it. For a
|
||||
person who only ever signs in through the proxy, create the account without a password:
|
||||
Codeman generates a random one-time password, which you can discard. The account then
|
||||
keeps its `must-change-pw` label in the Admin Panel; the label has no effect on proxy
|
||||
sign-ins.
|
||||
|
||||
### oauth2-proxy
|
||||
|
||||
Register an OIDC app with your identity provider (redirect URI
|
||||
`https://codeman.example.com/oauth2/callback`) and restrict it to the people who should
|
||||
get in. A minimal `oauth2-proxy.cfg`:
|
||||
|
||||
```toml
|
||||
http_address = "127.0.0.1:4180"
|
||||
reverse_proxy = true
|
||||
provider = "oidc"
|
||||
oidc_issuer_url = "https://login.microsoftonline.com/<tenant-id>/v2.0" # your provider
|
||||
redirect_url = "https://codeman.example.com/oauth2/callback"
|
||||
whitelist_domains = ["codeman.example.com"]
|
||||
email_domains = ["example.com"]
|
||||
set_xauthrequest = true # return the identity as X-Auth-Request-* headers
|
||||
skip_provider_button = true
|
||||
upstreams = ["static://202"] # forward_auth only, nothing to proxy
|
||||
cookie_secure = true
|
||||
cookie_samesite = "lax" # never sent from a sandboxed web-tab frame
|
||||
cookie_expire = "12h" # sign in again after this (default 168h)
|
||||
cookie_refresh = "1h" # re-check with the provider this often
|
||||
cookie_csrf_per_request = true # one CSRF cookie per sign-in, so parallel ones don't collide
|
||||
cookie_csrf_per_request_limit = 5
|
||||
scope = "openid email profile offline_access" # offline_access: a refresh token (Entra ID)
|
||||
```
|
||||
|
||||
Client ID, client secret and cookie secret go in the environment
|
||||
(`OAUTH2_PROXY_CLIENT_ID`, `OAUTH2_PROXY_CLIENT_SECRET`, `OAUTH2_PROXY_COOKIE_SECRET`).
|
||||
For Entra ID add `oidc_email_claim = "preferred_username"`. Without `cookie_refresh`, a
|
||||
person disabled at the provider keeps access until the cookie expires. `cookie_refresh`
|
||||
needs a refresh token: without one (for Entra ID, without `offline_access` in the scope),
|
||||
oauth2-proxy can't refresh, and people are sent back through sign-in whenever the ID token
|
||||
expires, about hourly.
|
||||
|
||||
Set `cookie_samesite`. oauth2-proxy puts no `SameSite` attribute on its cookie unless it is
|
||||
configured, and browsers disagree about a cookie without one. With `lax`, a sandboxed
|
||||
web-tab frame does not send the proxy's cookie in any browser.
|
||||
|
||||
The username Codeman gets is only as trustworthy as the claim it comes from:
|
||||
|
||||
- **Register the app as single-tenant.** The proxy trusts values that the administrators
|
||||
of the signing-in person's tenant control, so only your own tenant may sign in.
|
||||
- **`email` and `preferred_username` are mutable.** An administrator can change them, and
|
||||
an address can be given to another person later. That person then gets the Codeman
|
||||
account the address maps to, until you remove its row from the `map` below. Go through
|
||||
the table when people leave or are renamed.
|
||||
|
||||
### Caddy
|
||||
|
||||
Give Caddy the same secret through its environment, not in the Caddyfile (which is often
|
||||
world-readable): for the packaged service, a systemd drop-in with
|
||||
`EnvironmentFile=/etc/caddy/codeman-proxy.env` (mode 0600) containing
|
||||
`CODEMAN_TRUSTED_PROXY_SECRET=<secret>`. Keep the `{env.…}` placeholder below; a `{$…}`
|
||||
placeholder would put the value into the adapted config, which local processes can read
|
||||
from Caddy's admin port.
|
||||
|
||||
```caddyfile
|
||||
codeman.example.com {
|
||||
# Signed-in identity -> Codeman username (case-sensitive: use the spelling your
|
||||
# provider returns). Unlisted people get an empty username and are refused below.
|
||||
map {http.request.header.X-Auth-Request-Email} {codeman_user} {
|
||||
alice@example.com alice
|
||||
default ""
|
||||
}
|
||||
|
||||
# Hooks call 127.0.0.1:3000 directly; never expose them (or their /api/v1 aliases).
|
||||
@hooks path /api/hook-event /api/status-telemetry /api/v1/hook-event /api/v1/status-telemetry
|
||||
# Web tabs and rendered HTML files authenticate by the capability in their URL: their
|
||||
# sandboxed frames send no cookies, so they can't pass the sign-in below.
|
||||
@capability path /webview/* /html-view/*
|
||||
|
||||
# `route` keeps the order as written. Without it Caddy sorts directives itself, and
|
||||
# `handle` would run before `respond`, or forward_auth before request_header.
|
||||
route {
|
||||
respond @hooks 403
|
||||
|
||||
handle /oauth2/* {
|
||||
reverse_proxy 127.0.0.1:4180 {
|
||||
header_up X-Real-IP {remote_host}
|
||||
header_up X-Forwarded-Uri {uri}
|
||||
}
|
||||
}
|
||||
|
||||
handle @capability {
|
||||
# No sign-in and no secret: Codeman checks the capability itself. No password
|
||||
# either: these paths must never reach Codeman's password check or prompt.
|
||||
request_header -X-Codeman-Proxy-Secret
|
||||
request_header -X-Codeman-User
|
||||
request_header -Authorization
|
||||
# oauth2-proxy's cookie is a sign-in for this whole site. Codeman never needs
|
||||
# it, and its web-tab relay forwards browser cookies to a dashboard opened in
|
||||
# trusted mode.
|
||||
request_header Cookie "(^|;\s*)_oauth2_proxy[^=;]*=[^;]*" ""
|
||||
reverse_proxy 127.0.0.1:3000 {
|
||||
header_down -WWW-Authenticate
|
||||
}
|
||||
}
|
||||
|
||||
handle {
|
||||
route {
|
||||
# Only oauth2-proxy and this file may set identity headers.
|
||||
request_header -X-Auth-Request-Email
|
||||
request_header -X-Codeman-Proxy-Secret
|
||||
request_header -X-Codeman-User
|
||||
|
||||
forward_auth 127.0.0.1:4180 {
|
||||
uri /oauth2/auth
|
||||
copy_headers X-Auth-Request-Email
|
||||
@unauthenticated status 401
|
||||
handle_response @unauthenticated {
|
||||
# Only a page navigation can complete a sign-in. A background request
|
||||
# (fetch, the live-update stream, a WebSocket) gets a 401. A client
|
||||
# that sends no Sec-Fetch-Mode header is still redirected.
|
||||
@background {
|
||||
header Sec-Fetch-Mode *
|
||||
not header Sec-Fetch-Mode navigate
|
||||
}
|
||||
route {
|
||||
respond @background "Sign-in required" 401
|
||||
redir * /oauth2/start?rd={scheme}://{hostport}{uri}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@nouser vars {codeman_user} ""
|
||||
respond @nouser "No Codeman account for this sign-in" 403
|
||||
|
||||
# After forward_auth, which needs it: remove oauth2-proxy's cookie.
|
||||
request_header Cookie "(^|;\s*)_oauth2_proxy[^=;]*=[^;]*" ""
|
||||
|
||||
reverse_proxy 127.0.0.1:3000 {
|
||||
header_up X-Codeman-Proxy-Secret {env.CODEMAN_TRUSTED_PROXY_SECRET}
|
||||
header_up X-Codeman-User {codeman_user}
|
||||
# Codeman needs only the two headers above.
|
||||
header_up -X-Auth-Request-Email
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This example was run with Caddy 2.11.9 and oauth2-proxy 7.15.6. What it relies on, because
|
||||
Codeman cannot see a mistake here:
|
||||
|
||||
- **The proxy removes what the client sent.** The `request_header -…` lines delete any
|
||||
copy of the identity headers that arrived from outside, and `header_up` replaces a
|
||||
header, it never appends. The username therefore only ever comes from the sign-in result.
|
||||
- **The secret is added only behind the sign-in**, never on the `/webview/*` and
|
||||
`/html-view/*` route.
|
||||
- **The proxy's own cookie stops at the proxy.** The `request_header Cookie …` lines remove
|
||||
it on both routes. With a different `cookie_name` in oauth2-proxy, change the name in
|
||||
the pattern.
|
||||
- **A background request is not sent to the sign-in.** A request with a `Sec-Fetch-Mode`
|
||||
other than `navigate` gets a `401`. Page navigations are redirected as before, and so
|
||||
are clients that send no such header (command-line tools, old browsers). Without that
|
||||
rule an open Codeman page whose proxy session has ended starts a sign-in with every
|
||||
background request that follows the redirect, which `fetch()` and the live-update stream
|
||||
do. Each one replaces oauth2-proxy's CSRF cookie, and the person's real sign-in then
|
||||
ends on oauth2-proxy's error page ("CSRF token mismatch"). `cookie_csrf_per_request`
|
||||
covers the remaining case of several tabs signing in at once.
|
||||
- **oauth2-proxy's identity headers stop at the proxy too.** `header_up -X-Auth-Request-Email`
|
||||
removes the address on the way to Codeman, because the web-tab relay passes headers it
|
||||
does not know on to dashboards.
|
||||
|
||||
Check the order Caddy will actually use with
|
||||
`caddy adapt --config Caddyfile --adapter caddyfile` before going live. With
|
||||
`CODEMAN_BASE_URL` (a sub-path mount), prefix the paths in `@hooks` and `@capability`.
|
||||
|
||||
To check that a forged header is ignored, run this in the browser console of the signed-in
|
||||
page. It must show your own username:
|
||||
|
||||
```js
|
||||
fetch('/api/me', { headers: { 'X-Codeman-User': 'someone-else' } }).then((r) => r.json()).then(console.log)
|
||||
```
|
||||
|
||||
### Taking the username from the identity provider instead
|
||||
|
||||
The `map` is a list you maintain. If your provider can put the Codeman username into the
|
||||
ID token (for example the AD logon name: Entra ID can add it with a claims mapping policy
|
||||
that emits `user.onpremisessamaccountname` as a custom claim; the app then needs
|
||||
`acceptMappedClaims` enabled, which belongs only on a single-tenant app registration), let
|
||||
oauth2-proxy return that claim as a header. That needs
|
||||
oauth2-proxy 7.15.5 or later with its alpha config (`--alpha-config`), and the claim must
|
||||
be listed in the provider's `additionalClaims`, otherwise the header stays empty:
|
||||
|
||||
```yaml
|
||||
providers:
|
||||
- id: idp
|
||||
provider: oidc
|
||||
# ... clientID, clientSecretFile, oidcConfig ...
|
||||
additionalClaims:
|
||||
- samaccountname
|
||||
injectResponseHeaders:
|
||||
- name: X-Auth-Request-Codeman-User
|
||||
values:
|
||||
- claimSource:
|
||||
claim: samaccountname
|
||||
```
|
||||
|
||||
In the Caddyfile, drop the `map` and replace the inner `route` of the last `handle`:
|
||||
|
||||
```caddyfile
|
||||
route {
|
||||
request_header -X-Auth-Request-Email
|
||||
request_header -X-Auth-Request-Codeman-User
|
||||
request_header -X-Codeman-Proxy-Secret
|
||||
request_header -X-Codeman-User
|
||||
|
||||
forward_auth 127.0.0.1:4180 {
|
||||
uri /oauth2/auth
|
||||
copy_headers X-Auth-Request-Email X-Auth-Request-Codeman-User
|
||||
@unauthenticated status 401
|
||||
handle_response @unauthenticated {
|
||||
@background {
|
||||
header Sec-Fetch-Mode *
|
||||
not header Sec-Fetch-Mode navigate
|
||||
}
|
||||
route {
|
||||
respond @background "Sign-in required" 401
|
||||
redir * /oauth2/start?rd={scheme}://{hostport}{uri}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@nouser vars {http.request.header.X-Auth-Request-Codeman-User} ""
|
||||
respond @nouser "No Codeman username for this sign-in" 403
|
||||
|
||||
request_header Cookie "(^|;\s*)_oauth2_proxy[^=;]*=[^;]*" ""
|
||||
|
||||
reverse_proxy 127.0.0.1:3000 {
|
||||
header_up X-Codeman-Proxy-Secret {env.CODEMAN_TRUSTED_PROXY_SECRET}
|
||||
header_up X-Codeman-User {http.request.header.X-Auth-Request-Codeman-User}
|
||||
header_up -X-Auth-Request-Email
|
||||
header_up -X-Auth-Request-Codeman-User
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Adding a person is then: allow them at the identity provider, and
|
||||
`codeman users add <name>`. Codeman usernames allow letters, digits, `_` and `-` only, so
|
||||
the claim must fit that. A logon name with a dot (`jane.doe`) does not: for such accounts
|
||||
keep the `map`. A browser that signed in before the claim existed needs to sign
|
||||
out (`/oauth2/sign_out`) and in again.
|
||||
|
||||
### Things to know
|
||||
|
||||
- **No Codeman cookie is issued** for proxy sign-ins. The proxy authorizes every new
|
||||
request and WebSocket upgrade, but a terminal or live-update connection that is already
|
||||
open stays open until it disconnects.
|
||||
- **Cutting someone off:** disable their Codeman account (new requests are refused), then
|
||||
use **Logout** for them in the Admin Panel, which also revokes the web-tab and HTML-view
|
||||
links they opened (disabling alone doesn't, and those links don't need the proxy's
|
||||
sign-in). Deleting the account does both. Logout alone, or a password reset, does not
|
||||
cut off a proxy sign-in: it holds no cookie and uses no password, so the next request
|
||||
signs the person in again. Connections already open stay open until they disconnect.
|
||||
- **Web tabs and HTML view behind the proxy:** with trusted-proxy sign-in configured, a
|
||||
path under those prefixes without a live capability, malformed ones included, is refused
|
||||
(`403` / `404`) without a password check,
|
||||
prompt or failure count, so anonymous requests can't probe passwords or lock out the
|
||||
password sign-in.
|
||||
- **When the proxy session expires**, API calls and the live-update stream get the proxy's
|
||||
`401`. An open Codeman page then shows "No connection to the Codeman server" and does
|
||||
not recover by itself: reload it to sign in again. The `rd=` return address is not
|
||||
URL-encoded, so a query string with `&` loses everything after the first one.
|
||||
- **`mustChangePassword` is ignored** for proxy sign-ins, since no Codeman password was
|
||||
used, and `GET /api/me` reports it as `false` for them. A person's own "Revoke all" and logout end Codeman cookies, not the proxy's
|
||||
session; sign out of the proxy at `/oauth2/sign_out`.
|
||||
- **A wrong or empty secret is refused outright** (and failures are rate-limited per IP);
|
||||
it never falls back to the cookie or password sign-in.
|
||||
- **Sandboxed web tabs:** a request the dashboard makes outside its
|
||||
`/webview/<capability>/` prefix (a root-absolute asset the rewriting missed, or a page
|
||||
that reloads itself) goes through the proxy's sign-in, carries no cookie and fails
|
||||
there. Codeman's `Referer` relay and lost-frame recovery never see it. Dashboards that
|
||||
use relative URLs work; for the others use trusted mode or a new browser tab.
|
||||
- **Trusted web tabs** forward the browser's cookies to their dashboard. The proxy's
|
||||
sign-in cookie would be among them, which is why the Caddy example removes it.
|
||||
- **Docker Compose installs** can't use this: the proxy on the host reaches the container
|
||||
from the bridge address, not loopback.
|
||||
- **Audit log:** admin actions through the proxy are recorded with IP `127.0.0.1`.
|
||||
|
||||
## Gotchas
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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. |
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ non-updatable. See [Running As A Service](Running-As-A-Service).
|
||||
| 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. |
|
||||
@@ -62,11 +63,20 @@ non-updatable. See [Running As A Service](Running-As-A-Service).
|
||||
|
||||
Chips for every optional header control, with a live preview of the resulting header:
|
||||
|
||||
Run, Font Size, System Stats, Redraw Terminal, Response Viewer, Away Digest, Session
|
||||
Run, Font Size, System Stats, Redraw Terminal, Response Viewer, Codex files, Away Digest, Session
|
||||
Manager, Attachments, Edit history, File Viewer, Multi-monitor, Split, Tiles, Plan Usage, Lifecycle Log, Monitor,
|
||||
Project Insights, File Browser, Subagents, Approvals Inbox, Read My Mind, Ultracode Agents,
|
||||
Ultracode Windows, Cron.
|
||||
|
||||
**Codex files** (off by default, per device) switches on four extras for Codex sessions, together:
|
||||
a click on a file name Codex underlined in the pane opening that file in the preview when it names a
|
||||
single supported file from the conversation (off, the click goes to Codex), a **Response files** header button that lists the previewable files linked in the latest reply
|
||||
(desktop only: phones keep File Viewer as their one header button, even with this on), a click on a
|
||||
file name in Codex's own sidebar opening that file in the preview when it matches a single linked
|
||||
file (off, the click goes to Codex), and a **Dock** button on file previews that, on a window 1180px
|
||||
or wider with a single terminal, docks the preview beside the terminal. With it off none of the four
|
||||
exists, and every click in a Codex pane goes to Codex as before.
|
||||
|
||||
**Host readings** (opt-in, both off by default and per device): **GPU Stats** adds three items after CPU and MEM: GPU load, graphics memory and the GPU clock,
|
||||
and **CPU MHz** adds the live CPU clock. Both sets of items live inside **System Stats**, so they show only
|
||||
while that chip is on, and nothing is fetched while it is off. An item appears only when the
|
||||
@@ -113,7 +123,21 @@ images it produced. Claude sessions, local and remote (SSH). Nothing is read unt
|
||||
stores those diffs (secrets included) under `~/.codeman/edit-history/`; see
|
||||
[Working With Files](Working-With-Files#edit-history).
|
||||
|
||||
Most default to off. The stock desktop header is system stats, File Viewer, Tiles, and the gear.
|
||||
Under **Panels**, **Open Claude sessions in Chat view** (per device, off by default, never on
|
||||
phones) picks the view a Claude session opens in. The chat view draws the session's conversation
|
||||
as text, over the terminal. To type, switch to the Terminal view. The terminal keeps running underneath, so switching
|
||||
views never resizes it. The chat view applies to local and Docker Claude sessions in the main
|
||||
view. Remote (SSH) and adopted sessions keep the terminal, and so do the tiles of the tile grid
|
||||
and the second pane of a split. Each session remembers its own choice in this browser: press
|
||||
`Alt+Shift+C`, or use the Chat / Terminal switch at the terminal's top right, to change it.
|
||||
Another browser or device opens the same session in its own default until you choose there too.
|
||||
This setting decides only where a session with no choice of its own starts.
|
||||
|
||||
**Show the Chat / Terminal switch** (per device, off by default, never on phones) shows that switch
|
||||
at the top right of a Claude session. Turn it on to switch views with a click. Without it, each
|
||||
session keeps the view it had, and `Alt+Shift+C` still switches views.
|
||||
|
||||
Most header chips default to off. The stock desktop header is system stats, File Viewer, Tiles, and the gear.
|
||||
**Header Stats Style** picks how the system stats and plan usage are drawn: *Compact*
|
||||
(default; two pills with a ring beside every value), *Tiles* (label over value with a bar underneath) or *As before* (the bars and the `5H · 7D` chip). Desktop only, per device.
|
||||
New header controls never appear on phones. Split is desktop-only regardless of this
|
||||
@@ -299,6 +323,9 @@ Some things are configured before the server starts, not in the UI:
|
||||
| `CODEMAN_ALLOWED_HOSTS` | Extra Host and Origin allowlist entries for a reverse proxy. |
|
||||
| `CODEMAN_INSTANCE` | Scopes the data directory and tmux socket together. Required for a second instance. |
|
||||
| `CODEMAN_MULTIUSER` | Enables multi-user mode. |
|
||||
| `CODEMAN_TRUSTED_PROXY_SECRET_FILE` | Experimental, multi-user only. A file (mode 600) holding the secret that lets an authenticating reverse proxy on the same host sign people in (single sign-on). A setup that cannot be used stops the start. See [Multi-User Mode](Multi-User-Mode#single-sign-on-through-a-reverse-proxy). |
|
||||
| `CODEMAN_TRUSTED_PROXY_SECRET` | The same secret given directly. Both variables are read once at startup and then removed from the environment, so sessions don't inherit them; the file variant is preferred. |
|
||||
| `CODEMAN_TRUSTED_PROXY_USER_HEADER` | Header that proxy puts the Codeman username in. `X-Codeman-User` by default; only an `X-…` header or `Remote-User` is accepted. |
|
||||
| `CODEMAN_GESTURE` | Makes gesture control available to be enabled. |
|
||||
| `CODEMAN_DOCKER_BRIDGE_HOOKS` | Lets in-container hooks reach the host on a loopback bind. |
|
||||
| `CODEMAN_FILE_PICKER_ROOTS` | Extra roots for the path picker. |
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -131,6 +131,17 @@ That prompt comes from Claude Code, not Codeman. Codeman's default is to start w
|
||||
permission prompts skipped, which is what the security model is built around. If you would
|
||||
rather it prompted, change **App Settings → Agents & CLIs → Claude → Startup Mode**.
|
||||
|
||||
### Claude asks for permission although Startup Mode skips the prompts (Codeman runs as root)
|
||||
|
||||
When the Codeman server itself runs as root (common on a VPS and in an LXC container),
|
||||
Claude sessions start without the permission bypass and ask before they act. Claude Code
|
||||
refuses `--dangerously-skip-permissions` under root and exits, which on older versions left
|
||||
every Claude tab with a dead pane (`--dangerously-skip-permissions cannot be used with
|
||||
root/sudo privileges for security reasons`). Codeman now leaves the flag out there and writes
|
||||
one line to the server log for each such launch; the other startup modes are passed through
|
||||
unchanged. Run Codeman as a normal user to get the default back. A session in a Docker case
|
||||
or on a remote host runs under the account on that side, so this does not apply to it.
|
||||
|
||||
### My settings were reset, or a CLI I enabled is gone
|
||||
|
||||
Something rewrote a file in `~/.codeman/` (a hand edit, a restart that loaded a bad file, a
|
||||
|
||||
@@ -97,7 +97,10 @@ The reason: an opaque-origin frame's stylesheet, script, and API requests do not
|
||||
proxy's authentication cookie. The proxy redirects them to the login provider, and CORS or
|
||||
CSP kills them there.
|
||||
|
||||
Trusted mode keeps a real origin and the cookie, so it works. Test cannot catch this, because
|
||||
Trusted mode keeps a real origin and the cookie, so it works. In trusted mode Codeman
|
||||
forwards the browser's cookies to the dashboard, and that includes the proxy's own session
|
||||
cookie unless the proxy removes it from what it forwards to Codeman (the Caddy example in
|
||||
[Multi-User Mode](Multi-User-Mode#single-sign-on-through-a-reverse-proxy) does). Test cannot catch this, because
|
||||
it checks the server's reach, not the browser's.
|
||||
|
||||
## Security notes
|
||||
|
||||
@@ -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,
|
||||
@@ -118,6 +142,14 @@ File paths in a session are links. That works in two places:
|
||||
render as underlined monospace links. A Markdown link whose target is a path
|
||||
(`[report](/tmp/run/report.json)`, the way Codex cites files) opens the same way.
|
||||
|
||||
In a Codex session, with the **Codex files** setting on (App Settings > Header & Panels,
|
||||
per device, off by default), clicking a file name Codex underlined opens it in Codeman's
|
||||
preview when it names a single supported file from the conversation; anything else goes to
|
||||
Codex as before. The same setting adds three more: a **Response files** header button that lists the files linked in
|
||||
the latest reply (desktop only), a file name in Codex's own sidebar opening the preview when it
|
||||
matches a single linked file, and a **Dock** button that, on a wide window with a single
|
||||
terminal, switches between a preview beside the terminal and a floating one.
|
||||
|
||||
Clicking one opens it in the preview: images and PDFs render, video and audio play with a
|
||||
working scrub bar, documents convert, text shows inline, Markdown renders and HTML opens as a
|
||||
page. The exception is a plain text file (a log, `.txt`, `.json`, code) inside the workspace
|
||||
@@ -230,14 +262,16 @@ Images (png, jpg, gif, webp, bmp, heic) are re-encoded on the device before they
|
||||
goes as is, so it keeps its frames), and HEIC from an iPhone is converted to JPEG. Videos (mp4, webm, mov, m4v, ogv) are stored as recorded,
|
||||
up to 1 GB each by default (`CODEMAN_MAX_PASTE_VIDEO_BYTES`); they stream to disk rather than
|
||||
through server memory. Documents are the office formats (pdf, docx, pptx, xlsx, zip) and the
|
||||
text family (txt, md, csv, tsv, json, log, yaml, yml, xml). Each is checked on the way in,
|
||||
text family (txt, md, csv, tsv, json, log, yaml, yml, xml, html, htm). Each is checked on the way in,
|
||||
against its file signature for the binary formats and against its encoding for text (UTF-8,
|
||||
no NUL bytes), so a script renamed to `.pdf` is refused while a `.txt` can hold any text at
|
||||
all. A text file in another encoding is refused with a message saying it is not UTF-8 (or that
|
||||
it is UTF-16, which Excel's "Unicode Text" and Notepad's "Unicode" produce); save it as UTF-8
|
||||
(in Excel, "CSV UTF-8") and attach it again. Files with script or page extensions (sh, py,
|
||||
js, html) are not accepted, since a prompt upload is something for the agent to read, not
|
||||
something for Codeman to store and serve. A document keeps a trimmed copy of its original
|
||||
(in Excel, "CSV UTF-8") and attach it again. HTML is accepted because AI tools write
|
||||
specifications and reports as HTML as often as Markdown; an attached page is stored for the
|
||||
agent to read (the File Viewer shows its source; Codeman never renders it as a page). Files with script
|
||||
extensions (sh, py, js) are not accepted, since a prompt upload is something for the agent to
|
||||
read, not something to run. A document keeps a trimmed copy of its original
|
||||
name, letters, digits, dot, dash and underscore with anything else turned into a dash, so
|
||||
`Q3 report.pdf` is findable as `paste-<time>-<id>-Q3-report.pdf`; a name made entirely of
|
||||
other characters saves without one. Uploads are refused for remote (SSH) sessions, whose
|
||||
|
||||
+122
-18
@@ -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
|
||||
@@ -1184,9 +1185,20 @@ ensure_sudo() {
|
||||
if ! command -v sudo &>/dev/null; then
|
||||
die "sudo is required but not installed. Please install packages manually or run as root."
|
||||
fi
|
||||
# A sudo that runs without a password (NOPASSWD, or the timestamp
|
||||
# sudo_session_try keeps warm) needs no terminal and nothing validated.
|
||||
# `sudo -v` is no substitute for this test: it asks for a password as soon as
|
||||
# ONE sudoers entry of the account asks for one, so an account in the sudo
|
||||
# group with a NOPASSWD entry of its own (the cloud-image layout) runs
|
||||
# `sudo <command>` freely and is refused by `sudo -v` (measured on sudo 1.9.15).
|
||||
if sudo -n true 2>/dev/null; then
|
||||
return 0
|
||||
fi
|
||||
# Validate sudo access
|
||||
# When piped (curl | bash), stdin is the pipe — redirect from /dev/tty so sudo can prompt
|
||||
if [[ -e /dev/tty ]]; then
|
||||
# When piped (curl | bash), stdin is the pipe: redirect from /dev/tty so sudo can prompt.
|
||||
# Only when it can be opened (see tty_openable): with no terminal at all, sudo gets
|
||||
# its chance as it is and fails by itself when it would have to ask.
|
||||
if tty_openable; then
|
||||
if ! sudo -v 2>/dev/null < /dev/tty; then
|
||||
die "Failed to obtain sudo privileges."
|
||||
fi
|
||||
@@ -1216,8 +1228,9 @@ ensure_homebrew() {
|
||||
fi
|
||||
|
||||
info "Installing Homebrew first..."
|
||||
# When piped (curl | bash), stdin is the pipe — Homebrew needs TTY for sudo password prompt
|
||||
if [[ -e /dev/tty ]]; then
|
||||
# When piped (curl | bash), stdin is the pipe: Homebrew needs TTY for sudo password prompt.
|
||||
# With no terminal to open (see tty_openable) it runs unattended instead.
|
||||
if tty_openable; then
|
||||
/bin/bash -c "$(download_to_stdout https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" < /dev/tty
|
||||
else
|
||||
NONINTERACTIVE=1 /bin/bash -c "$(download_to_stdout https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
|
||||
@@ -2018,9 +2031,21 @@ fetch_source_archive() {
|
||||
# the keyboard even though the user is sitting at a terminal. These helpers
|
||||
# prompt via /dev/tty whenever a real terminal is available, and only fall back
|
||||
# to defaults when there is genuinely none (CI, truly headless pipes).
|
||||
|
||||
# True when /dev/tty can really be OPENED. The node is there on every Linux and
|
||||
# macOS, also for a process with no controlling terminal (su -c, cron, a CI
|
||||
# runner, cloud-init, a container started without -t): `[[ -e /dev/tty ]]` says
|
||||
# yes there, and a `< /dev/tty` behind it fails before the command ever runs.
|
||||
# That ended a headless install with a working passwordless sudo on "Failed to
|
||||
# obtain sudo privileges". Opening the node is the only test, so every redirect
|
||||
# from /dev/tty asks this first, never `-e`.
|
||||
tty_openable() {
|
||||
{ : < /dev/tty; } 2>/dev/null
|
||||
}
|
||||
|
||||
has_tty() {
|
||||
[[ -t 0 ]] && return 0
|
||||
{ : < /dev/tty; } 2>/dev/null
|
||||
tty_openable
|
||||
}
|
||||
|
||||
read_reply() {
|
||||
@@ -2101,7 +2126,7 @@ sudo_session_try() {
|
||||
if ! sudo -n true 2>/dev/null; then
|
||||
echo "" >&2
|
||||
info "Some steps need administrator rights. You will be asked for your password once."
|
||||
if [[ -e /dev/tty ]]; then
|
||||
if tty_openable; then
|
||||
sudo -v < /dev/tty || return 1
|
||||
else
|
||||
sudo -v || return 1
|
||||
@@ -2123,7 +2148,7 @@ sudo_session_start() {
|
||||
if sudo_session_try; then
|
||||
return 0
|
||||
fi
|
||||
if [[ -e /dev/tty ]]; then
|
||||
if tty_openable; then
|
||||
die "Failed to obtain sudo privileges."
|
||||
fi
|
||||
die "Failed to obtain sudo privileges. Try running the script directly instead of piping."
|
||||
@@ -2339,26 +2364,61 @@ xml_unescape() {
|
||||
printf '%s' "$1" | sed -e 's/</</g' -e 's/>/>/g' -e 's/&/\&/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 +2427,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
|
||||
|
||||
@@ -2876,8 +2944,9 @@ offer_install_tailscale() {
|
||||
sudo_session_start
|
||||
info "Running the official Tailscale installer..."
|
||||
# When piped (curl | bash), stdin is our pipe: give the child installer
|
||||
# the real terminal so its own sudo prompt works.
|
||||
if [[ -e /dev/tty ]]; then
|
||||
# the real terminal so its own sudo prompt works. A run with no terminal
|
||||
# to open (see tty_openable) hands it stdin as it is.
|
||||
if tty_openable; then
|
||||
if ! sh -c "$(download_to_stdout https://tailscale.com/install.sh)" < /dev/tty; then
|
||||
warn "Tailscale installation failed."
|
||||
return 1
|
||||
@@ -2922,7 +2991,7 @@ ensure_tailscale_login() {
|
||||
if "$ts_bin" up --timeout=300s; then up_ok="1"; fi
|
||||
else
|
||||
sudo_session_start
|
||||
if [[ -e /dev/tty ]]; then
|
||||
if tty_openable; then
|
||||
if run_as_root "$ts_bin" up --timeout=300s < /dev/tty; then up_ok="1"; fi
|
||||
else
|
||||
if run_as_root "$ts_bin" up --timeout=300s; then up_ok="1"; fi
|
||||
@@ -3636,6 +3705,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 +3793,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 +4494,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
|
||||
|
||||
Generated
+3
-3
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "aicodeman",
|
||||
"version": "1.51.1",
|
||||
"version": "1.52.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "aicodeman",
|
||||
"version": "1.51.1",
|
||||
"version": "1.52.1",
|
||||
"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
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "aicodeman",
|
||||
"version": "1.51.1",
|
||||
"version": "1.52.1",
|
||||
"description": "Self-hosted mission control for AI coding agents: run Claude Code, Codex, OpenCode, Gemini, DeepSeek, Grok and more 24/7 in tmux, from any device.",
|
||||
"mcpName": "io.github.Ark0N/codeman",
|
||||
"type": "module",
|
||||
@@ -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",
|
||||
|
||||
@@ -35,8 +35,8 @@ security-framework = "3"
|
||||
# Ignoring signals in the logo blinker (src/logo.rs). Already in the tree
|
||||
# through wry and tao, so no new crate is added.
|
||||
libc = "0.2"
|
||||
# JavaScript dialogs, HTTP Basic challenges, clearing cookies and the window's
|
||||
# content size (src/macos.rs). The versions wry already pulls in, so no new
|
||||
# JavaScript dialogs, HTTP Basic challenges, clearing one server's cookies and
|
||||
# the window's content size (src/macos.rs). The versions wry already pulls in, so no new
|
||||
# crate is added.
|
||||
objc2 = { version = "0.6.5", default-features = false, features = ["std"] }
|
||||
block2 = { version = "0.6.2", default-features = false, features = ["std"] }
|
||||
@@ -44,10 +44,12 @@ objc2-foundation = { version = "0.3.2", default-features = false, features = [
|
||||
"std",
|
||||
"objc2-core-foundation",
|
||||
"block2",
|
||||
"NSArray",
|
||||
"NSBundle",
|
||||
"NSDate",
|
||||
"NSDictionary",
|
||||
"NSGeometry",
|
||||
"NSHTTPCookie",
|
||||
"NSObject",
|
||||
"NSOperation",
|
||||
"NSProcessInfo",
|
||||
@@ -61,6 +63,7 @@ objc2-foundation = { version = "0.3.2", default-features = false, features = [
|
||||
"NSURLRequest",
|
||||
"NSURLResponse",
|
||||
"NSURLSession",
|
||||
"NSUUID",
|
||||
"NSValue",
|
||||
] }
|
||||
objc2-app-kit = { version = "0.3.2", default-features = false, features = [
|
||||
@@ -80,6 +83,7 @@ objc2-web-kit = { version = "0.3.2", default-features = false, features = [
|
||||
"block2",
|
||||
"objc2-app-kit",
|
||||
"WKFrameInfo",
|
||||
"WKHTTPCookieStore",
|
||||
"WKNavigationDelegate",
|
||||
"WKSecurityOrigin",
|
||||
"WKUIDelegate",
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
A small native app that opens Codeman in its own window. Double-click it, and
|
||||
it runs Codeman on this Mac (installing it first if it is not there) or
|
||||
connects to Codeman on another machine (installing it there over SSH if
|
||||
needed), and Codeman fills the window. `⌃⌘F` puts it in full screen.
|
||||
needed), and Codeman fills the window. Several servers open side by side as
|
||||
tabs in the title bar, one click apart. `⌃⌘F` puts it in full screen.
|
||||
|
||||
macOS first: the app runs on 11.3 or later, and Codeman's own page needs the
|
||||
WebKit of Safari 16.4 (see Known limits). The same code is meant to build for
|
||||
@@ -28,20 +29,21 @@ cannot do.
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| **Server tabs** | One tab per Codeman server, in a strip that takes the place of the title bar (the traffic lights sit at its left end, so the strip costs about 10 points over a plain title bar and stays in full screen). A click switches tabs, and every tab stays loaded, so a switch is instant: no reload, no new login. Each tab shows what its server's agents do: a red count for sessions that need a permission or an answer, an amber dot when one finished and waits for you, a blue ring while agents work, a dashed circle when the server does not answer. The app reads that itself from each server every two seconds (`api/sessions` and `api/approvals`, the reader the Apple logo uses), because WebKit stalls a hidden page. Each tab has a colour of its own, as a stripe on the tab in front, so you do not type into the wrong machine. `+` (or `⌘T`) opens the connect screen in a new tab; a server that is already open in a tab is not opened twice, its tab comes to the front instead. A double-click on a name, or **Rename Tab…** in the right-click menu, renames it; the right-click menu also picks the colour, reloads, connects the tab to another server and closes tabs. Drag a tab to reorder. Closing a tab only closes the window onto that server: its sessions keep running there, and `⇧⌘T` opens it again. The tabs of a server come back at the next launch, and connect by themselves when *Connect automatically when the app opens* is on. **All Servers** (`⌘0`, or the grid button left of the tabs) shows every server at once, the ones that need you first, with their sessions most urgent first; a click on a session opens its tab and selects it. |
|
||||
| **This Mac** | The connect screen's first tab looks for Codeman on this Mac and offers what fits: *Open Codeman* when it runs, *Start Codeman* when it is installed but stopped, *Install Codeman on this Mac* when it is not there. The address comes from Codeman's LaunchAgent (port, sub-path, HTTPS). The tab also finds every Codeman server of yours that already runs on this Mac (with `ps` and `lsof`: a `codeman web --port 4000` in a terminal, a beta instance beside the installed one) and recommends connecting to it. Each one's address is worked out from its listening socket and its command line (`127.0.0.1` for a bind to loopback or to every interface, its own address for a bind to one, `https` with `--https`, the path of `--base-url`), and each is asked once whether Codeman answers there. When nothing answers at the usual address (the LaunchAgent's, or `http://127.0.0.1:3000` without one), *Open Codeman* is for the first found server that does; when none of them can be opened, the tab says *Codeman is already running on this Mac* and lists them. Next to a Codeman that answers, the others are listed under *Also running on this Mac*. A row shows the address, the version, and a *Connect* button, or the reason the app cannot open that one (HTTPS with Codeman's own certificate, no answer). *Connect* is the connect of the Another machine tab with that address filled in: the same check, the login saved for it, the same entry under recent servers. Finding a server connects to nothing by itself. The tab never offers to start a second server, which would take over the first one's sessions, and Start refuses while one runs. A server that runs but listens nowhere yet (the first seconds after login, a restart) shows as *starting*: the tab looks again every second and, when a connect to this Mac had just been refused, opens Codeman once it is up. Start asks launchd to run the LaunchAgent (`kickstart`, or `bootstrap` when it is not loaded), so the server keeps its own settings and supervision; without a LaunchAgent it runs `codeman web -d`. The login comes from where Codeman keeps it: the LaunchAgent's `CODEMAN_USERNAME`/`CODEMAN_PASSWORD`, else `~/.codeman/.env` (what Codeman's command-line clients read), `admin` by default. It goes only to `127.0.0.1` on that Codeman's port, only while one of your own Codeman processes holds that port, is never saved to the Keychain, and never reaches the page. Whether Codeman is installed is looked up in its files and processes, then the login shell; the interactive profile (nvm in `.zshrc`, say) only on *Check again*. Install sets Codeman up from the app itself, with no Terminal and no password (see Decisions). It fetches the installer, asks it what is on this Mac, then asks two things: which coding agent to install, only when this Mac has none (the list comes from the installer, and *Skip for now* is there), and who can reach Codeman (this Mac only, or the local network with a password). A checklist follows the install, the installer's output is one click away, and Cancel stops it; installing again picks up where it stopped. Codeman runs as a LaunchAgent, so it keeps running when the app quits and starts at login. Port 3000 is used unless something else answers there, then the next free one. Closing the app does not stop an install: it runs on its own, and the app picks it up when it opens again. When it is done the app looks every 3 seconds and opens Codeman as soon as it answers; it stops looking after the first answer, after 30 minutes, or 90 seconds after a finished install whose server never answered (then it offers Start). *Install in Terminal instead* runs the installer in a Terminal window, for what the app cannot do (see Known limits): it may ask for the Mac password (Homebrew) and asks its own questions there. The app offers it by itself on a Mac where the graphical install cannot finish. An install still running in Terminal is recognized by its process, so the tab waits for it instead of offering Install twice. *Add a coding agent*, on this tab and in the app menu whenever Codeman is on this Mac, is the same chooser after the install: pick one agent, watch it install, open Codeman. It needs no password, leaves a running Codeman alone, and can be cancelled or left running like an install. After *Skip for now* the app says Codeman has no agent yet and offers this before it opens Codeman. |
|
||||
| **Another machine** | The second tab connects to a server by address (below). *Codeman is not installed there yet?* opens Terminal, connects with `ssh -t` and runs Codeman's installer on that machine, which asks its questions there; the app then suggests `http://<host>:3000` and the installer prints the real address at the end. The SSH login is checked to the characters of a user and host name (no option can be slipped in) and may carry a `:port`. The remote command runs under `bash -o pipefail`, so a failed download fails the install instead of reporting success. The same tab shows the one-line install command, with a Copy button, to run on a machine by hand. |
|
||||
| **Connect screen** | Server address, recent servers, a login for password-protected servers (password kept in the macOS Keychain), auto-connect at launch. An address typed without `http://` or `https://` gets `http://`, except a tailnet name with no port (`machine.tailnet.ts.net`, which is `tailscale serve`), which gets `https://`. It explains each failure: nothing listening; wrong password; too many failed logins (the password field stays open, since a single-user Codeman accepts the right password even then); unknown host name; an address this Mac cannot reach (with a pointer to the Local Network setting); an `http://` address on a port that only speaks HTTPS; an untrusted certificate; a redirect, with a button for the suggested `https://` address; not a Codeman server. A multi-user account that must change its password connects, and Codeman's own dialog asks for the new one. If the server page has not started showing within 15 seconds, or you press Cancel while it opens, the connect screen comes back with a notice. A login that would cross the network over plain `http://` to another machine says so. Return opens or starts the Codeman on this Mac (or connects to the one found here, when that is the tab's main button) and Esc cancels a connect, as in a Mac dialog (Install always takes a click). On a Mac whose WebKit is too old for Codeman it says so and Connect stays off (see Known limits). |
|
||||
| **Start Codeman** | On the This Mac tab, and when `http://127.0.0.1:<port>` or `http://localhost:<port>` answers nothing, one click runs `codeman web -d` (or `~/.codeman/app`) with your login shell's environment, so the server gets your real PATH (Homebrew, nvm) for the agents it spawns. zsh, bash and other POSIX shells run the start themselves; fish, nu, xonsh, tcsh and other shells only report their environment, and the start runs under `/bin/sh` with it. Offered for those two addresses only: `codeman web -d` listens on 127.0.0.1. |
|
||||
| **Login** | The app answers the server's HTTP Basic login requests itself, with the login you connected with, so the page keeps working after the server restarts (a restart forgets every session cookie). It answers only for Codeman's own pages under the server's base path: a web tab or a rendered HTML file that asks for a Basic login of its own is left to WebKit and never gets your Codeman password. WebKit keeps no copy of the login, so every request for it gets the current one. Each connect first clears the app's cookies, so connecting to the same server as another user really switches users (local storage, where Codeman keeps its per-device settings, stays; a dashboard in a web tab that keeps its own login in a cookie may ask for it again). A page that still gets a 401 reloads once. If the server refuses the login (the password was changed, say), the app does not keep sending it: it checks it with a single probe, and only if the server refuses that too does the connect screen come back with a notice. That does not take focus from the app you are in: if Codeman is in the background, its Dock icon bounces. |
|
||||
| **Login** | The app answers the server's HTTP Basic login requests itself, with the login you connected that tab with (each tab answers for its own server only), so the page keeps working after the server restarts (a restart forgets every session cookie). It answers only for Codeman's own pages under the server's base path: a web tab or a rendered HTML file that asks for a Basic login of its own is left to WebKit and never gets your Codeman password. WebKit keeps no copy of the login, so every request for it gets the current one. Each connect first clears that server's cookies, so connecting to the same server as another user really switches users (local storage, where Codeman keeps its per-device settings, stays; a dashboard in a web tab that keeps its own login in a cookie may ask for it again). On macOS 14 and later each server's pages keep their cookies and local storage in a data store of their own (see Decisions); before macOS 14 two servers on one machine (a Codeman on port 3000 and a beta on 5000) cannot be open in two tabs at once, since they would share one login cookie, and the app says so. A page that still gets a 401 reloads once. If the server refuses the login (the password was changed, say), the app does not keep sending it: it checks it with a single probe, and only if the server refuses that too does the connect screen come back with a notice. That does not take focus from the app you are in: if Codeman is in the background, its Dock icon bounces. |
|
||||
| **Dialogs** | Codeman's `confirm()`, `prompt()` and `alert()` (Delete case, Kill all sessions, Update Codeman, discarding unsaved edits, ...) show as native macOS dialogs. wry implements none of them, and without them WKWebView answers Cancel without showing anything. Each dialog's first line names the page it comes from, and says so when that is an embedded frame (a web tab, a rendered HTML preview), so a frame cannot pass its text off as Codeman's. |
|
||||
| **Full screen** | `⌃⌘F` or the green button. The last state is restored at launch; *Always Open in Full Screen* forces it. Leaving full screen returns to the saved window size and position. |
|
||||
| **Menus** | A real Edit menu (without one, `⌘C`/`⌘V` do nothing in a WKWebView), Reload `⌘R`, Switch Server `⇧⌘O`, Developer Tools `⌥⌘I`. The page sees every key first, so Codeman's own shortcuts keep working. If the main window ends up showing a raw file instead of Codeman, `⌘R` takes it back to Codeman. |
|
||||
| **Menus** | A real Edit menu (without one, `⌘C`/`⌘V` do nothing in a WKWebView), Reload `⌘R`, Developer Tools `⌥⌘I`, and a Server menu: New Server Tab `⌘T` (Switch Server `⇧⌘O` does the same), Close Tab `⌘W` (Close Window is `⇧⌘W`), Reopen Closed Tab `⇧⌘T`, Show All Servers `⌘0`, Show Previous and Next Tab `⇧⌘[` and `⇧⌘]`, and one item per tab, `⌘1` to `⌘8` (from nine tabs on, `⌘9` is the last one). `⌃Tab` and `⌥1` to `⌥9` stay Codeman's own (they switch sessions inside the server you are on). The page sees every key first, so Codeman's own shortcuts keep working. If the main window ends up showing a raw file instead of Codeman, `⌘R` takes it back to Codeman. |
|
||||
| **Pop-outs** | Implements Codeman's existing native-wrapper bridge, `window.CodemanHost` (`openInHostWindow` in `src/web/public/app.js`), so popping out a session or a file preview opens a real app window, and the pop-out icon is on by default. Session and rendered-HTML pop-outs come only from Codeman's own pop-out button. A `window.open` from page script opens only Codeman's file and download windows, without taking keyboard focus, at most 3 at once and then 1 per second. Only Codeman's own pop-out pages become app windows (see Decisions); when the app refuses one, Codeman shows a toast. Each pop-out opens a step down and to the right of the window in use, never exactly on top of another one. A web tab's *Open in new tab* opens the dashboard in your default browser, as it would from a browser tab. |
|
||||
| **Links** | On Codeman's own pages (the dashboard and session windows), a link to another site opens in your default browser, also on `⌘`-click or a middle click. Pages can send at most 3 links to the browser at once, then 1 per second. Inside a rendered HTML preview or a web tab, a plain link to another site does nothing, while one that asks for a new window (`target="_blank"`, `window.open`) opens in your default browser within the same budget (see Known limits). |
|
||||
| **Downloads** | Codeman's Download links, and downloads Codeman opens in a new window, save the file to `~/Downloads` whatever its type, and a toast in Codeman names the file. Files the web view cannot display are saved the same way. |
|
||||
| **A page that stops** | When the web content process of a window ends (a WebKit crash, or macOS taking the process back under memory pressure), the window loads its page again instead of staying blank. A second time within 30 seconds, the main window goes back to the connect screen and a pop-out closes, so a page that cannot stay up never becomes a reload loop. |
|
||||
| **Apple logo** | On a MacBook Pro with a PROLED XDR display, the lit Apple logo on the lid says what the agents are doing. **View > Blink Apple Logo** is the one switch, off until you turn it on. The more the logo moves, the more it needs you: it breathes (a slow fade out and back in) while agents work, blinks every two seconds for a yellow tab and flashes three times, then rests, for a red one. Each state can take another style under **View > Apple Logo Blink Styles**: Off, Breathe, Calm, Slow, Wink, Heartbeat, Fast, or Alarm. Picking a style turns the switch on, and turning the switch on with every state off brings back the recommended three (Breathe, Calm, Alarm). When several states hold, the most urgent one with a style shows: red, then yellow, then work. Styles chosen in 1.50.0 are kept, with the switch on if any of them was. The menu only exists on a Mac with that logo. No password is needed. Shell tabs do not count. The app asks the server every two seconds, and a change has to hold for three seconds before the logo follows it, so an agent between two turns does not flicker it. It keeps working while the window is hidden, and with any Codeman server. The logo moves on its own hardware fades, the ones [LogoLight](https://github.com/Ark0N/LogoLight) uses, so a blink writes no setting, and a logo you switched off yourself stays off. LogoLight (1.3 or later) steps aside while Codeman shows its agents on the logo, and takes the logo back afterwards, with whatever it showed before; while an older LogoLight runs, Codeman leaves the logo to it. While the app is closed nothing blinks. With the lid closed it just goes on while the Mac stays awake on its power adapter (**Keep This Mac Awake > With the Lid Closed**, or an external display): macOS keeps the logo dark under a closed lid, so the app tells the logo the lid is open and the keyboard that it is closed, which stays dark, as LogoLight's *Lit with Lid Closed* does. The light sensor is covered then, so the logo glows as it would in a dark room. The line under **Apple Logo Blink Styles** says what the closed lid did last (blinking, or why not). On battery, and while the display only sleeps with the lid open, the blink pauses and writes nothing. |
|
||||
| **Keep awake** | **Codeman > Keep This Mac Awake** keeps the Mac from going to sleep while Codeman's agents work on it: **While Agents Work** (an agent at work, and for 5 minutes after the last one stopped, so the gap between two turns or a reply from your phone does not let it drop off), or **Always** (while the app is open). Off until you choose. Only for a Codeman on this Mac (`127.0.0.1`, `localhost`, or one of this Mac's own addresses); for a server on another machine the menu says so. The display still sleeps. No password is needed anywhere: the app holds a power assertion of its own, which macOS shows in Activity Monitor and in `pmset -g assertions` as *Codeman keeps this Mac awake while its agents work*, and which ends with the app, a crash or a Force Quit included. On a MacBook, **Only When Plugged In** (on by default) pauses it on battery, and **With the Lid Closed** keeps a closed MacBook awake as well: while it holds, the app has macOS's sleep-on-lid-close turned off (see Decisions), and turns it back on when it lets go, quits or crashes. The lid is never kept awake on battery, whatever the settings: unplugged with the lid closed, the Mac goes to sleep. A line at the bottom of the menu says what it does right now: whether the lid is covered, that it is left to macOS while an external display is connected (a docked MacBook stays awake with its lid closed by macOS's own doing), and if the Mac slept under the lid all the same, until when. Codeman 1.50.1 kept the lid awake through a small root helper, behind the administrator password. Nothing uses that helper any more, and where it is still installed the menu has **Remove the Old Lid Helper…** (the one item that asks for the password). It lives in the app, so it ends when the app quits: Codeman keeps running as a LaunchAgent, but nothing keeps the Mac awake then. That is why, while it watches a Codeman on this Mac, closing the Codeman window hides the app instead of quitting it, as Cmd+H does, also while it is paused (on battery, say), since it carries on by itself: a click on its Dock icon brings it back, and only Cmd+Q (or Quit from the Dock) ends it. With no server open, or one on another machine, closing the window quits. |
|
||||
| **Apple logo** | On a MacBook Pro with a PROLED XDR display, the lit Apple logo on the lid says what the agents are doing. **View > Blink Apple Logo** is the one switch, off until you turn it on. The more the logo moves, the more it needs you: it breathes (a slow fade out and back in) while agents work, blinks every two seconds for a yellow tab and flashes three times, then rests, for a red one. Each state can take another style under **View > Apple Logo Blink Styles**: Off, Breathe, Calm, Slow, Wink, Heartbeat, Fast, or Alarm. Picking a style turns the switch on, and turning the switch on with every state off brings back the recommended three (Breathe, Calm, Alarm). When several states hold, the most urgent one with a style shows: red, then yellow, then work. Styles chosen in 1.50.0 are kept, with the switch on if any of them was. The menu only exists on a Mac with that logo. No password is needed. Shell tabs do not count. The app asks the server every two seconds, and a change has to hold for three seconds before the logo follows it, so an agent between two turns does not flicker it. It keeps working while the window is hidden, and with any Codeman server: with several tabs open it shows the most urgent state of all of them together, so a red tab on any server flashes it. The logo moves on its own hardware fades, the ones [LogoLight](https://github.com/Ark0N/LogoLight) uses, so a blink writes no setting, and a logo you switched off yourself stays off. LogoLight (1.3 or later) steps aside while Codeman shows its agents on the logo, and takes the logo back afterwards, with whatever it showed before; while an older LogoLight runs, Codeman leaves the logo to it. While the app is closed nothing blinks. With the lid closed it just goes on while the Mac stays awake on its power adapter (**Keep This Mac Awake > With the Lid Closed**, or an external display): macOS keeps the logo dark under a closed lid, so the app tells the logo the lid is open and the keyboard that it is closed, which stays dark, as LogoLight's *Lit with Lid Closed* does. The light sensor is covered then, so the logo glows as it would in a dark room. The line under **Apple Logo Blink Styles** says what the closed lid did last (blinking, or why not). On battery, and while the display only sleeps with the lid open, the blink pauses and writes nothing. |
|
||||
| **Keep awake** | **Codeman > Keep This Mac Awake** keeps the Mac from going to sleep while Codeman's agents work on it: **While Agents Work** (an agent at work, and for 5 minutes after the last one stopped, so the gap between two turns or a reply from your phone does not let it drop off), or **Always** (while the app is open). Off until you choose. It watches the Codeman on this Mac among the open tabs (the tab in front when that is one). Only for a Codeman on this Mac (`127.0.0.1`, `localhost`, or one of this Mac's own addresses); for a server on another machine the menu says so. The display still sleeps. No password is needed anywhere: the app holds a power assertion of its own, which macOS shows in Activity Monitor and in `pmset -g assertions` as *Codeman keeps this Mac awake while its agents work*, and which ends with the app, a crash or a Force Quit included. On a MacBook, **Only When Plugged In** (on by default) pauses it on battery, and **With the Lid Closed** keeps a closed MacBook awake as well: while it holds, the app has macOS's sleep-on-lid-close turned off (see Decisions), and turns it back on when it lets go, quits or crashes. The lid is never kept awake on battery, whatever the settings: unplugged with the lid closed, the Mac goes to sleep. A line at the bottom of the menu says what it does right now: whether the lid is covered, that it is left to macOS while an external display is connected (a docked MacBook stays awake with its lid closed by macOS's own doing), and if the Mac slept under the lid all the same, until when. Codeman 1.50.1 kept the lid awake through a small root helper, behind the administrator password. Nothing uses that helper any more, and where it is still installed the menu has **Remove the Old Lid Helper…** (the one item that asks for the password). It lives in the app, so it ends when the app quits: Codeman keeps running as a LaunchAgent, but nothing keeps the Mac awake then. That is why, while it watches a Codeman on this Mac, closing the Codeman window hides the app instead of quitting it, as Cmd+H does, also while it is paused (on battery, say), since it carries on by itself: a click on its Dock icon brings it back, and only Cmd+Q (or Quit from the Dock) ends it. With no server open, or one on another machine, closing the window quits. |
|
||||
| **Window** | Size, position and full-screen state are remembered. A saved window that hangs off the screen it opens on (it was last on a larger display that is gone, say) is pulled back on and shrunk to fit; one whose title bar is on no screen at all opens at the default size instead. Clicking the Dock icon brings back a minimized window. |
|
||||
|
||||
## Build (on a Mac)
|
||||
@@ -73,7 +75,8 @@ the macOS version in `macos/Info.plist` (`LSMinimumSystemVersion`, 11.3), and
|
||||
takes the binary from where cargo says it wrote it, so `CARGO_TARGET_DIR` and a
|
||||
cargo config's `build.target-dir` work.
|
||||
|
||||
Settings live in `~/Library/Application Support/Codeman/desktop.json`; passwords
|
||||
Settings live in `~/Library/Application Support/Codeman/desktop.json` (with the
|
||||
tabs to open again: their servers, names, colours and which was in front); passwords
|
||||
in the Keychain under *Codeman Desktop*, one item per username and server. A
|
||||
`desktop.json` the app cannot read or parse is moved aside, never overwritten:
|
||||
to `desktop.json.corrupt`, or to the first free name of `desktop.json.corrupt.1`
|
||||
@@ -99,6 +102,29 @@ the page logged in. Using the crates directly is also smaller.
|
||||
the JavaScript dialog methods and the authentication-challenge method to the
|
||||
classes of wry's own delegates, so wry stays an unmodified crates.io dependency.
|
||||
|
||||
**One window, a web view per tab.** The tab strip (`assets/tabs.html`) is a
|
||||
web view of its own across the top of the window, and each tab's pages sit
|
||||
below it, the one in front visible and the others hidden but loaded
|
||||
(`src/tabs.rs` holds the pure half: names, colours, order, the state the strip
|
||||
and the overview are sent). A tab shows the connect page until its server's
|
||||
page commits: that page loads in a second, hidden web view behind it, so the
|
||||
connect page keeps its status line and Cancel while the server loads, and the
|
||||
load can be abandoned without a blank tab. The strip and the overview listen to
|
||||
their own page only (`policy::parse_strip_ipc`, `parse_overview_ipc`) and
|
||||
navigate nowhere else, and a session id from the overview goes into Codeman's
|
||||
page only when it is made of the characters Codeman's ids are.
|
||||
|
||||
**A data store per server.** Codeman's login cookie has the same name on every
|
||||
port, and cookies are not told apart by port, so two servers on one machine in
|
||||
one store would keep logging each other out. On macOS 14 and later each
|
||||
server's pages (its tab and its pop-outs) use a WebKit data store of their own,
|
||||
named by a hash of the server's address (`tabs::store_id`), so it is the same
|
||||
store at every launch. The one exception is the server used last before tabs
|
||||
existed: it keeps WebKit's default store, and with it the local storage where
|
||||
Codeman keeps its per-device settings (every other server starts those afresh
|
||||
once). Before a connect only that server's cookies are removed from its store,
|
||||
never another tab's.
|
||||
|
||||
**What a page may ask of the app** (all in `src/policy.rs`, unit-tested):
|
||||
|
||||
- Codeman shows content it did not write on its own origin: rendered HTML files
|
||||
@@ -136,8 +162,11 @@ classes of wry's own delegates, so wry stays an unmodified crates.io dependency.
|
||||
relay 401s from content Codeman did not write. Only such a challenge can
|
||||
send the user back to the connect screen. WebKit is handed the login without
|
||||
persistence, so it keeps no copy: every challenge gets the current login,
|
||||
and one from before a Switch Server is never replayed.
|
||||
- Each connect starts by clearing the app's cookies (never local storage).
|
||||
and one from before another connect is never replayed. Each tab hands over
|
||||
a login of its own, and a challenge goes to the tab whose server holds the
|
||||
URL that got the 401 (the deepest base path, when two servers share an
|
||||
origin behind one proxy), so one tab never answers for another.
|
||||
- Each connect starts by clearing that server's cookies (never local storage).
|
||||
Codeman checks its session cookie before the `Authorization` header, so an
|
||||
earlier user's cookie would otherwise win over the new login.
|
||||
- Microphone and camera requests prompt per page. wry's default without a
|
||||
@@ -242,7 +271,7 @@ can write to the runtime folder. It asks `preflight` for the list like an instal
|
||||
does, and both pass `--no-admin`: that flag decides which agents count as
|
||||
installable, so without it on both the page could offer one the run refuses. The
|
||||
menu item is on the connect page because that is where the app may run things:
|
||||
from a Codeman page it leaves the page the way *Switch Server* does.
|
||||
from a Codeman page it opens in a new tab, as New Server Tab does.
|
||||
|
||||
**Terminal stays for what the app cannot do.** The route with Homebrew asks for
|
||||
the administrator password on a terminal, the Xcode tools arrive as a system
|
||||
|
||||
@@ -1636,13 +1636,20 @@
|
||||
els.fullscreen.checked = !!msg.startFullscreen;
|
||||
els.version.textContent = 'Codeman Desktop ' + (msg.version || '');
|
||||
renderRecent();
|
||||
if (state.servers[0]) choose(state.servers[0]);
|
||||
// A server tab opened again at launch names its server (target), and
|
||||
// connects to it by itself when connectNow says so; any other tab
|
||||
// shows the server used last.
|
||||
var target = typeof msg.target === 'string' && msg.target ? msg.target : '';
|
||||
var targeted = target ? (state.servers.filter(function (s) { return s.url === target; })[0] || { url: target }) : null;
|
||||
var shown = targeted || state.servers[0];
|
||||
if (shown) choose(shown);
|
||||
var auto = !!(msg.autoConnect && !manual && !tooOld && !msg.starting && !msg.notice && state.servers[0]);
|
||||
// The tab of the server used last; This Mac on a first run. An
|
||||
// automatic connect opens Codeman without looking at this Mac first:
|
||||
// that look runs a few processes and asks the server once more, and
|
||||
// it is only needed when the connect fails, which then asks for it.
|
||||
selectTab(state.servers[0] && !isLocalUrl(state.servers[0].url) ? 'remote' : 'local', auto);
|
||||
if (targeted) auto = !!(msg.connectNow && !tooOld && !msg.starting && !msg.notice);
|
||||
// The tab of that server; This Mac on a first run. An automatic
|
||||
// connect opens Codeman without looking at this Mac first: that look
|
||||
// runs a few processes and asks the server once more, and it is only
|
||||
// needed when the connect fails, which then asks for it.
|
||||
selectTab(shown && !isLocalUrl(shown.url) ? 'remote' : 'local', auto);
|
||||
if (msg.starting) {
|
||||
setBusy(true, false);
|
||||
setStatus('busy', 'Starting Codeman on this Mac…', msg.notice || '');
|
||||
|
||||
@@ -0,0 +1,373 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>All servers</title>
|
||||
<style>
|
||||
/* All servers (Cmd+0): one card per server tab, what needs you first. The
|
||||
native side sends the whole list, already ordered, on every change. */
|
||||
:root { color-scheme: dark; }
|
||||
* { box-sizing: border-box; }
|
||||
html { min-height: 100%; background: #0b0c0f; }
|
||||
body {
|
||||
margin: 0; min-height: 100%; overflow-x: hidden; background: #0b0c0f; color: #e8eaed;
|
||||
font: 13px/1.4 -apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, sans-serif;
|
||||
-webkit-user-select: none; user-select: none; cursor: default;
|
||||
}
|
||||
main { padding: 22px 28px 28px; }
|
||||
header { display: flex; align-items: baseline; flex-wrap: wrap; column-gap: 14px; row-gap: 4px; margin-bottom: 18px; }
|
||||
h1 { margin: 0; font-size: 20px; font-weight: 650; letter-spacing: -0.01em; }
|
||||
#summary { font-size: 13px; color: #8b9099; }
|
||||
#summary .needs { color: #fca5a5; }
|
||||
#summary .waiting { color: #fcd34d; }
|
||||
#grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(300px, 100%), 1fr)); gap: 18px; align-items: stretch; }
|
||||
|
||||
button { font: inherit; color: inherit; margin: 0; cursor: pointer; -webkit-user-select: none; user-select: none; }
|
||||
button:focus-visible { outline: 2px solid #3b82f6; outline-offset: 2px; }
|
||||
|
||||
.card {
|
||||
--c: #94a3b8;
|
||||
display: flex; flex-direction: column; min-width: 0; min-height: 236px; padding-top: 3px;
|
||||
border: 1px solid #23252b; border-radius: 12px; background: #121316;
|
||||
box-shadow: inset 0 3px 0 var(--c);
|
||||
}
|
||||
.card.urgent { border-color: rgba(248,113,113,0.45); }
|
||||
.card.offline { border-style: dashed; border-color: #30333b; background: #0f1013; box-shadow: inset 0 3px 0 #30333b; }
|
||||
.card.slim { min-height: 0; align-self: start; }
|
||||
|
||||
.head {
|
||||
display: flex; align-items: flex-start; gap: 10px; width: 100%; padding: 11px 16px 10px;
|
||||
border: 0; border-radius: 9px 9px 0 0; background: transparent; text-align: left;
|
||||
}
|
||||
.head:hover .name { text-decoration: underline; text-decoration-color: #3a3d45; text-underline-offset: 3px; }
|
||||
.head:focus-visible { outline-offset: -2px; }
|
||||
.title { flex: 1; min-width: 0; }
|
||||
.name { display: block; font-size: 15px; font-weight: 650; line-height: 1.35; color: #e8eaed; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.card.offline .name { color: #8b9099; }
|
||||
.url { display: block; margin-top: 2px; font-size: 12px; color: #8b9099; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.key { flex: none; padding-top: 2px; font-size: 12px; color: #6b7079; }
|
||||
|
||||
.body { flex: 1; min-height: 0; padding: 0 10px; }
|
||||
.row {
|
||||
display: flex; align-items: center; gap: 9px; width: 100%; padding: 7px 8px; margin: 0 0 3px;
|
||||
border: 0; border-radius: 8px; background: transparent; font-size: 12.5px; line-height: 18px; text-align: left;
|
||||
}
|
||||
.row:hover { background: #1a1c21; }
|
||||
.row.needs { background: rgba(248,113,113,0.10); }
|
||||
.row.needs:hover { background: rgba(248,113,113,0.16); }
|
||||
.row.waiting { background: rgba(251,191,36,0.07); }
|
||||
.row.waiting:hover { background: rgba(251,191,36,0.12); }
|
||||
.mark { flex: none; display: flex; align-items: center; justify-content: center; width: 18px; height: 18px; }
|
||||
.mark::before { content: ""; display: block; }
|
||||
.row.needs .mark { border-radius: 9px; background: #f87171; color: #2a0707; font-weight: 700; font-size: 11px; line-height: 18px; }
|
||||
.row.needs .mark::before { display: none; }
|
||||
.row.waiting .mark::before { width: 9px; height: 9px; border-radius: 50%; background: #fbbf24; }
|
||||
.row.working .mark::before {
|
||||
width: 11px; height: 11px; border-radius: 50%; border: 2px solid #60a5fa; border-right-color: transparent;
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
.row.idle .mark::before { width: 8px; height: 8px; border-radius: 50%; background: #3a3d45; }
|
||||
.sname { flex: 0 1 auto; min-width: 0; max-width: 55%; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.stext { flex: 1 1 0; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #8b9099; }
|
||||
.row.needs .stext { color: #fca5a5; }
|
||||
.row.waiting .stext { color: #fcd34d; }
|
||||
.row.idle .stext { color: #6b7079; }
|
||||
.more { padding: 3px 8px 0; font-size: 12px; color: #6b7079; }
|
||||
.note { display: flex; align-items: center; gap: 9px; padding: 4px 6px; font-size: 12.5px; color: #8b9099; }
|
||||
.note.warn { color: #fcd34d; }
|
||||
|
||||
.foot { display: flex; align-items: center; gap: 10px; margin-top: 10px; padding: 10px 16px 14px; border-top: 1px solid #1d1f24; }
|
||||
.meta { flex: 1; min-width: 0; font-size: 12px; color: #6b7079; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.action {
|
||||
flex: none; height: 28px; padding: 0 12px; border: 1px solid #30333b; border-radius: 7px;
|
||||
background: #16181d; color: #e8eaed; font-weight: 600; font-size: 12px;
|
||||
}
|
||||
.action:hover { background: #1d2026; border-color: #3a3d45; }
|
||||
.action.urgent { border-color: #ef4444; background: #ef4444; color: #ffffff; }
|
||||
.action.urgent:hover { border-color: #dc2626; background: #dc2626; }
|
||||
|
||||
.add {
|
||||
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px;
|
||||
min-height: 236px; padding: 0; border: 1.5px dashed #30333b; border-radius: 12px;
|
||||
background: transparent; color: #8b9099;
|
||||
}
|
||||
.add:hover { border-color: #3a3d45; color: #c9ccd2; }
|
||||
.add-ico { width: 40px; height: 40px; border-radius: 12px; border: 1.5px dashed #3a3d45; display: flex; align-items: center; justify-content: center; }
|
||||
.add-label { font-size: 13px; font-weight: 600; }
|
||||
.add-key { font-size: 12px; color: #6b7079; }
|
||||
|
||||
.spin {
|
||||
flex: none; width: 14px; height: 14px; border-radius: 50%;
|
||||
border: 2px solid #30333b; border-top-color: #60a5fa; animation: spin 0.9s linear infinite;
|
||||
}
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.row.working .mark::before, .spin { animation: none; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<header>
|
||||
<h1>All servers</h1>
|
||||
<span id="summary"></span>
|
||||
</header>
|
||||
<div id="grid"></div>
|
||||
</main>
|
||||
<script>
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var FALLBACK_COLOR = '#94a3b8';
|
||||
var COLOR_RE = /^#[0-9a-fA-F]{6}$/;
|
||||
var MAX_ROWS = 4;
|
||||
var STATES = ['needs', 'waiting', 'working', 'idle'];
|
||||
var SVG_NS = 'http://www.w3.org/2000/svg';
|
||||
|
||||
var grid = document.getElementById('grid');
|
||||
var summary = document.getElementById('summary');
|
||||
|
||||
function post(msg) { try { window.ipc.postMessage(JSON.stringify(msg)); } catch (e) { /* not in the app */ } }
|
||||
|
||||
// Names, URLs, versions and session texts come from servers: they are only
|
||||
// ever set as text, and a colour only after it passed the #rrggbb check.
|
||||
function str(v) { return typeof v === 'string' ? v : ''; }
|
||||
function color(v) { return typeof v === 'string' && COLOR_RE.test(v) ? v : FALLBACK_COLOR; }
|
||||
function count(v) {
|
||||
var n = Math.floor(Number(v));
|
||||
return isFinite(n) && n > 0 ? n : 0;
|
||||
}
|
||||
function shortcut(v) {
|
||||
var n = Number(v);
|
||||
return n >= 1 && n <= 9 && Math.floor(n) === n ? n : null;
|
||||
}
|
||||
function plural(n, one, many) { return n + ' ' + (n === 1 ? one : many); }
|
||||
|
||||
function normServer(s) {
|
||||
if (!s || typeof s !== 'object') return null;
|
||||
var tab = Number(s.tab);
|
||||
if (!isFinite(tab)) return null;
|
||||
var c = s.counts && typeof s.counts === 'object' ? s.counts : {};
|
||||
var sessions = [];
|
||||
(Array.isArray(s.sessions) ? s.sessions : []).forEach(function (x) {
|
||||
if (!x || typeof x !== 'object') return;
|
||||
sessions.push({
|
||||
id: str(x.id),
|
||||
name: str(x.name),
|
||||
state: STATES.indexOf(x.state) >= 0 ? x.state : 'idle',
|
||||
text: str(x.text)
|
||||
});
|
||||
});
|
||||
return {
|
||||
tab: tab,
|
||||
name: str(s.name),
|
||||
color: color(s.color),
|
||||
url: str(s.url),
|
||||
local: s.local === true,
|
||||
key: shortcut(s.key),
|
||||
version: str(s.version),
|
||||
kind: s.kind === 'connect' || s.kind === 'loading' ? s.kind : 'server',
|
||||
offline: s.offline === true,
|
||||
refused: s.refused === true,
|
||||
sessions: sessions,
|
||||
counts: {
|
||||
needsYou: count(c.needsYou),
|
||||
waiting: count(c.waiting),
|
||||
working: count(c.working),
|
||||
sessions: count(c.sessions)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function el(tag, cls, text) {
|
||||
var e = document.createElement(tag);
|
||||
if (cls) e.className = cls;
|
||||
if (text !== undefined) e.textContent = text;
|
||||
return e;
|
||||
}
|
||||
function button(cls, focusKey, text) {
|
||||
var b = el('button', cls, text);
|
||||
b.type = 'button';
|
||||
b.dataset.focus = focusKey;
|
||||
return b;
|
||||
}
|
||||
function plusIcon(size) {
|
||||
var s = document.createElementNS(SVG_NS, 'svg');
|
||||
s.setAttribute('width', String(size));
|
||||
s.setAttribute('height', String(size));
|
||||
s.setAttribute('viewBox', '0 0 16 16');
|
||||
s.setAttribute('fill', 'none');
|
||||
s.setAttribute('stroke', 'currentColor');
|
||||
s.setAttribute('stroke-width', '1.7');
|
||||
s.setAttribute('aria-hidden', 'true');
|
||||
var p = document.createElementNS(SVG_NS, 'path');
|
||||
p.setAttribute('d', 'M8 2.5v11M2.5 8h11');
|
||||
s.appendChild(p);
|
||||
return s;
|
||||
}
|
||||
|
||||
function renderSummary(servers) {
|
||||
var needs = 0, waiting = 0, working = 0, offline = 0;
|
||||
servers.forEach(function (s) {
|
||||
if (s.offline) { offline++; return; }
|
||||
needs += s.counts.needsYou;
|
||||
waiting += s.counts.waiting;
|
||||
working += s.counts.working;
|
||||
});
|
||||
var parts = [];
|
||||
if (needs) parts.push(el('span', 'needs', needs + (needs === 1 ? ' needs you' : ' need you')));
|
||||
if (waiting) parts.push(el('span', 'waiting', waiting + ' waiting'));
|
||||
if (working) parts.push(el('span', 'working', working + ' working'));
|
||||
if (offline) parts.push(el('span', 'offline', offline + ' offline'));
|
||||
if (!parts.length) parts.push(el('span', 'calm', 'Nothing needs you'));
|
||||
var out = [];
|
||||
parts.forEach(function (p, i) {
|
||||
if (i) out.push(document.createTextNode(' · '));
|
||||
out.push(p);
|
||||
});
|
||||
summary.replaceChildren.apply(summary, out);
|
||||
}
|
||||
|
||||
function sessionRow(s, x) {
|
||||
var row = button('row ' + x.state, 'row:' + s.tab + ':' + x.id);
|
||||
var mark = el('span', 'mark', x.state === 'needs' ? '!' : undefined);
|
||||
mark.setAttribute('aria-hidden', 'true');
|
||||
row.appendChild(mark);
|
||||
row.appendChild(el('span', 'sname', x.name || 'Untitled'));
|
||||
row.appendChild(el('span', 'stext', x.text));
|
||||
var said = { needs: 'needs you', waiting: 'waiting', working: 'working', idle: 'idle' }[x.state];
|
||||
row.setAttribute('aria-label', (x.name || 'Untitled') + ', ' + said + (x.text ? ': ' + x.text : ''));
|
||||
if (x.id) row.addEventListener('click', function () { post({ cmd: 'openSession', tab: s.tab, session: x.id }); });
|
||||
else row.disabled = true;
|
||||
return row;
|
||||
}
|
||||
|
||||
function card(s) {
|
||||
var c = el('section', 'card');
|
||||
c.style.setProperty('--c', s.color);
|
||||
var name = s.name || (s.kind === 'connect' ? 'New server tab' : 'Untitled');
|
||||
c.setAttribute('aria-label', name);
|
||||
|
||||
var head = button('head', 'head:' + s.tab);
|
||||
var title = el('span', 'title');
|
||||
title.appendChild(el('span', 'name', name));
|
||||
if (s.url) title.appendChild(el('span', 'url', s.url));
|
||||
head.appendChild(title);
|
||||
if (s.key) head.appendChild(el('span', 'key', '⌘' + s.key));
|
||||
head.addEventListener('click', function () { post({ cmd: 'open', tab: s.tab }); });
|
||||
c.appendChild(head);
|
||||
|
||||
var body = el('div', 'body');
|
||||
var meta = '';
|
||||
var action = button('action', 'act:' + s.tab, 'Open');
|
||||
var onAction = function () { post({ cmd: 'open', tab: s.tab }); };
|
||||
|
||||
if (s.kind === 'connect') {
|
||||
c.classList.add('slim');
|
||||
body.appendChild(el('div', 'note', 'Not connected yet'));
|
||||
} else if (s.kind === 'loading') {
|
||||
var note = el('div', 'note');
|
||||
note.appendChild(el('span', 'spin'));
|
||||
note.appendChild(document.createTextNode('Connecting…'));
|
||||
body.appendChild(note);
|
||||
} else if (s.offline) {
|
||||
c.classList.add('offline');
|
||||
body.appendChild(el('div', 'note', 'Not answering, the app keeps trying'));
|
||||
meta = s.version;
|
||||
action.textContent = 'Retry';
|
||||
onAction = function () { post({ cmd: 'retry', tab: s.tab }); };
|
||||
} else if (s.refused) {
|
||||
body.appendChild(el('div', 'note warn', 'The login was refused'));
|
||||
meta = s.version;
|
||||
} else {
|
||||
var shown = s.sessions.slice(0, MAX_ROWS);
|
||||
shown.forEach(function (x) { body.appendChild(sessionRow(s, x)); });
|
||||
var total = Math.max(s.counts.sessions, s.sessions.length);
|
||||
if (total > shown.length) body.appendChild(el('div', 'more', '+' + (total - shown.length) + ' more'));
|
||||
if (!total) body.appendChild(el('div', 'note', 'No sessions'));
|
||||
meta = plural(total, 'session', 'sessions') + (s.version ? ' · ' + s.version : '');
|
||||
if (s.counts.needsYou > 0) {
|
||||
c.classList.add('urgent');
|
||||
action.textContent = 'Answer';
|
||||
action.classList.add('urgent');
|
||||
// Answer goes straight to the first session that needs you, when the
|
||||
// list names it; else to the server.
|
||||
var first = s.sessions.filter(function (x) { return x.state === 'needs' && x.id; })[0];
|
||||
if (first) onAction = function () { post({ cmd: 'openSession', tab: s.tab, session: first.id }); };
|
||||
}
|
||||
}
|
||||
c.appendChild(body);
|
||||
|
||||
var foot = el('div', 'foot');
|
||||
foot.appendChild(el('span', 'meta', meta));
|
||||
action.setAttribute('aria-label', action.textContent + ' ' + name);
|
||||
action.addEventListener('click', onAction);
|
||||
foot.appendChild(action);
|
||||
c.appendChild(foot);
|
||||
return c;
|
||||
}
|
||||
|
||||
function addCard() {
|
||||
var b = button('add', 'new');
|
||||
b.setAttribute('aria-label', 'Add a server');
|
||||
var ico = el('span', 'add-ico');
|
||||
ico.appendChild(plusIcon(16));
|
||||
b.appendChild(ico);
|
||||
b.appendChild(el('span', 'add-label', 'Add a server'));
|
||||
b.appendChild(el('span', 'add-key', '⌘T'));
|
||||
b.addEventListener('click', function () { post({ cmd: 'new' }); });
|
||||
return b;
|
||||
}
|
||||
|
||||
var lastJson = null;
|
||||
|
||||
function render(servers) {
|
||||
// A state arrives every few seconds: the button that had the keyboard
|
||||
// focus gets it back in the new cards.
|
||||
var active = document.activeElement;
|
||||
var focusKey = active && active.dataset ? active.dataset.focus : '';
|
||||
renderSummary(servers);
|
||||
var cards = servers.map(card);
|
||||
cards.push(addCard());
|
||||
grid.replaceChildren.apply(grid, cards);
|
||||
if (focusKey) {
|
||||
var all = grid.querySelectorAll('[data-focus]');
|
||||
for (var i = 0; i < all.length; i++) {
|
||||
if (all[i].dataset.focus === focusKey) { all[i].focus({ preventScroll: true }); break; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function onNative(msg) {
|
||||
if (typeof msg === 'string') {
|
||||
try { msg = JSON.parse(msg); } catch (e) { return; }
|
||||
}
|
||||
if (!msg || typeof msg !== 'object' || msg.type !== 'state') return;
|
||||
var servers = [];
|
||||
var seen = new Set();
|
||||
(Array.isArray(msg.servers) ? msg.servers : []).forEach(function (raw) {
|
||||
var s = normServer(raw);
|
||||
if (!s || seen.has(s.tab)) return;
|
||||
seen.add(s.tab);
|
||||
servers.push(s);
|
||||
});
|
||||
var json = JSON.stringify(servers);
|
||||
if (json === lastJson) return;
|
||||
lastJson = json;
|
||||
render(servers);
|
||||
}
|
||||
|
||||
Object.defineProperty(window, '__codemanOverview', {
|
||||
value: Object.freeze({ onNative: onNative }),
|
||||
writable: false,
|
||||
configurable: false,
|
||||
enumerable: false
|
||||
});
|
||||
|
||||
render([]);
|
||||
post({ cmd: 'ready' });
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,609 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Codeman tabs</title>
|
||||
<style>
|
||||
/* The tab strip: a 38px web view across the top of the window, under the
|
||||
macOS traffic lights. One tab per Codeman server; the native side owns
|
||||
the tabs and sends the whole list on every change. */
|
||||
:root { color-scheme: dark; }
|
||||
* { box-sizing: border-box; }
|
||||
html, body { margin: 0; height: 100%; overflow: hidden; background: #141519; }
|
||||
body {
|
||||
font: 500 13px/1 -apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, sans-serif;
|
||||
color: #a3a8b1; cursor: default;
|
||||
-webkit-user-select: none; user-select: none;
|
||||
}
|
||||
#strip {
|
||||
position: relative; height: 38px; display: flex; align-items: flex-end; gap: 4px;
|
||||
padding: 0 8px 0 78px; overflow: hidden; background: #141519;
|
||||
}
|
||||
#strip.fullscreen { padding-left: 10px; }
|
||||
/* The bottom line is drawn under the tabs, so the active tab covers it and
|
||||
joins the page below. */
|
||||
#strip::after {
|
||||
content: ""; position: absolute; left: 0; right: 0; bottom: 0; height: 1px;
|
||||
background: #23252b; pointer-events: none; z-index: 1;
|
||||
}
|
||||
.icon-btn {
|
||||
align-self: center; flex: none; width: 28px; height: 28px; padding: 0; border: 0;
|
||||
border-radius: 7px; background: transparent; color: #8b9099;
|
||||
display: flex; align-items: center; justify-content: center; cursor: default; outline: none;
|
||||
}
|
||||
.icon-btn:hover { background: #1b1d22; color: #c9ccd2; }
|
||||
#overview { margin-right: 6px; }
|
||||
#overview.on { background: #2563eb; color: #ffffff; }
|
||||
#new { margin-left: 2px; }
|
||||
/* Empty strip moves the window, so some of it stays empty however many
|
||||
tabs there are. */
|
||||
#fill { flex: 1 0 48px; align-self: stretch; }
|
||||
|
||||
/* The tabs share the room evenly: 200px each, down to 72px; past that the
|
||||
row is clipped, never wrapped or scrolled. */
|
||||
#tabs {
|
||||
display: flex; align-items: flex-end; gap: 2px; flex: 0 1 auto; min-width: 0;
|
||||
height: 100%; overflow: hidden;
|
||||
}
|
||||
.tab {
|
||||
--c: #94a3b8;
|
||||
/* width, not only flex-basis: the row's own width is worked out from
|
||||
its tabs' widths, and flex-basis does not count there. */
|
||||
position: relative; flex: 0 1 auto; width: 200px; min-width: 72px; height: 31px;
|
||||
display: flex; align-items: center; gap: 8px; padding: 0 7px 0 10px;
|
||||
border-radius: 9px 9px 0 0; color: #a3a8b1; overflow: hidden;
|
||||
}
|
||||
.tab:hover { background: #1b1d22; }
|
||||
/* A thin line between two tabs neither in front nor under the pointer, so a
|
||||
badge at a tab's right end reads as that tab's and not the next one's. */
|
||||
.tab + .tab::before {
|
||||
content: ''; position: absolute; left: 0; top: 9px; bottom: 7px; width: 1px;
|
||||
background: #2c2f37; pointer-events: none;
|
||||
}
|
||||
.tab.active::before, .tab.active + .tab::before,
|
||||
.tab:hover::before, .tab:hover + .tab::before { display: none; }
|
||||
.tab.active {
|
||||
z-index: 2; background: #0b0c0f; color: #e8eaed;
|
||||
box-shadow: inset 0 2px 0 var(--c), inset 1px 0 0 #23252b, inset -1px 0 0 #23252b;
|
||||
}
|
||||
/* The tab button itself is a transparent layer over the whole tab, so a
|
||||
click anywhere on it is one target and the name, icon and badge stay
|
||||
plain text for the screen reader's label. */
|
||||
.hit {
|
||||
position: absolute; inset: 0; z-index: 0; margin: 0; padding: 0; border: 0;
|
||||
background: transparent; border-radius: inherit; cursor: default; outline: none;
|
||||
}
|
||||
.ico { flex: none; display: flex; color: var(--c); }
|
||||
.tab.connect .ico { color: #60a5fa; }
|
||||
.name { flex: 1 1 auto; min-width: 0; line-height: 16px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.tab.offline .name { color: #6b7079; }
|
||||
.tab.renaming .name { display: none; }
|
||||
.rename {
|
||||
position: relative; z-index: 1; flex: 1 1 auto; min-width: 0; height: 21px; margin: 0;
|
||||
padding: 0 5px; border: 1px solid #3b82f6; border-radius: 5px; background: #0b0c0f;
|
||||
color: #e8eaed; font: inherit; outline: none; -webkit-user-select: text; user-select: text;
|
||||
}
|
||||
.badge { flex: none; display: none; }
|
||||
.badge.needs {
|
||||
display: block; min-width: 18px; height: 18px; padding: 0 6px; border-radius: 9px;
|
||||
background: #f87171; color: #2a0707; font: 700 11px/18px -apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, sans-serif;
|
||||
text-align: center; font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.badge.waiting { display: block; width: 9px; height: 9px; border-radius: 50%; background: #fbbf24; }
|
||||
.badge.working {
|
||||
display: block; width: 11px; height: 11px; border-radius: 50%;
|
||||
border: 2px solid #60a5fa; border-right-color: transparent; animation: spin 1s linear infinite;
|
||||
}
|
||||
.badge.offline { display: block; width: 10px; height: 10px; border-radius: 50%; border: 1.5px dashed #6b7079; }
|
||||
.spin {
|
||||
display: block; width: 12px; height: 12px; margin: 1.5px; border-radius: 50%;
|
||||
border: 2px solid #30333b; border-top-color: var(--c); animation: spin 0.9s linear infinite;
|
||||
}
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
.close {
|
||||
position: relative; z-index: 1; flex: none; width: 16px; height: 16px; padding: 0; border: 0;
|
||||
border-radius: 4px; background: transparent; color: #8b9099; cursor: default; outline: none;
|
||||
display: none; align-items: center; justify-content: center;
|
||||
}
|
||||
.tab:hover .close, .tab.active .close { display: flex; }
|
||||
.close:hover { background: #2a2d34; color: #e8eaed; }
|
||||
/* Only while a tab is dragged do the others slide aside. */
|
||||
#tabs.dragging .tab { transition: transform 150ms ease; }
|
||||
#tabs.dragging .tab.lifted { transition: none; z-index: 3; background: #1b1d22; }
|
||||
#tabs.dragging .tab.lifted.active { background: #0b0c0f; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.badge.working, .spin { animation: none; }
|
||||
#tabs.dragging .tab { transition: none; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="strip">
|
||||
<button id="overview" class="icon-btn" type="button" tabindex="-1" aria-label="All servers" aria-pressed="false" title="All servers (⌘0)">
|
||||
<svg width="15" height="15" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><rect x="1.5" y="1.5" width="5" height="5" rx="1.2"></rect><rect x="9.5" y="1.5" width="5" height="5" rx="1.2"></rect><rect x="1.5" y="9.5" width="5" height="5" rx="1.2"></rect><rect x="9.5" y="9.5" width="5" height="5" rx="1.2"></rect></svg>
|
||||
</button>
|
||||
<div id="tabs" role="tablist" aria-label="Servers"></div>
|
||||
<button id="new" class="icon-btn" type="button" tabindex="-1" aria-label="New server tab" title="New server tab (⌘T)">
|
||||
<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true"><path d="M8 2.5v11M2.5 8h11"></path></svg>
|
||||
</button>
|
||||
<div id="fill"></div>
|
||||
</div>
|
||||
<script>
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var FALLBACK_COLOR = '#94a3b8';
|
||||
var COLOR_RE = /^#[0-9a-fA-F]{6}$/;
|
||||
var MAX_NAME = 40;
|
||||
var DRAG_START_PX = 4;
|
||||
var SVG_NS = 'http://www.w3.org/2000/svg';
|
||||
|
||||
var strip = document.getElementById('strip');
|
||||
var tabsEl = document.getElementById('tabs');
|
||||
var overviewBtn = document.getElementById('overview');
|
||||
var newBtn = document.getElementById('new');
|
||||
|
||||
function post(msg) { try { window.ipc.postMessage(JSON.stringify(msg)); } catch (e) { /* not in the app */ } }
|
||||
|
||||
// Everything below arrives from the native side, and most of it was typed
|
||||
// on a server (names, URLs): it is only ever set as text or as a checked
|
||||
// attribute value, never parsed as markup or CSS.
|
||||
function str(v) { return typeof v === 'string' ? v : ''; }
|
||||
function color(v) { return typeof v === 'string' && COLOR_RE.test(v) ? v : FALLBACK_COLOR; }
|
||||
function count(v) {
|
||||
var n = Math.floor(Number(v));
|
||||
return isFinite(n) && n > 0 ? n : 0;
|
||||
}
|
||||
function shortcut(v) {
|
||||
var n = Number(v);
|
||||
return n >= 1 && n <= 9 && Math.floor(n) === n ? n : null;
|
||||
}
|
||||
|
||||
function normTab(t) {
|
||||
if (!t || typeof t !== 'object') return null;
|
||||
var id = Number(t.id);
|
||||
if (!isFinite(id)) return null;
|
||||
var st = t.status && typeof t.status === 'object' ? t.status : {};
|
||||
return {
|
||||
id: id,
|
||||
name: str(t.name),
|
||||
color: color(t.color),
|
||||
active: t.active === true,
|
||||
kind: t.kind === 'connect' || t.kind === 'loading' ? t.kind : 'server',
|
||||
local: t.local === true,
|
||||
url: str(t.url),
|
||||
key: shortcut(t.key),
|
||||
needs: count(st.needsYou),
|
||||
waiting: count(st.waiting),
|
||||
working: count(st.working),
|
||||
offline: st.offline === true
|
||||
};
|
||||
}
|
||||
|
||||
// One badge, by precedence: needs you, waiting, working, not answering.
|
||||
function badgeOf(t) {
|
||||
if (t.kind === 'connect') return '';
|
||||
if (t.needs) return 'needs';
|
||||
if (t.waiting) return 'waiting';
|
||||
if (t.working) return 'working';
|
||||
if (t.offline) return 'offline';
|
||||
return '';
|
||||
}
|
||||
|
||||
function statusWords(t) {
|
||||
if (t.kind === 'loading') return ['Connecting'];
|
||||
if (t.kind === 'connect') return [];
|
||||
var out = [];
|
||||
if (t.needs) out.push(t.needs + (t.needs === 1 ? ' needs you' : ' need you'));
|
||||
if (t.waiting) out.push(t.waiting + ' waiting');
|
||||
if (t.working) out.push(t.working + ' working');
|
||||
if (t.offline) out.push('Not answering');
|
||||
return out;
|
||||
}
|
||||
|
||||
function displayName(t) { return t.name || 'Untitled'; }
|
||||
|
||||
// ---- icons (fixed shapes from this file; no outside text goes in) ----
|
||||
function svg(size, width, parts) {
|
||||
var s = document.createElementNS(SVG_NS, 'svg');
|
||||
s.setAttribute('width', String(size));
|
||||
s.setAttribute('height', String(size));
|
||||
s.setAttribute('viewBox', '0 0 16 16');
|
||||
s.setAttribute('fill', 'none');
|
||||
s.setAttribute('stroke', 'currentColor');
|
||||
s.setAttribute('stroke-width', String(width));
|
||||
s.setAttribute('aria-hidden', 'true');
|
||||
parts.forEach(function (p) {
|
||||
var el = document.createElementNS(SVG_NS, p[0]);
|
||||
Object.keys(p[1]).forEach(function (k) { el.setAttribute(k, p[1][k]); });
|
||||
s.appendChild(el);
|
||||
});
|
||||
return s;
|
||||
}
|
||||
var ICONS = {
|
||||
local: function () {
|
||||
return svg(15, 1.5, [['rect', { x: '2.5', y: '3', width: '11', height: '7.5', rx: '1.2' }], ['path', { d: 'M1 13h14' }]]);
|
||||
},
|
||||
server: function () {
|
||||
return svg(15, 1.5, [
|
||||
['rect', { x: '2', y: '2', width: '12', height: '5', rx: '1.2' }],
|
||||
['rect', { x: '2', y: '9', width: '12', height: '5', rx: '1.2' }],
|
||||
['path', { d: 'M4.5 4.5h1M4.5 11.5h1' }]
|
||||
]);
|
||||
},
|
||||
connect: function () { return svg(15, 1.7, [['path', { d: 'M8 2.5v11M2.5 8h11' }]]); },
|
||||
loading: function () {
|
||||
var s = document.createElement('span');
|
||||
s.className = 'spin';
|
||||
return s;
|
||||
},
|
||||
close: function () { return svg(10, 1.6, [['path', { d: 'M3 3l10 10M13 3L3 13' }]]); }
|
||||
};
|
||||
function iconKind(t) {
|
||||
if (t.kind === 'connect' || t.kind === 'loading') return t.kind;
|
||||
return t.local ? 'local' : 'server';
|
||||
}
|
||||
|
||||
// ---- state ----
|
||||
var state = { tabs: [], overviewActive: false, fullscreen: false };
|
||||
var lastJson = '';
|
||||
var views = new Map(); // tab id -> the tab's elements and what they show
|
||||
var renaming = null; // { id, input, initial }
|
||||
var drag = null; // a press on a tab that may turn into a drag
|
||||
var pendingRender = false;
|
||||
var rendering = false;
|
||||
var suppressClick = false;
|
||||
|
||||
function createView(id) {
|
||||
var root = document.createElement('div');
|
||||
root.className = 'tab';
|
||||
root.setAttribute('role', 'presentation');
|
||||
root.dataset.id = String(id);
|
||||
var hit = document.createElement('button');
|
||||
hit.type = 'button';
|
||||
hit.className = 'hit';
|
||||
hit.tabIndex = -1;
|
||||
hit.setAttribute('role', 'tab');
|
||||
var ico = document.createElement('span');
|
||||
ico.className = 'ico';
|
||||
ico.setAttribute('aria-hidden', 'true');
|
||||
var name = document.createElement('span');
|
||||
name.className = 'name';
|
||||
name.setAttribute('aria-hidden', 'true');
|
||||
var badge = document.createElement('span');
|
||||
badge.className = 'badge';
|
||||
badge.setAttribute('aria-hidden', 'true');
|
||||
var close = document.createElement('button');
|
||||
close.type = 'button';
|
||||
close.className = 'close';
|
||||
close.tabIndex = -1;
|
||||
close.setAttribute('aria-label', 'Close tab');
|
||||
close.title = 'Close tab';
|
||||
close.appendChild(ICONS.close());
|
||||
root.appendChild(hit);
|
||||
root.appendChild(ico);
|
||||
root.appendChild(name);
|
||||
root.appendChild(badge);
|
||||
root.appendChild(close);
|
||||
var v = { id: id, root: root, hit: hit, ico: ico, name: name, badge: badge, close: close, icon: '', badgeKind: null, tab: null };
|
||||
views.set(id, v);
|
||||
return v;
|
||||
}
|
||||
|
||||
function updateView(v, t) {
|
||||
v.tab = t;
|
||||
var bk = badgeOf(t);
|
||||
var cls = 'tab' + (t.active ? ' active' : '') + (bk === 'offline' ? ' offline' : '') +
|
||||
(t.kind !== 'server' ? ' ' + t.kind : '') + (renaming && renaming.id === t.id ? ' renaming' : '');
|
||||
if (v.root.className !== cls) v.root.className = cls;
|
||||
v.root.style.setProperty('--c', t.color);
|
||||
var ik = iconKind(t);
|
||||
if (v.icon !== ik) {
|
||||
v.icon = ik;
|
||||
v.ico.replaceChildren(ICONS[ik]());
|
||||
}
|
||||
var label = displayName(t);
|
||||
if (v.name.textContent !== label) v.name.textContent = label;
|
||||
var btext = bk === 'needs' ? (t.needs > 99 ? '99+' : String(t.needs)) : '';
|
||||
if (v.badgeKind !== bk + btext) {
|
||||
v.badgeKind = bk + btext;
|
||||
v.badge.className = 'badge' + (bk ? ' ' + bk : '');
|
||||
v.badge.textContent = btext;
|
||||
}
|
||||
var words = statusWords(t);
|
||||
v.hit.setAttribute('aria-selected', t.active ? 'true' : 'false');
|
||||
v.hit.setAttribute('aria-label', [label].concat(words).join(', '));
|
||||
// The strip is too short for a hover card under it, so the native
|
||||
// tooltip carries the same lines.
|
||||
var lines = [label + (t.key ? ' ⌘' + t.key : '')];
|
||||
if (t.url) lines.push(t.url);
|
||||
v.hit.title = lines.concat(words).join('\n');
|
||||
}
|
||||
|
||||
function render() {
|
||||
if (drag && drag.active) { pendingRender = true; return; }
|
||||
pendingRender = false;
|
||||
rendering = true;
|
||||
strip.classList.toggle('fullscreen', state.fullscreen);
|
||||
overviewBtn.classList.toggle('on', state.overviewActive);
|
||||
overviewBtn.setAttribute('aria-pressed', state.overviewActive ? 'true' : 'false');
|
||||
var seen = new Set();
|
||||
state.tabs.forEach(function (t, i) {
|
||||
var v = views.get(t.id) || createView(t.id);
|
||||
updateView(v, t);
|
||||
seen.add(t.id);
|
||||
var at = tabsEl.children[i];
|
||||
if (at !== v.root) tabsEl.insertBefore(v.root, at || null);
|
||||
});
|
||||
views.forEach(function (v, id) {
|
||||
if (seen.has(id)) return;
|
||||
if (renaming && renaming.id === id) endRename('gone');
|
||||
v.root.remove();
|
||||
views.delete(id);
|
||||
});
|
||||
rendering = false;
|
||||
// Moving a tab in the row takes the focus from a rename under way: give it back.
|
||||
if (renaming && document.activeElement !== renaming.input) renaming.input.focus();
|
||||
}
|
||||
|
||||
function applyState(msg) {
|
||||
var seen = new Set();
|
||||
var tabs = [];
|
||||
(Array.isArray(msg.tabs) ? msg.tabs : []).forEach(function (raw) {
|
||||
var t = normTab(raw);
|
||||
if (!t || seen.has(t.id)) return;
|
||||
seen.add(t.id);
|
||||
tabs.push(t);
|
||||
});
|
||||
var next = { tabs: tabs, overviewActive: msg.overviewActive === true, fullscreen: msg.fullscreen === true };
|
||||
var json = JSON.stringify(next);
|
||||
if (json === lastJson && !pendingRender) return;
|
||||
lastJson = json;
|
||||
state = next;
|
||||
render();
|
||||
}
|
||||
|
||||
// ---- rename ----
|
||||
function startRename(id) {
|
||||
var v = views.get(id);
|
||||
if (!v || (drag && drag.active)) return;
|
||||
if (renaming) {
|
||||
if (renaming.id === id) { renaming.input.focus(); return; }
|
||||
endRename('commit');
|
||||
}
|
||||
var input = document.createElement('input');
|
||||
input.type = 'text';
|
||||
input.className = 'rename';
|
||||
input.maxLength = MAX_NAME;
|
||||
input.spellcheck = false;
|
||||
input.autocomplete = 'off';
|
||||
input.setAttribute('aria-label', 'Tab name');
|
||||
input.value = v.tab ? v.tab.name.slice(0, MAX_NAME) : '';
|
||||
renaming = { id: id, input: input, before: v.tab ? v.tab.name : '', initial: input.value.trim() };
|
||||
v.root.classList.add('renaming');
|
||||
v.root.insertBefore(input, v.badge);
|
||||
input.addEventListener('keydown', function (ev) {
|
||||
ev.stopPropagation();
|
||||
if (ev.key === 'Enter') { ev.preventDefault(); endRename('commit'); }
|
||||
else if (ev.key === 'Escape') { ev.preventDefault(); endRename('cancel'); }
|
||||
});
|
||||
input.addEventListener('blur', function () {
|
||||
if (rendering) return;
|
||||
if (renaming && renaming.input === input) endRename('commit');
|
||||
});
|
||||
// The keyboard reaches this field only while this web view is the first
|
||||
// responder, and the native side hands it back to the page below after
|
||||
// every other click on the strip: ask for it.
|
||||
post({ cmd: 'editing' });
|
||||
input.focus();
|
||||
input.select();
|
||||
}
|
||||
|
||||
// how: 'commit' (Enter, a click elsewhere), 'cancel' (Escape) or 'gone'
|
||||
// (the tab was closed). Every rename that ends on a tab still there posts
|
||||
// one rename, a cancelled or unchanged one with the name the tab had: the
|
||||
// native side takes that as "rename finished" and hands the keyboard back
|
||||
// to the page below.
|
||||
function endRename(how) {
|
||||
var r = renaming;
|
||||
if (!r) return;
|
||||
renaming = null;
|
||||
var name = r.input.value.trim().slice(0, MAX_NAME);
|
||||
r.input.remove();
|
||||
var v = views.get(r.id);
|
||||
if (v) v.root.classList.remove('renaming');
|
||||
if (how === 'gone') return;
|
||||
if (how === 'cancel' || name === r.initial) {
|
||||
post({ cmd: 'rename', id: r.id, name: r.before });
|
||||
return;
|
||||
}
|
||||
// Shown at once; an empty name is the default the native side picks.
|
||||
if (v && name) v.name.textContent = name;
|
||||
post({ cmd: 'rename', id: r.id, name: name });
|
||||
}
|
||||
|
||||
// ---- drag to reorder ----
|
||||
function beginDrag() {
|
||||
var roots = Array.prototype.slice.call(tabsEl.children);
|
||||
drag.roots = roots;
|
||||
drag.from = roots.indexOf(drag.root);
|
||||
if (drag.from < 0) { drag = null; return; }
|
||||
drag.rects = roots.map(function (r) { return r.getBoundingClientRect(); });
|
||||
var r0 = drag.rects[drag.from];
|
||||
var gap = roots.length > 1 ? drag.rects[1].left - drag.rects[0].right : 0;
|
||||
drag.step = r0.width + gap;
|
||||
drag.to = drag.from;
|
||||
drag.active = true;
|
||||
if (renaming) endRename('commit');
|
||||
try { drag.root.setPointerCapture(drag.pointerId); } catch (e) { /* the pointer is gone */ }
|
||||
tabsEl.classList.add('dragging');
|
||||
drag.root.classList.add('lifted');
|
||||
}
|
||||
|
||||
function moveDrag(dx) {
|
||||
var rects = drag.rects;
|
||||
var r0 = rects[drag.from];
|
||||
var minDx = rects[0].left - r0.left;
|
||||
var maxDx = rects[rects.length - 1].right - r0.right;
|
||||
dx = Math.max(minDx, Math.min(maxDx, dx));
|
||||
drag.root.style.transform = 'translateX(' + dx + 'px)';
|
||||
var centre = r0.left + r0.width / 2 + dx;
|
||||
// A tab after the dragged one is passed once the centres meet, not only once they cross:
|
||||
// the clamp stops a tab dragged all the way right with its centre ON the last tab's
|
||||
// centre, and a strict comparison there left it one place short of the end.
|
||||
var to = 0;
|
||||
for (var i = 0; i < rects.length; i++) {
|
||||
if (i === drag.from) continue;
|
||||
var c = rects[i].left + rects[i].width / 2;
|
||||
if (i > drag.from ? centre >= c : centre > c) to++;
|
||||
}
|
||||
drag.to = to;
|
||||
drag.roots.forEach(function (r, i) {
|
||||
if (i === drag.from) return;
|
||||
var shift = 0;
|
||||
if (drag.from < to && i > drag.from && i <= to) shift = -drag.step;
|
||||
else if (to < drag.from && i >= to && i < drag.from) shift = drag.step;
|
||||
r.style.transform = shift ? 'translateX(' + shift + 'px)' : '';
|
||||
});
|
||||
}
|
||||
|
||||
function endDrag(commit) {
|
||||
var d = drag;
|
||||
drag = null;
|
||||
if (!d || !d.active) return;
|
||||
try { d.root.releasePointerCapture(d.pointerId); } catch (e) { /* already released */ }
|
||||
// The slide stops before the tabs move, so nothing animates back.
|
||||
tabsEl.classList.remove('dragging');
|
||||
d.root.classList.remove('lifted');
|
||||
d.roots.forEach(function (r) { r.style.transform = ''; });
|
||||
// The click that ends a drag is not a select.
|
||||
suppressClick = true;
|
||||
setTimeout(function () { suppressClick = false; }, 0);
|
||||
if (commit && d.to !== d.from) {
|
||||
var at = state.tabs.findIndex(function (t) { return t.id === d.id; });
|
||||
if (at >= 0) {
|
||||
var moved = state.tabs.splice(at, 1)[0];
|
||||
state.tabs.splice(d.to, 0, moved);
|
||||
lastJson = JSON.stringify(state);
|
||||
}
|
||||
post({ cmd: 'move', id: d.id, to: d.to });
|
||||
pendingRender = true;
|
||||
}
|
||||
if (pendingRender) render();
|
||||
}
|
||||
|
||||
function tabOf(target) {
|
||||
var root = target && target.closest ? target.closest('.tab') : null;
|
||||
return root && views.has(Number(root.dataset.id)) ? Number(root.dataset.id) : null;
|
||||
}
|
||||
function inside(target, sel) { return !!(target && target.closest && target.closest(sel)); }
|
||||
|
||||
// ---- events ----
|
||||
var middleDownOn = null;
|
||||
|
||||
document.addEventListener('mousedown', function (ev) {
|
||||
var t = ev.target;
|
||||
if (renaming && t !== renaming.input) endRename('commit');
|
||||
if (inside(t, 'input')) return;
|
||||
// The strip never takes the focus or starts a selection.
|
||||
ev.preventDefault();
|
||||
if (ev.button === 1) { middleDownOn = tabOf(t); return; }
|
||||
if (ev.button !== 0 || ev.ctrlKey) return;
|
||||
if (inside(t, '.tab, button')) return;
|
||||
// The second press of a double click zooms, as a title bar does. Decided
|
||||
// here, not on dblclick: the first press's window drag may keep WebKit
|
||||
// from ever seeing a dblclick.
|
||||
if (ev.detail === 2) post({ cmd: 'zoom' });
|
||||
if (ev.detail > 1) return;
|
||||
post({ cmd: 'drag' });
|
||||
});
|
||||
|
||||
// Middle click closes, as in a browser (auxclick is not in every WebKit).
|
||||
document.addEventListener('mouseup', function (ev) {
|
||||
if (ev.button !== 1) return;
|
||||
var id = tabOf(ev.target);
|
||||
if (id !== null && id === middleDownOn) post({ cmd: 'close', id: id });
|
||||
middleDownOn = null;
|
||||
});
|
||||
|
||||
document.addEventListener('dblclick', function (ev) {
|
||||
var t = ev.target;
|
||||
var id = tabOf(t);
|
||||
if (id !== null) {
|
||||
if (!inside(t, '.close, input')) startRename(id);
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
// WebKit's own menu (Reload, Inspect Element) never shows on the strip,
|
||||
// the rename field included; only a tab has a menu, the native one, and
|
||||
// not while its name is being typed.
|
||||
document.addEventListener('contextmenu', function (ev) {
|
||||
ev.preventDefault();
|
||||
var id = inside(ev.target, 'input') ? null : tabOf(ev.target);
|
||||
if (id !== null) post({ cmd: 'menu', id: id });
|
||||
});
|
||||
|
||||
tabsEl.addEventListener('click', function (ev) {
|
||||
if (suppressClick) { suppressClick = false; return; }
|
||||
if (ev.ctrlKey) return; // a Control-click is the right click: the menu answers it
|
||||
var id = tabOf(ev.target);
|
||||
if (id === null || inside(ev.target, 'input')) return;
|
||||
if (inside(ev.target, '.close')) post({ cmd: 'close', id: id });
|
||||
else post({ cmd: 'select', id: id });
|
||||
});
|
||||
|
||||
tabsEl.addEventListener('pointerdown', function (ev) {
|
||||
if (ev.button !== 0 || ev.ctrlKey || !ev.isPrimary) return;
|
||||
var id = tabOf(ev.target);
|
||||
if (id === null || inside(ev.target, '.close, input')) return;
|
||||
drag = { id: id, root: views.get(id).root, pointerId: ev.pointerId, startX: ev.clientX, active: false };
|
||||
});
|
||||
|
||||
document.addEventListener('pointermove', function (ev) {
|
||||
if (!drag || ev.pointerId !== drag.pointerId) return;
|
||||
var dx = ev.clientX - drag.startX;
|
||||
if (!drag.active) {
|
||||
if (Math.abs(dx) < DRAG_START_PX) return;
|
||||
beginDrag();
|
||||
if (!drag) return;
|
||||
}
|
||||
moveDrag(dx);
|
||||
});
|
||||
|
||||
document.addEventListener('pointerup', function (ev) {
|
||||
if (drag && ev.pointerId === drag.pointerId) endDrag(true);
|
||||
});
|
||||
document.addEventListener('pointercancel', function (ev) {
|
||||
if (drag && ev.pointerId === drag.pointerId) endDrag(false);
|
||||
});
|
||||
window.addEventListener('blur', function () { if (drag) endDrag(false); });
|
||||
|
||||
overviewBtn.addEventListener('click', function () { post({ cmd: 'overview' }); });
|
||||
newBtn.addEventListener('click', function () { post({ cmd: 'new' }); });
|
||||
|
||||
function onNative(msg) {
|
||||
if (typeof msg === 'string') {
|
||||
try { msg = JSON.parse(msg); } catch (e) { return; }
|
||||
}
|
||||
if (!msg || typeof msg !== 'object') return;
|
||||
if (msg.type === 'state') applyState(msg);
|
||||
else if (msg.type === 'rename') {
|
||||
var id = Number(msg.id);
|
||||
if (isFinite(id)) startRename(id);
|
||||
}
|
||||
}
|
||||
|
||||
Object.defineProperty(window, '__codemanTabs', {
|
||||
value: Object.freeze({ onNative: onNative }),
|
||||
writable: false,
|
||||
configurable: false,
|
||||
enumerable: false
|
||||
});
|
||||
|
||||
post({ cmd: 'ready' });
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -57,6 +57,10 @@ pub enum Poll {
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Session {
|
||||
#[serde(default)]
|
||||
id: String,
|
||||
#[serde(default)]
|
||||
name: Option<String>,
|
||||
#[serde(default)]
|
||||
status: String,
|
||||
#[serde(default)]
|
||||
@@ -80,11 +84,20 @@ fn count_working(body: &str) -> Option<u32> {
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Approval {
|
||||
#[serde(default)]
|
||||
kind: String,
|
||||
#[serde(default, rename = "acknowledgedAt")]
|
||||
#[serde(default)]
|
||||
acknowledged_at: Option<f64>,
|
||||
#[serde(default)]
|
||||
session_id: String,
|
||||
#[serde(default)]
|
||||
tool_name: Option<String>,
|
||||
#[serde(default)]
|
||||
tool_summary: Option<String>,
|
||||
#[serde(default)]
|
||||
message: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -108,6 +121,145 @@ fn read_alerts(body: &str) -> Option<(bool, bool)> {
|
||||
Some((waiting, needs_you))
|
||||
}
|
||||
|
||||
/// What one agent session is doing, most urgent first (`SessionState::rank`).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SessionState {
|
||||
/// Stopped on a permission or a question: a red tab.
|
||||
Needs,
|
||||
/// Finished, and nobody has looked yet: a yellow tab.
|
||||
Waiting,
|
||||
/// At work.
|
||||
Working,
|
||||
Idle,
|
||||
}
|
||||
|
||||
impl SessionState {
|
||||
pub fn rank(self) -> u8 {
|
||||
match self {
|
||||
SessionState::Needs => 0,
|
||||
SessionState::Waiting => 1,
|
||||
SessionState::Working => 2,
|
||||
SessionState::Idle => 3,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One agent session of a server, for the tab badges and the overview. `name`
|
||||
/// and `text` come from the server: the pages that show them treat them as
|
||||
/// text.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SessionRow {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub state: SessionState,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// Every agent session of a server and what it is doing. Shell tabs are left
|
||||
/// out, as for the logo.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Detail {
|
||||
pub sessions: Vec<SessionRow>,
|
||||
}
|
||||
|
||||
impl Detail {
|
||||
/// The same answer `Poller::poll` gives for this server.
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
pub fn activity(&self) -> Activity {
|
||||
let any = |state: SessionState| self.sessions.iter().any(|s| s.state == state);
|
||||
Activity {
|
||||
working: any(SessionState::Working),
|
||||
waiting: any(SessionState::Waiting),
|
||||
needs_you: any(SessionState::Needs),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum DetailPoll {
|
||||
Seen(Detail),
|
||||
Failed,
|
||||
/// 401 or 403: the login is refused (or must be changed first). Asking
|
||||
/// again would count against the login rate limit.
|
||||
Refused,
|
||||
/// 429: too many failed logins from this address, maybe other clients'.
|
||||
/// Worth asking again, much later.
|
||||
RateLimited,
|
||||
}
|
||||
|
||||
/// How long a server's text may be in a row of the overview, in characters.
|
||||
const MAX_ROW_TEXT: usize = 160;
|
||||
const MAX_ROW_NAME: usize = 80;
|
||||
/// How many sessions of one server are kept, so a server cannot make the app
|
||||
/// hold a list of any length.
|
||||
const MAX_SESSIONS: usize = 200;
|
||||
|
||||
/// Server text for a row: control characters out, whitespace runs folded,
|
||||
/// cut at `max` characters.
|
||||
fn row_text(raw: &str, max: usize) -> String {
|
||||
let folded = raw
|
||||
.split(|c: char| c.is_whitespace() || c.is_control())
|
||||
.filter(|w| !w.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
match folded.char_indices().nth(max) {
|
||||
Some((cut, _)) => format!("{}\u{2026}", &folded[..cut]),
|
||||
None => folded,
|
||||
}
|
||||
}
|
||||
|
||||
/// The detail of a server from its two answers: `GET api/sessions` and, when
|
||||
/// the server has it, `GET api/approvals` (None: an older server, no alerts).
|
||||
/// None when the sessions answer is not a list of sessions.
|
||||
pub fn read_detail(sessions_body: &str, approvals_body: Option<&str>) -> Option<Detail> {
|
||||
let (Sessions::Envelope { data: sessions } | Sessions::Bare(sessions)) =
|
||||
serde_json::from_str(sessions_body).ok()?;
|
||||
let approvals: Vec<Approval> = approvals_body
|
||||
.and_then(|body| serde_json::from_str::<ApprovalsAnswer>(body).ok())
|
||||
.map(|a| a.data.approvals)
|
||||
.unwrap_or_default();
|
||||
let rows = sessions
|
||||
.into_iter()
|
||||
.filter(|s| s.mode != "shell" && !s.id.is_empty())
|
||||
.take(MAX_SESSIONS)
|
||||
.map(|s| {
|
||||
let mine = || approvals.iter().filter(|a| a.session_id == s.id);
|
||||
let urgent = mine().find(|a| a.kind == "permission" || a.kind == "question");
|
||||
let waiting = mine().any(|a| a.kind == "idle" && a.acknowledged_at.is_none());
|
||||
let (state, text) = if let Some(a) = urgent {
|
||||
let text = match (a.kind.as_str(), &a.tool_name, &a.tool_summary, &a.message) {
|
||||
("permission", Some(tool), Some(summary), _) => format!("{tool}: {summary}"),
|
||||
("permission", Some(tool), None, _) => format!("Allow {tool}?"),
|
||||
(_, _, _, Some(message)) => message.clone(),
|
||||
("question", _, _, None) => "Has a question for you".to_string(),
|
||||
_ => "Needs your permission".to_string(),
|
||||
};
|
||||
(SessionState::Needs, text)
|
||||
} else if waiting {
|
||||
(SessionState::Waiting, "Finished, waiting for you".to_string())
|
||||
} else if s.status == "busy" {
|
||||
(SessionState::Working, "Working".to_string())
|
||||
} else {
|
||||
(SessionState::Idle, "Idle".to_string())
|
||||
};
|
||||
let name = s.name.as_deref().map(|n| row_text(n, MAX_ROW_NAME)).unwrap_or_default();
|
||||
let name = if name.is_empty() {
|
||||
s.id.chars().take(8).collect()
|
||||
} else {
|
||||
name
|
||||
};
|
||||
SessionRow {
|
||||
id: s.id,
|
||||
name,
|
||||
state,
|
||||
text: row_text(&text, MAX_ROW_TEXT),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
Some(Detail { sessions: rows })
|
||||
}
|
||||
|
||||
/// `name=value` out of a `Set-Cookie` header, for Codeman's session cookie.
|
||||
fn session_cookie(header: &str) -> Option<&str> {
|
||||
let pair = header.split(';').next()?.trim();
|
||||
@@ -215,6 +367,29 @@ impl Poller {
|
||||
(activity.waiting, activity.needs_you) = self.alerts;
|
||||
Poll::Seen(activity)
|
||||
}
|
||||
|
||||
/// Every agent session and what it is doing (`read_detail`), for a server
|
||||
/// tab's badges and the overview. Needs a poller made with `alerts`.
|
||||
pub fn detail(&mut self) -> DetailPoll {
|
||||
let url = self.sessions_url.clone();
|
||||
let sessions = match self.ask(&url) {
|
||||
Some((200, Some(body))) => body,
|
||||
Some((429, _)) => return DetailPoll::RateLimited,
|
||||
Some((s, _)) if refused(s) => return DetailPoll::Refused,
|
||||
_ => return DetailPoll::Failed,
|
||||
};
|
||||
let approvals = match self.approvals_url.clone() {
|
||||
Some(url) => match self.ask(&url) {
|
||||
Some((200, body)) => body,
|
||||
Some((429, _)) => return DetailPoll::RateLimited,
|
||||
Some((s, _)) if refused(s) => return DetailPoll::Refused,
|
||||
// An older server has no list; a failed read counts as none.
|
||||
_ => None,
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
read_detail(&sessions, approvals.as_deref()).map_or(DetailPoll::Failed, DetailPoll::Seen)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -462,4 +637,66 @@ mod tests {
|
||||
let server = Url::parse(&format!("http://127.0.0.1:{port}/")).unwrap();
|
||||
assert_eq!(Poller::new(&server, None, false).unwrap().poll(), Poll::Failed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detail_reads_every_agent_session_and_its_state() {
|
||||
let sessions = r#"{"success":true,"data":[
|
||||
{"id":"s1","name":"webshop","status":"busy","mode":"claude"},
|
||||
{"id":"s2","name":"billing","status":"idle","mode":"claude"},
|
||||
{"id":"s3","name":"docs","status":"idle","mode":"codex"},
|
||||
{"id":"s4","name":"shell","status":"busy","mode":"shell"},
|
||||
{"id":"s5","status":"idle","mode":"claude"},
|
||||
{"id":"s6","name":" two\n lines\u0007 ","status":"idle","mode":"claude"}]}"#;
|
||||
let approvals = r#"{"success":true,"data":{"approvals":[
|
||||
{"sessionId":"s2","kind":"permission","toolName":"Bash","toolSummary":"npm run migrate"},
|
||||
{"sessionId":"s3","kind":"idle"},
|
||||
{"sessionId":"s5","kind":"idle","acknowledgedAt":1},
|
||||
{"sessionId":"s6","kind":"question","message":"Which locale first?"}]}}"#;
|
||||
let detail = read_detail(sessions, Some(approvals)).unwrap();
|
||||
let states: Vec<(&str, SessionState, &str)> = detail
|
||||
.sessions
|
||||
.iter()
|
||||
.map(|s| (s.id.as_str(), s.state, s.text.as_str()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
states,
|
||||
[
|
||||
("s1", SessionState::Working, "Working"),
|
||||
("s2", SessionState::Needs, "Bash: npm run migrate"),
|
||||
("s3", SessionState::Waiting, "Finished, waiting for you"),
|
||||
("s5", SessionState::Idle, "Idle"),
|
||||
("s6", SessionState::Needs, "Which locale first?"),
|
||||
]
|
||||
);
|
||||
// A session with no name shows its id's start; server text is folded.
|
||||
assert_eq!(detail.sessions[3].name, "s5");
|
||||
assert_eq!(detail.sessions[4].name, "two lines");
|
||||
assert_eq!(
|
||||
detail.activity(),
|
||||
Activity {
|
||||
working: true,
|
||||
waiting: true,
|
||||
needs_you: true
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detail_without_approvals_and_from_junk() {
|
||||
let bare = r#"[{"id":"a","name":"x","status":"busy","mode":"claude"}]"#;
|
||||
let detail = read_detail(bare, None).unwrap();
|
||||
assert_eq!(detail.sessions.len(), 1);
|
||||
assert_eq!(detail.sessions[0].state, SessionState::Working);
|
||||
assert_eq!(read_detail("not json", None), None);
|
||||
assert_eq!(read_detail(r#"{"success":true,"data":{}}"#, None), None);
|
||||
// A junk approvals answer counts as none.
|
||||
assert_eq!(read_detail(bare, Some("<html>")).unwrap().sessions.len(), 1);
|
||||
let long = format!(
|
||||
r#"[{{"id":"a","name":"{}","status":"idle","mode":"claude"}}]"#,
|
||||
"n".repeat(500)
|
||||
);
|
||||
let name = &read_detail(&long, None).unwrap().sessions[0].name;
|
||||
assert_eq!(name.chars().count(), MAX_ROW_NAME + 1);
|
||||
assert!(name.ends_with('\u{2026}'));
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,10 @@ use std::borrow::Cow;
|
||||
use wry::http::{header::CONTENT_TYPE, Request, Response, StatusCode};
|
||||
|
||||
const CONNECT_HTML: &[u8] = include_bytes!("../assets/connect.html");
|
||||
/// The tab strip across the top of the window, and the overview of every
|
||||
/// server (tabs.rs).
|
||||
const TABS_HTML: &[u8] = include_bytes!("../assets/tabs.html");
|
||||
const OVERVIEW_HTML: &[u8] = include_bytes!("../assets/overview.html");
|
||||
const ICON_PNG: &[u8] = include_bytes!("../assets/icon.png");
|
||||
|
||||
/// The connect page loads nothing from outside the app.
|
||||
@@ -14,6 +18,8 @@ const CSP: &str = "default-src 'none'; script-src 'unsafe-inline'; style-src 'un
|
||||
pub fn respond(request: Request<Vec<u8>>) -> Response<Cow<'static, [u8]>> {
|
||||
let (body, mime): (&'static [u8], &str) = match request.uri().path() {
|
||||
"/" | "/index.html" => (CONNECT_HTML, "text/html; charset=utf-8"),
|
||||
"/tabs.html" => (TABS_HTML, "text/html; charset=utf-8"),
|
||||
"/overview.html" => (OVERVIEW_HTML, "text/html; charset=utf-8"),
|
||||
"/icon.png" => (ICON_PNG, "image/png"),
|
||||
_ => {
|
||||
return Response::builder()
|
||||
@@ -59,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;
|
||||
@@ -113,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);
|
||||
@@ -220,6 +248,24 @@ pub fn refused_script(session_id: Option<&str>) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// Hands a message to one of the app's own pages: the connect page
|
||||
/// (`__codemanDesktop`), the tab strip (`__codemanTabs`) or the overview
|
||||
/// (`__codemanOverview`). The message is JSON, which is also a JavaScript
|
||||
/// expression.
|
||||
pub fn native_message_script(global: &str, msg: &serde_json::Value) -> String {
|
||||
format!("window.{global} && window.{global}.onNative({msg})")
|
||||
}
|
||||
|
||||
/// Selects a session in Codeman's page, as a click on its tab would (the
|
||||
/// overview's rows). `id` has passed `tabs::is_session_id`, and goes in as a
|
||||
/// JSON string all the same.
|
||||
pub fn select_session_script(id: &str) -> String {
|
||||
let id = serde_json::to_string(id).unwrap_or_else(|_| "\"\"".into());
|
||||
format!(
|
||||
"try {{ if (window.app && typeof window.app.selectSession === 'function') window.app.selectSession({id}); }} catch (e) {{}}"
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -248,6 +294,26 @@ mod tests {
|
||||
assert_eq!(get("/other.js").status(), StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serves_the_strip_and_the_overview() {
|
||||
for (path, global) in [("/tabs.html", "__codemanTabs"), ("/overview.html", "__codemanOverview")] {
|
||||
let page = get(path);
|
||||
assert_eq!(page.status(), StatusCode::OK, "{path}");
|
||||
assert_eq!(page.headers()["content-security-policy"], CSP, "{path}");
|
||||
assert!(String::from_utf8_lossy(page.body()).contains(global), "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_scripts_carry_json() {
|
||||
let msg = serde_json::json!({ "type": "state", "name": "a\"b</script>" });
|
||||
let script = native_message_script("__codemanTabs", &msg);
|
||||
assert!(script.starts_with("window.__codemanTabs && window.__codemanTabs.onNative({"));
|
||||
assert!(script.contains(r#""a\"b</script>""#));
|
||||
let select = select_session_script("abc-1");
|
||||
assert!(select.contains(r#"selectSession("abc-1")"#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_script_escapes_the_session_id() {
|
||||
let js = refused_script(Some("a'\"); alert(1); //\u{2028}\\"));
|
||||
@@ -278,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}");
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const MAX_SERVERS: usize = 8;
|
||||
/// How many server tabs are saved for the next launch.
|
||||
pub const MAX_TABS: usize = 24;
|
||||
/// How many recovery copies of an unreadable config can sit side by side:
|
||||
/// `desktop.json.corrupt`, then `desktop.json.corrupt.1` to `.9`.
|
||||
const ASIDE_SLOTS: usize = 10;
|
||||
@@ -59,6 +61,50 @@ pub struct Config {
|
||||
/// make the whole file unreadable, which would cost the server list.
|
||||
#[serde(deserialize_with = "lenient_window")]
|
||||
pub window: Option<WindowFrame>,
|
||||
/// The server tabs to open again at the next launch, in strip order. Only
|
||||
/// tabs that belong to a server are kept. Read leniently, like `window`.
|
||||
#[serde(deserialize_with = "lenient_tabs")]
|
||||
pub tabs: Vec<TabEntry>,
|
||||
/// The tab that was in front, an index into `tabs`.
|
||||
#[serde(deserialize_with = "lenient_index")]
|
||||
pub active_tab: usize,
|
||||
/// The one server whose pages keep WebKit's default data store, so the
|
||||
/// local storage it had before tabs existed (Codeman's per-device settings)
|
||||
/// stays with it; every other server gets a store of its own
|
||||
/// (`tabs::store_id`). None: not decided yet, which the first launch with
|
||||
/// tabs does (the most recent server, or `Some("")` for none).
|
||||
#[serde(deserialize_with = "lenient_string", skip_serializing_if = "Option::is_none")]
|
||||
pub default_store_server: Option<String>,
|
||||
}
|
||||
|
||||
/// One saved tab: the server it is for, and what the user made of it.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TabEntry {
|
||||
pub url: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub color: Option<String>,
|
||||
}
|
||||
|
||||
fn lenient_tabs<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<TabEntry>, D::Error> {
|
||||
let value = serde_json::Value::deserialize(d)?;
|
||||
let list = value.as_array().cloned().unwrap_or_default();
|
||||
Ok(list
|
||||
.into_iter()
|
||||
.filter_map(|v| serde_json::from_value::<TabEntry>(v).ok())
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn lenient_index<'de, D: serde::Deserializer<'de>>(d: D) -> Result<usize, D::Error> {
|
||||
let value = serde_json::Value::deserialize(d)?;
|
||||
Ok(value.as_u64().and_then(|n| usize::try_from(n).ok()).unwrap_or(0))
|
||||
}
|
||||
|
||||
fn lenient_string<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
||||
let value = serde_json::Value::deserialize(d)?;
|
||||
Ok(value.as_str().map(str::to_owned))
|
||||
}
|
||||
|
||||
fn lenient_window<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<WindowFrame>, D::Error> {
|
||||
@@ -83,6 +129,9 @@ impl Default for Config {
|
||||
logo_blink: BlinkStyles::default(),
|
||||
keep_awake: keep_awake::Settings::default(),
|
||||
window: None,
|
||||
tabs: Vec::new(),
|
||||
active_tab: 0,
|
||||
default_store_server: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,6 +390,35 @@ impl Config {
|
||||
self.servers.retain(|s| !s.url.is_empty() && seen.insert(s.url.clone()));
|
||||
self.servers.truncate(MAX_SERVERS);
|
||||
self.window = self.window.and_then(WindowFrame::sanitized);
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
self.tabs.retain(|t| !t.url.is_empty() && seen.insert(t.url.clone()));
|
||||
self.tabs.truncate(MAX_TABS);
|
||||
for tab in &mut self.tabs {
|
||||
tab.name = tab.name.as_deref().and_then(crate::tabs::clean_name);
|
||||
tab.color = tab.color.take().filter(|c| crate::tabs::is_color(c));
|
||||
}
|
||||
if self.active_tab >= self.tabs.len() {
|
||||
self.active_tab = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Settle `default_store_server` once: the server used last keeps the data
|
||||
/// store it always had. True when it changed (the caller saves).
|
||||
pub fn settle_default_store(&mut self) -> bool {
|
||||
if self.default_store_server.is_some() {
|
||||
return false;
|
||||
}
|
||||
self.default_store_server = Some(self.servers.first().map(|s| s.url.clone()).unwrap_or_default());
|
||||
true
|
||||
}
|
||||
|
||||
/// The data store a server's pages use: None for WebKit's default one,
|
||||
/// else the server's own (`tabs::store_id`).
|
||||
pub fn store_for(&self, url: &str) -> Option<[u8; 16]> {
|
||||
match &self.default_store_server {
|
||||
Some(server) if server == url => None,
|
||||
_ => Some(crate::tabs::store_id(url)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Move (or add) a server to the top of the recent list. Returns the
|
||||
@@ -898,4 +976,83 @@ mod tests {
|
||||
};
|
||||
assert!(full.fitted_to(&tiny, MIN).unwrap().fullscreen);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tabs_round_trip_and_bad_values_are_dropped() {
|
||||
let dir = tmp_dir("tabs");
|
||||
let path = dir.join("desktop.json");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::write(
|
||||
&path,
|
||||
r##"{"servers":[],"activeTab":7,"tabs":[
|
||||
{"url":"http://127.0.0.1:3000/","name":" Mine ","color":"#A78BFA"},
|
||||
{"url":"http://127.0.0.1:3000/","name":"again"},
|
||||
{"url":"https://studio.example.ts.net/","color":"red;x"},
|
||||
{"url":""},
|
||||
42,
|
||||
{"name":"no url"}]}"##,
|
||||
)
|
||||
.unwrap();
|
||||
let (c, can_save) = Config::load_from(&path);
|
||||
assert!(can_save);
|
||||
assert_eq!(
|
||||
c.tabs,
|
||||
[
|
||||
TabEntry {
|
||||
url: "http://127.0.0.1:3000/".into(),
|
||||
name: Some("Mine".into()),
|
||||
color: Some("#A78BFA".into()),
|
||||
},
|
||||
TabEntry {
|
||||
url: "https://studio.example.ts.net/".into(),
|
||||
name: None,
|
||||
color: None,
|
||||
},
|
||||
]
|
||||
);
|
||||
// An index past the list falls back to the first tab.
|
||||
assert_eq!(c.active_tab, 0);
|
||||
c.save_to(&path).unwrap();
|
||||
let (again, _) = Config::load_from(&path);
|
||||
assert_eq!(again.tabs, c.tabs);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_tab_value_never_costs_the_server_list() {
|
||||
let dir = tmp_dir("badtabs");
|
||||
let path = dir.join("desktop.json");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::write(
|
||||
&path,
|
||||
r#"{"servers":[{"url":"http://a/"}],"tabs":"nope","activeTab":-3,"defaultStoreServer":5}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (c, can_save) = Config::load_from(&path);
|
||||
assert!(can_save);
|
||||
assert_eq!(c.servers.len(), 1);
|
||||
assert!(c.tabs.is_empty());
|
||||
assert_eq!(c.active_tab, 0);
|
||||
assert_eq!(c.default_store_server, None);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_server_used_last_keeps_the_default_store() {
|
||||
let mut c = Config::default();
|
||||
let _ = c.remember("http://old/", None, false);
|
||||
let _ = c.remember("http://recent/", None, false);
|
||||
assert!(c.settle_default_store());
|
||||
assert_eq!(c.default_store_server.as_deref(), Some("http://recent/"));
|
||||
// Decided once: a later connect does not move it.
|
||||
let _ = c.remember("http://old/", None, false);
|
||||
assert!(!c.settle_default_store());
|
||||
assert_eq!(c.store_for("http://recent/"), None);
|
||||
assert_eq!(c.store_for("http://old/"), Some(crate::tabs::store_id("http://old/")));
|
||||
// A first run with no server keeps no server on the default store.
|
||||
let mut fresh = Config::default();
|
||||
assert!(fresh.settle_default_store());
|
||||
assert_eq!(fresh.default_store_server.as_deref(), Some(""));
|
||||
assert!(fresh.store_for("http://x/").is_some());
|
||||
}
|
||||
}
|
||||
+103
-43
@@ -1165,14 +1165,33 @@ fn watch(logo: &impl Logo, marker: &Marker, styles: BlinkStyles, signals: &mut i
|
||||
}
|
||||
}
|
||||
|
||||
/// The one line the app writes to the child.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
/// The one line the app writes to the child: every open server tab, each with
|
||||
/// its login, and the styles. The logo shows the most urgent state of all of
|
||||
/// them together.
|
||||
#[derive(Serialize, Deserialize, PartialEq)]
|
||||
struct Connection {
|
||||
server: String,
|
||||
authorization: Option<String>,
|
||||
servers: Vec<Target>,
|
||||
styles: BlinkStyles,
|
||||
}
|
||||
|
||||
/// One server the child asks.
|
||||
#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
|
||||
pub struct Target {
|
||||
pub server: String,
|
||||
pub authorization: Option<String>,
|
||||
}
|
||||
|
||||
/// What several servers' agents do together: each state holds when it holds on
|
||||
/// any of them.
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
fn merged(all: &[Activity]) -> Activity {
|
||||
all.iter().fold(Activity::default(), |acc, a| Activity {
|
||||
working: acc.working || a.working,
|
||||
waiting: acc.waiting || a.waiting,
|
||||
needs_you: acc.needs_you || a.needs_you,
|
||||
})
|
||||
}
|
||||
|
||||
/// The app's side: the pipe to the child, which is all there is to it.
|
||||
#[derive(Default)]
|
||||
pub struct Watcher {
|
||||
@@ -1185,27 +1204,23 @@ impl Watcher {
|
||||
self.current.is_some()
|
||||
}
|
||||
|
||||
/// Watch this server with this login in these styles, or nothing. A child
|
||||
/// for anything else ends first: its pipe closes with the old value. It is
|
||||
/// back to normal well before the next child looks, which takes `SETTLE`.
|
||||
pub fn sync(&mut self, want: Option<(&str, Option<&str>, BlinkStyles)>) {
|
||||
let same = match (&self.current, want) {
|
||||
(Some((now, _)), Some((server, authorization, styles))) => {
|
||||
now.server == server && now.authorization.as_deref() == authorization && now.styles == styles
|
||||
}
|
||||
/// Watch these servers with their logins in these styles, or nothing (an
|
||||
/// empty list is nothing too). A child for anything else ends first: its
|
||||
/// pipe closes with the old value. It is back to normal well before the
|
||||
/// next child looks, which takes `SETTLE`.
|
||||
pub fn sync(&mut self, want: Option<(Vec<Target>, BlinkStyles)>) {
|
||||
let want = want
|
||||
.filter(|(servers, _)| !servers.is_empty())
|
||||
.map(|(servers, styles)| Connection { servers, styles });
|
||||
let same = match (&self.current, &want) {
|
||||
(Some((now, _)), Some(want)) => now == want,
|
||||
(None, None) => true,
|
||||
_ => false,
|
||||
};
|
||||
if same {
|
||||
return;
|
||||
}
|
||||
self.current = want.and_then(|(server, authorization, styles)| {
|
||||
spawn_child(Connection {
|
||||
server: server.to_owned(),
|
||||
authorization: authorization.map(str::to_owned),
|
||||
styles,
|
||||
})
|
||||
});
|
||||
self.current = want.and_then(spawn_child);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1843,16 +1858,25 @@ mod system {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs for the life of the child. A server that does not answer counts as
|
||||
/// nothing going on, and one that refuses the login is never asked again.
|
||||
fn poll_until_refused(mut poller: Poller, shared: &Mutex<Activity>) {
|
||||
/// Runs for the life of the child, one per server. A server that does not
|
||||
/// answer counts as nothing going on, and one that refuses the login is
|
||||
/// never asked again. Each writes its own slot, and `shared` is what all of
|
||||
/// them say together (`merged`).
|
||||
fn poll_until_refused(mut poller: Poller, index: usize, slots: &Mutex<Vec<Activity>>, shared: &Mutex<Activity>) {
|
||||
loop {
|
||||
let poll = poller.poll();
|
||||
if let Ok(mut activity) = shared.lock() {
|
||||
*activity = match poll {
|
||||
Poll::Seen(seen) => seen,
|
||||
_ => Activity::default(),
|
||||
};
|
||||
let seen = match poll {
|
||||
Poll::Seen(seen) => seen,
|
||||
_ => Activity::default(),
|
||||
};
|
||||
let all = slots.lock().ok().map(|mut slots| {
|
||||
if let Some(slot) = slots.get_mut(index) {
|
||||
*slot = seen;
|
||||
}
|
||||
super::merged(&slots)
|
||||
});
|
||||
if let (Some(all), Ok(mut activity)) = (all, shared.lock()) {
|
||||
*activity = all;
|
||||
}
|
||||
if poll == Poll::Refused {
|
||||
return;
|
||||
@@ -1877,18 +1901,19 @@ mod system {
|
||||
.read_line(&mut line)
|
||||
.ok()
|
||||
.and_then(|_| serde_json::from_str::<Connection>(&line).ok());
|
||||
let Some(Connection {
|
||||
server,
|
||||
authorization,
|
||||
styles,
|
||||
}) = connection
|
||||
else {
|
||||
let Some(Connection { servers, styles }) = connection else {
|
||||
std::process::exit(0);
|
||||
};
|
||||
let poller = Url::parse(&server)
|
||||
.ok()
|
||||
.and_then(|url| Poller::new(&url, authorization, styles.wants_alerts()));
|
||||
let (Some(poller), Some(logo)) = (poller, SystemLogo::open()) else {
|
||||
let pollers: Vec<Poller> = servers
|
||||
.into_iter()
|
||||
.filter_map(|target| {
|
||||
Url::parse(&target.server)
|
||||
.ok()
|
||||
.and_then(|url| Poller::new(&url, target.authorization, styles.wants_alerts()))
|
||||
})
|
||||
.collect();
|
||||
let logo = SystemLogo::open();
|
||||
let Some(logo) = logo.filter(|_| !pollers.is_empty()) else {
|
||||
std::process::exit(0);
|
||||
};
|
||||
|
||||
@@ -1900,8 +1925,12 @@ mod system {
|
||||
let _ = closed.send(());
|
||||
});
|
||||
let activity = Arc::new(Mutex::new(Activity::default()));
|
||||
let found = activity.clone();
|
||||
std::thread::spawn(move || poll_until_refused(poller, &found));
|
||||
let slots = Arc::new(Mutex::new(vec![Activity::default(); pollers.len()]));
|
||||
for (index, poller) in pollers.into_iter().enumerate() {
|
||||
let found = activity.clone();
|
||||
let slots = slots.clone();
|
||||
std::thread::spawn(move || poll_until_refused(poller, index, &slots, &found));
|
||||
}
|
||||
|
||||
let mut signals = Live {
|
||||
pipe_closed,
|
||||
@@ -3371,15 +3400,17 @@ mod tests {
|
||||
fn the_connection_line_round_trips_with_and_without_a_login() {
|
||||
for authorization in [None, Some("Basic abc".to_string())] {
|
||||
let line = serde_json::to_string(&Connection {
|
||||
server: "http://127.0.0.1:3000/".into(),
|
||||
authorization: authorization.clone(),
|
||||
servers: vec![Target {
|
||||
server: "http://127.0.0.1:3000/".into(),
|
||||
authorization: authorization.clone(),
|
||||
}],
|
||||
styles: WORK,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(!line.contains('\n'), "one line");
|
||||
let back: Connection = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!(back.server, "http://127.0.0.1:3000/");
|
||||
assert_eq!(back.authorization, authorization);
|
||||
assert_eq!(back.servers[0].server, "http://127.0.0.1:3000/");
|
||||
assert_eq!(back.servers[0].authorization, authorization);
|
||||
assert_eq!(back.styles, WORK);
|
||||
}
|
||||
}
|
||||
@@ -3686,4 +3717,33 @@ mod tests {
|
||||
watcher.sync(None);
|
||||
assert!(watcher.current.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_servers_merge_into_one_logo() {
|
||||
assert_eq!(merged(&[]), Activity::default());
|
||||
assert_eq!(merged(&[working(), Activity::default()]), working());
|
||||
let all = merged(&[working(), needs_you(), waiting()]);
|
||||
assert!(all.working && all.waiting && all.needs_you);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_child_line_names_every_server() {
|
||||
let line = serde_json::to_string(&Connection {
|
||||
servers: vec![
|
||||
Target {
|
||||
server: "http://127.0.0.1:3000/".into(),
|
||||
authorization: None,
|
||||
},
|
||||
Target {
|
||||
server: "https://studio.example.ts.net/".into(),
|
||||
authorization: Some("Basic eA==".into()),
|
||||
},
|
||||
],
|
||||
styles: WORK,
|
||||
})
|
||||
.unwrap();
|
||||
let back: Connection = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!(back.servers.len(), 2);
|
||||
assert_eq!(back.servers[1].authorization.as_deref(), Some("Basic eA=="));
|
||||
}
|
||||
}
|
||||
+294
-74
@@ -21,8 +21,14 @@
|
||||
//! of it: every challenge comes back here and gets the login of that moment,
|
||||
//! never one an earlier connect left behind.
|
||||
//!
|
||||
//! Two smaller helpers live here too: `clear_cookies`, which empties the web
|
||||
//! views' cookie jar before a login so an earlier user's session cookie cannot
|
||||
//! Each server tab hands over a login of its own (`set_credentials`, keyed by
|
||||
//! the tab), and a challenge is answered with the login of the tab whose server
|
||||
//! it is (`pick`), and only to a web view of that tab (`bind_view`), so two
|
||||
//! tabs never answer for each other, even when one tab's page fetches from
|
||||
//! the other's server.
|
||||
//!
|
||||
//! Two smaller helpers live here too: `clear_cookies`, which removes one
|
||||
//! server's cookies before a login so an earlier user's session cookie cannot
|
||||
//! win over the new login, and `content_size`, the window's content area.
|
||||
//!
|
||||
//! `install` adds the missing methods to the classes of the delegates wry made,
|
||||
@@ -145,6 +151,40 @@ fn bare_host(host: &str) -> &str {
|
||||
host.strip_prefix('[').and_then(|h| h.strip_suffix(']')).unwrap_or(host)
|
||||
}
|
||||
|
||||
/// Which tab's login a challenge is for. The URL that got the 401 belongs to
|
||||
/// the tab whose server the protection space names and whose base path holds
|
||||
/// it, the deepest one when several do (a server at `/` and another below a
|
||||
/// path on the same origin, behind one proxy); then that tab answers only when
|
||||
/// the URL is in its scope (`policy::challenge_in_scope`). So a web tab of the
|
||||
/// deeper server never gets the login of the server above it. None: no tab's
|
||||
/// server, so WebKit's own handling.
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
fn pick<'a>(challenge: &Challenge<'_>, saved: &'a [(u64, BasicCredentials)]) -> Option<(u64, &'a BasicCredentials)> {
|
||||
let failed = challenge.failed?;
|
||||
let (tab, owner) = saved
|
||||
.iter()
|
||||
.filter(|(_, s)| {
|
||||
credentials_match(s, challenge.scheme, challenge.host, challenge.port)
|
||||
&& crate::policy::within_base(failed, &s.server)
|
||||
})
|
||||
.max_by_key(|(_, s)| s.server.path().len())?;
|
||||
crate::policy::challenge_in_scope(failed, &owner.server).then_some((*tab, owner))
|
||||
}
|
||||
|
||||
/// Whether a cookie the store keeps for `domain` goes to pages of `host`: a
|
||||
/// host-only cookie of that host (Codeman's own, which names no domain), or a
|
||||
/// domain cookie (`.example.ts.net`) the host lies under. Case-insensitive,
|
||||
/// IPv6 brackets ignored.
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
fn cookie_for_host(domain: &str, host: &str) -> bool {
|
||||
let host = bare_host(host).to_ascii_lowercase();
|
||||
let domain = bare_host(domain.trim()).to_ascii_lowercase();
|
||||
match domain.strip_prefix('.') {
|
||||
Some(parent) => host == parent || host.ends_with(&domain),
|
||||
None => !domain.is_empty() && host == domain,
|
||||
}
|
||||
}
|
||||
|
||||
/// How a dialog names the page that opened it ("localhost:3000"), from a
|
||||
/// security origin's host and port (0 = the scheme's default, left out).
|
||||
fn origin_label(host: &str, port: i64) -> Option<String> {
|
||||
@@ -182,25 +222,51 @@ pub fn install(webview: &wry::WebView) {
|
||||
imp::install(webview);
|
||||
}
|
||||
|
||||
/// The login HTTP Basic challenges from that server are answered with
|
||||
/// (`None`: answer none), from the next challenge on: WebKit keeps no copy of
|
||||
/// an earlier one. Also re-arms the refusal report. Main thread only.
|
||||
/// The login HTTP Basic challenges from tab `tab`'s server are answered with
|
||||
/// (`None`: that tab answers none), from the next challenge on: WebKit keeps
|
||||
/// no copy of an earlier one. Also re-arms that tab's refusal report. Main
|
||||
/// thread only.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn set_credentials(creds: Option<BasicCredentials>) {
|
||||
imp::set_credentials(creds);
|
||||
pub fn set_credentials(tab: u64, creds: Option<BasicCredentials>) {
|
||||
imp::set_credentials(tab, creds);
|
||||
}
|
||||
|
||||
/// Called on the main thread, once per `set_credentials`, when the server
|
||||
/// refused the saved login. It runs inside a WebKit callback, so it should
|
||||
/// only post an event, never touch windows directly.
|
||||
/// Called on the main thread with the tab, once per `set_credentials` of that
|
||||
/// tab, when its server refused the saved login. It runs inside a WebKit
|
||||
/// callback, so it should only post an event, never touch windows directly.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn set_auth_rejected_handler(handler: Box<dyn Fn()>) {
|
||||
pub fn set_auth_rejected_handler(handler: Box<dyn Fn(u64)>) {
|
||||
imp::set_auth_rejected_handler(handler);
|
||||
}
|
||||
|
||||
/// Removes every cookie from the app's default website data store, which all
|
||||
/// of its web views use, then calls `done`. Only cookies: local storage, where
|
||||
/// Codeman keeps per-device settings, stays. Main thread only.
|
||||
/// Ties a web view to a tab: a Basic challenge from that web view is answered
|
||||
/// with that tab's login only, never another tab's, whatever server the
|
||||
/// request went to. Call it for every server page and pop-out web view. Main
|
||||
/// thread only.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn bind_view(webview: &wry::WebView, tab: u64) {
|
||||
imp::bind_view(webview, tab);
|
||||
}
|
||||
|
||||
/// A closed tab's web views answer no challenge any more.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn forget_tab(tab: u64) {
|
||||
imp::forget_tab(tab);
|
||||
}
|
||||
|
||||
/// Whether WebKit gives each server a data store of its own
|
||||
/// (`dataStoreForIdentifier:`, macOS 14 and later). wry falls back to the
|
||||
/// default store without it, and so does `clear_cookies`.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn own_stores_available() -> bool {
|
||||
imp::os_major_version() >= 14
|
||||
}
|
||||
|
||||
/// Removes the cookies of `host` (`cookie_for_host`) from a data store: the
|
||||
/// server's own (`store`, on a macOS that has them) or the default one, then
|
||||
/// calls `done`. Only that host's cookies, so the other servers' tabs stay
|
||||
/// logged in, and only cookies: local storage, where Codeman keeps
|
||||
/// per-device settings, stays. Main thread only.
|
||||
///
|
||||
/// `done` runs exactly once, on the main thread, as its own operation on the
|
||||
/// main queue: never before this returns and never inside a WebKit callback.
|
||||
@@ -209,8 +275,8 @@ pub fn set_auth_rejected_handler(handler: Box<dyn Fn()>) {
|
||||
/// nothing and calls `done` right away on the calling thread. If WebKit never
|
||||
/// answers at all, `done` never runs: the caller's own deadline covers that.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn clear_cookies(done: Box<dyn FnOnce()>) {
|
||||
imp::clear_cookies(done);
|
||||
pub fn clear_cookies(store: Option<[u8; 16]>, host: String, done: Box<dyn FnOnce()>) {
|
||||
imp::clear_cookies(store, host, done);
|
||||
}
|
||||
|
||||
/// The window's content area in points (`contentRectForFrameRect` of its
|
||||
@@ -244,28 +310,38 @@ mod imp {
|
||||
use objc2::{msg_send, sel, ClassType, Message};
|
||||
use objc2_app_kit::{NSAlert, NSAlertFirstButtonReturn, NSTextField, NSView, NSWindow};
|
||||
use objc2_foundation::{
|
||||
MainThreadMarker, NSDate, NSInteger, NSOperationQueue, NSPoint, NSRect, NSSet, NSSize, NSString,
|
||||
NSURLAuthenticationChallenge, NSURLAuthenticationMethodHTTPBasic, NSURLCredential, NSURLCredentialPersistence,
|
||||
NSURLProtectionSpace, NSURLRequest, NSURLResponse, NSURLSessionAuthChallengeDisposition, NSURL,
|
||||
MainThreadMarker, NSArray, NSHTTPCookie, NSInteger, NSOperationQueue, NSPoint, NSProcessInfo, NSRect, NSSize,
|
||||
NSString, NSURLAuthenticationChallenge, NSURLAuthenticationMethodHTTPBasic, NSURLCredential,
|
||||
NSURLCredentialPersistence, NSURLProtectionSpace, NSURLRequest, NSURLResponse,
|
||||
NSURLSessionAuthChallengeDisposition, NSURL, NSUUID,
|
||||
};
|
||||
use objc2_web_kit::{WKFrameInfo, WKSecurityOrigin, WKWebsiteDataStore, WKWebsiteDataTypeCookies};
|
||||
use objc2_web_kit::{WKFrameInfo, WKSecurityOrigin, WKWebsiteDataStore};
|
||||
use tao::platform::macos::WindowExtMacOS;
|
||||
use url::Url;
|
||||
use wry::WebViewExtMacOS;
|
||||
|
||||
use super::{decide, dialog_title, origin_label, BasicCredentials, Challenge, ChallengeAnswer};
|
||||
use super::{
|
||||
cookie_for_host, decide, dialog_title, origin_label, pick, BasicCredentials, Challenge, ChallengeAnswer,
|
||||
};
|
||||
|
||||
/// Page text in a dialog is cut at this many UTF-16 units, so a huge
|
||||
/// message cannot push the alert's buttons off the screen.
|
||||
const MAX_DIALOG_UTF16: usize = 2000;
|
||||
|
||||
/// What the app is told, with the tab, when a server refuses its login.
|
||||
type RejectedHandler = Rc<dyn Fn(u64)>;
|
||||
|
||||
thread_local! {
|
||||
/// The login challenges are answered with; `None` answers none.
|
||||
static SAVED: RefCell<Option<BasicCredentials>> = const { RefCell::new(None) };
|
||||
/// The server refused `SAVED` and the app was told; `set_credentials` clears it.
|
||||
static REJECTED: Cell<bool> = const { Cell::new(false) };
|
||||
/// Told once when the server refuses `SAVED`.
|
||||
static ON_REJECTED: RefCell<Option<Rc<dyn Fn()>>> = const { RefCell::new(None) };
|
||||
/// The login of each tab that has one, by tab.
|
||||
static SAVED: RefCell<Vec<(u64, BasicCredentials)>> = const { RefCell::new(Vec::new()) };
|
||||
/// The tabs whose server refused their login, the app told; a tab's
|
||||
/// `set_credentials` takes it out again.
|
||||
static REJECTED: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
|
||||
/// The tab of each server page and pop-out web view, by the address of
|
||||
/// its WKWebView (`bind_view`).
|
||||
static VIEWS: RefCell<Vec<(usize, u64)>> = const { RefCell::new(Vec::new()) };
|
||||
/// Told once, with the tab, when a server refuses its login.
|
||||
static ON_REJECTED: RefCell<Option<RejectedHandler>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
// The added methods, with every object argument as a raw pointer: WebKit
|
||||
@@ -365,61 +441,145 @@ mod imp {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn set_credentials(creds: Option<BasicCredentials>) {
|
||||
pub(super) fn set_credentials(tab: u64, creds: Option<BasicCredentials>) {
|
||||
if MainThreadMarker::new().is_none() {
|
||||
eprintln!("codeman-desktop: macos::set_credentials called off the main thread; ignored");
|
||||
return;
|
||||
}
|
||||
let stored = SAVED.try_with(|saved| saved.try_borrow_mut().map(|mut saved| *saved = creds).is_ok());
|
||||
let stored = SAVED.try_with(|saved| {
|
||||
saved
|
||||
.try_borrow_mut()
|
||||
.map(|mut saved| {
|
||||
saved.retain(|(t, _)| *t != tab);
|
||||
if let Some(creds) = creds {
|
||||
saved.push((tab, creds));
|
||||
}
|
||||
})
|
||||
.is_ok()
|
||||
});
|
||||
if stored != Ok(true) {
|
||||
eprintln!("codeman-desktop: could not store the login for Basic challenges");
|
||||
}
|
||||
let _ = REJECTED.try_with(|rejected| rejected.set(false));
|
||||
let _ = REJECTED.try_with(|rejected| {
|
||||
if let Ok(mut rejected) = rejected.try_borrow_mut() {
|
||||
rejected.retain(|t| *t != tab);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn set_auth_rejected_handler(handler: Box<dyn Fn()>) {
|
||||
pub(super) fn bind_view(webview: &wry::WebView, tab: u64) {
|
||||
if MainThreadMarker::new().is_none() {
|
||||
return;
|
||||
}
|
||||
let address = Retained::as_ptr(&WebViewExtMacOS::webview(webview)) as usize;
|
||||
let _ = VIEWS.try_with(|views| {
|
||||
if let Ok(mut views) = views.try_borrow_mut() {
|
||||
// A WKWebView freed earlier may have left its address behind.
|
||||
views.retain(|(a, _)| *a != address);
|
||||
views.push((address, tab));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn forget_tab(tab: u64) {
|
||||
let _ = VIEWS.try_with(|views| {
|
||||
if let Ok(mut views) = views.try_borrow_mut() {
|
||||
views.retain(|(_, t)| *t != tab);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The tab a WKWebView belongs to, by its address.
|
||||
fn tab_of_view(web_view: *mut AnyObject) -> Option<u64> {
|
||||
let address = web_view as usize;
|
||||
VIEWS
|
||||
.try_with(|views| {
|
||||
views
|
||||
.try_borrow()
|
||||
.ok()
|
||||
.and_then(|views| views.iter().find(|(a, _)| *a == address).map(|(_, t)| *t))
|
||||
})
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
pub(super) fn os_major_version() -> isize {
|
||||
NSProcessInfo::processInfo().operatingSystemVersion().majorVersion
|
||||
}
|
||||
|
||||
pub(super) fn set_auth_rejected_handler(handler: Box<dyn Fn(u64)>) {
|
||||
if MainThreadMarker::new().is_none() {
|
||||
eprintln!("codeman-desktop: macos::set_auth_rejected_handler called off the main thread; ignored");
|
||||
return;
|
||||
}
|
||||
let handler: Rc<dyn Fn()> = Rc::from(handler);
|
||||
let handler: RejectedHandler = Rc::from(handler);
|
||||
let stored = ON_REJECTED.try_with(|slot| slot.try_borrow_mut().map(|mut slot| *slot = Some(handler)).is_ok());
|
||||
if stored != Ok(true) {
|
||||
eprintln!("codeman-desktop: could not store the login-refused handler");
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn clear_cookies(done: Box<dyn FnOnce()>) {
|
||||
if MainThreadMarker::new().is_none() {
|
||||
pub(super) fn clear_cookies(store: Option<[u8; 16]>, host: String, done: Box<dyn FnOnce()>) {
|
||||
let Some(mtm) = MainThreadMarker::new() else {
|
||||
eprintln!("codeman-desktop: macos::clear_cookies called off the main thread; cookies kept");
|
||||
// `done` was made on this thread, so it runs here instead of being
|
||||
// sent to another one.
|
||||
run_done(done);
|
||||
return;
|
||||
}
|
||||
};
|
||||
// Every way out of here, a panic included, either hands `pending` to
|
||||
// WebKit's completion handler or drops it, and both pass `done` on.
|
||||
let pending = Pending(Cell::new(Some(done)));
|
||||
let _ = catch_unwind(AssertUnwindSafe(|| autoreleasepool(|_| remove_cookies(pending))));
|
||||
// WebKit's completion handlers or drops it, and both pass `done` on.
|
||||
let pending = Rc::new(Pending(Cell::new(Some(done))));
|
||||
let _ = catch_unwind(AssertUnwindSafe(|| {
|
||||
autoreleasepool(|_| remove_cookies(mtm, store, host, pending))
|
||||
}));
|
||||
}
|
||||
|
||||
fn remove_cookies(pending: Pending) {
|
||||
// SAFETY: class methods called on the main thread (checked by the
|
||||
// caller), with nil handled by the `Option` return types.
|
||||
let store: Option<Retained<WKWebsiteDataStore>> =
|
||||
unsafe { msg_send![WKWebsiteDataStore::class(), defaultDataStore] };
|
||||
let since: Option<Retained<NSDate>> = unsafe { msg_send![NSDate::class(), distantPast] };
|
||||
let (Some(store), Some(since)) = (store, since) else {
|
||||
eprintln!("codeman-desktop: no website data store; cookies kept");
|
||||
return;
|
||||
fn remove_cookies(mtm: MainThreadMarker, store: Option<[u8; 16]>, host: String, pending: Rc<Pending>) {
|
||||
// The same store wry gave the server's web view: its own on a macOS that
|
||||
// has them, else the default one. `dataStoreForIdentifier:` does not
|
||||
// exist before macOS 14, and an all-zero identifier throws.
|
||||
let own = store.filter(|id| os_major_version() >= 14 && id.iter().any(|b| *b != 0));
|
||||
// SAFETY: class methods called on the main thread (the marker).
|
||||
let data_store: Retained<WKWebsiteDataStore> = match own {
|
||||
Some(id) => unsafe { WKWebsiteDataStore::dataStoreForIdentifier(&NSUUID::from_bytes(id), mtm) },
|
||||
None => unsafe { WKWebsiteDataStore::defaultDataStore(mtm) },
|
||||
};
|
||||
// SAFETY: an immutable string constant exported by WebKit.
|
||||
let types = NSSet::from_slice(&[unsafe { WKWebsiteDataTypeCookies }]);
|
||||
let completion = RcBlock::new(move || pending.finish());
|
||||
// SAFETY: main thread; WebKit copies the block, keeps it until the
|
||||
// cookies are gone and then calls it. Dropping our reference after the
|
||||
// call is fine.
|
||||
unsafe { store.removeDataOfTypes_modifiedSince_completionHandler(&types, &since, &completion) };
|
||||
// SAFETY: a property read on the main thread.
|
||||
let cookies = unsafe { data_store.httpCookieStore() };
|
||||
let delete_from = cookies.clone();
|
||||
let fetched = RcBlock::new(move |all: std::ptr::NonNull<NSArray<NSHTTPCookie>>| {
|
||||
// SAFETY: WebKit hands a valid array for the length of this call.
|
||||
let all = unsafe { all.as_ref() };
|
||||
let mine: Vec<Retained<NSHTTPCookie>> = autoreleasepool(|_| {
|
||||
all.to_vec()
|
||||
.into_iter()
|
||||
.filter(|cookie| rust_string(&cookie.domain()).is_some_and(|d| cookie_for_host(&d, &host)))
|
||||
.collect()
|
||||
});
|
||||
if mine.is_empty() {
|
||||
pending.finish();
|
||||
return;
|
||||
}
|
||||
// `done` goes once the last of them is deleted.
|
||||
let left = Rc::new(Cell::new(mine.len()));
|
||||
for cookie in &mine {
|
||||
let left = left.clone();
|
||||
let pending = pending.clone();
|
||||
let deleted = RcBlock::new(move || {
|
||||
left.set(left.get().saturating_sub(1));
|
||||
if left.get() == 0 {
|
||||
pending.finish();
|
||||
}
|
||||
});
|
||||
// SAFETY: main thread (WebKit calls this handler there); WebKit
|
||||
// copies the block and calls it once the cookie is gone.
|
||||
unsafe { delete_from.deleteCookie_completionHandler(cookie, Some(&deleted)) };
|
||||
}
|
||||
});
|
||||
// SAFETY: main thread; WebKit copies the block, calls it with the
|
||||
// store's cookies, and releases it.
|
||||
unsafe { cookies.getAllCookies(&fetched) };
|
||||
}
|
||||
|
||||
/// `done` until it is passed on: by the completion handler, or, when
|
||||
@@ -692,7 +852,7 @@ mod imp {
|
||||
extern "C-unwind" fn did_receive_challenge(
|
||||
_this: *mut AnyObject,
|
||||
_cmd: Sel,
|
||||
_web_view: *mut AnyObject,
|
||||
web_view: *mut AnyObject,
|
||||
challenge: *mut NSURLAuthenticationChallenge,
|
||||
handler: *mut ChallengeHandler,
|
||||
) {
|
||||
@@ -700,22 +860,24 @@ mod imp {
|
||||
let Some(handler) = (unsafe { handler.as_ref() }) else {
|
||||
return;
|
||||
};
|
||||
let reply = catch_unwind(AssertUnwindSafe(|| reply_to(unsafe { challenge.as_ref() }))).unwrap_or_default();
|
||||
let tab = tab_of_view(web_view);
|
||||
let reply = catch_unwind(AssertUnwindSafe(|| reply_to(unsafe { challenge.as_ref() }, tab))).unwrap_or_default();
|
||||
let credential = reply
|
||||
.credential
|
||||
.as_ref()
|
||||
.map_or(ptr::null_mut(), |c| Retained::as_ptr(c).cast_mut());
|
||||
handler.call((reply.disposition, credential));
|
||||
// Told after WebKit has its answer, so the app's handler cannot delay it.
|
||||
if reply.report {
|
||||
notify_rejected();
|
||||
if let Some(tab) = reply.report {
|
||||
notify_rejected(tab);
|
||||
}
|
||||
}
|
||||
|
||||
struct Reply {
|
||||
disposition: NSURLSessionAuthChallengeDisposition,
|
||||
credential: Option<Retained<NSURLCredential>>,
|
||||
report: bool,
|
||||
/// The tab whose server refused its login, to tell the app.
|
||||
report: Option<u64>,
|
||||
}
|
||||
|
||||
impl Default for Reply {
|
||||
@@ -723,12 +885,14 @@ mod imp {
|
||||
Reply {
|
||||
disposition: NSURLSessionAuthChallengeDisposition::PerformDefaultHandling,
|
||||
credential: None,
|
||||
report: false,
|
||||
report: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reply_to(challenge: Option<&NSURLAuthenticationChallenge>) -> Reply {
|
||||
/// `tab`: the tab of the web view that was challenged, whose login is the
|
||||
/// only one it may get. None (a view of no tab): no login at all.
|
||||
fn reply_to(challenge: Option<&NSURLAuthenticationChallenge>, tab: Option<u64>) -> Reply {
|
||||
let Some(challenge) = challenge else {
|
||||
return Reply::default();
|
||||
};
|
||||
@@ -762,10 +926,13 @@ mod imp {
|
||||
let failed = failure_url(challenge);
|
||||
|
||||
let saved = SAVED
|
||||
.try_with(|saved| saved.try_borrow().ok().and_then(|saved| saved.clone()))
|
||||
.try_with(|saved| saved.try_borrow().ok().map(|saved| saved.clone()))
|
||||
.ok()
|
||||
.flatten();
|
||||
let rejected = REJECTED.try_with(Cell::get).unwrap_or(false);
|
||||
.flatten()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter(|(t, _)| Some(*t) == tab)
|
||||
.collect::<Vec<_>>();
|
||||
let asked = Challenge {
|
||||
basic,
|
||||
proxy,
|
||||
@@ -775,8 +942,14 @@ mod imp {
|
||||
previous_failures: previous_failures as i64,
|
||||
failed: failed.as_ref(),
|
||||
};
|
||||
match (decide(&asked, saved.as_ref(), rejected), saved) {
|
||||
(ChallengeAnswer::UseCredential, Some(saved)) => {
|
||||
let picked = pick(&asked, &saved);
|
||||
let rejected = picked.is_some_and(|(tab, _)| {
|
||||
REJECTED
|
||||
.try_with(|rejected| rejected.try_borrow().is_ok_and(|r| r.contains(&tab)))
|
||||
.unwrap_or(false)
|
||||
});
|
||||
match (decide(&asked, picked.map(|(_, s)| s), rejected), picked) {
|
||||
(ChallengeAnswer::UseCredential, Some((_, saved))) => {
|
||||
let user = NSString::from_str(&saved.username);
|
||||
let password = NSString::from_str(&saved.password);
|
||||
// None: WebKit uses it for this request only and stores
|
||||
@@ -797,26 +970,32 @@ mod imp {
|
||||
Some(credential) => Reply {
|
||||
disposition: NSURLSessionAuthChallengeDisposition::UseCredential,
|
||||
credential: Some(credential),
|
||||
report: false,
|
||||
report: None,
|
||||
},
|
||||
None => Reply::default(),
|
||||
}
|
||||
}
|
||||
(ChallengeAnswer::CancelAndReport, _) => {
|
||||
let _ = REJECTED.try_with(|rejected| rejected.set(true));
|
||||
(ChallengeAnswer::CancelAndReport, Some((tab, _))) => {
|
||||
let _ = REJECTED.try_with(|rejected| {
|
||||
if let Ok(mut rejected) = rejected.try_borrow_mut() {
|
||||
rejected.push(tab);
|
||||
}
|
||||
});
|
||||
eprintln!("codeman-desktop: {host}:{port} refused the saved login; not sending it again");
|
||||
Reply {
|
||||
disposition: NSURLSessionAuthChallengeDisposition::CancelAuthenticationChallenge,
|
||||
credential: None,
|
||||
report: true,
|
||||
report: Some(tab),
|
||||
}
|
||||
}
|
||||
(ChallengeAnswer::Cancel, _) => Reply {
|
||||
disposition: NSURLSessionAuthChallengeDisposition::CancelAuthenticationChallenge,
|
||||
credential: None,
|
||||
report: false,
|
||||
report: None,
|
||||
},
|
||||
(ChallengeAnswer::Default | ChallengeAnswer::UseCredential, _) => Reply::default(),
|
||||
(ChallengeAnswer::Default | ChallengeAnswer::UseCredential | ChallengeAnswer::CancelAndReport, _) => {
|
||||
Reply::default()
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -833,7 +1012,7 @@ mod imp {
|
||||
Url::parse(&rust_string(&*text?)?).ok()
|
||||
}
|
||||
|
||||
fn notify_rejected() {
|
||||
fn notify_rejected(tab: u64) {
|
||||
// Cloned out first: the handler may call `set_credentials` or
|
||||
// `set_auth_rejected_handler`, which would find the cell borrowed.
|
||||
let handler = ON_REJECTED
|
||||
@@ -841,7 +1020,7 @@ mod imp {
|
||||
.ok()
|
||||
.flatten();
|
||||
if let Some(handler) = handler {
|
||||
if catch_unwind(AssertUnwindSafe(|| handler())).is_err() {
|
||||
if catch_unwind(AssertUnwindSafe(|| handler(tab))).is_err() {
|
||||
eprintln!("codeman-desktop: the login-refused handler panicked");
|
||||
}
|
||||
}
|
||||
@@ -1074,4 +1253,45 @@ mod tests {
|
||||
// gets a first line of the app's own, never its own text in bold.
|
||||
assert_eq!(dialog_title(None), "An embedded page says:");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_tab_answers_for_its_own_server() {
|
||||
let saved = vec![
|
||||
(1, saved("http://127.0.0.1:3000/")),
|
||||
(2, saved("http://127.0.0.1:5000/")),
|
||||
(3, saved("http://h:3000/")),
|
||||
(4, saved("http://h:3000/codeman/")),
|
||||
];
|
||||
let at = |port: i64, host: &'static str, failed: &Url| {
|
||||
let c = challenge("http", host, port, 0, Some(failed));
|
||||
pick(&c, &saved).map(|(tab, _)| tab)
|
||||
};
|
||||
assert_eq!(at(3000, "127.0.0.1", &url("http://127.0.0.1:3000/api/status")), Some(1));
|
||||
assert_eq!(at(5000, "127.0.0.1", &url("http://127.0.0.1:5000/api/status")), Some(2));
|
||||
assert_eq!(at(4000, "127.0.0.1", &url("http://127.0.0.1:4000/api/status")), None);
|
||||
// Below a base path the deeper server wins; elsewhere the root one.
|
||||
assert_eq!(at(3000, "h", &url("http://h:3000/codeman/api/status")), Some(4));
|
||||
assert_eq!(at(3000, "h", &url("http://h:3000/api/status")), Some(3));
|
||||
// A web tab under either is nobody's.
|
||||
assert_eq!(at(3000, "h", &url("http://h:3000/webview/cap/")), None);
|
||||
assert_eq!(at(3000, "h", &url("http://h:3000/codeman/webview/cap/")), None);
|
||||
let none: Vec<(u64, BasicCredentials)> = Vec::new();
|
||||
let c = challenge("http", "h", 3000, 0, None);
|
||||
assert!(pick(&c, &none).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cookies_go_with_their_host() {
|
||||
assert!(cookie_for_host("127.0.0.1", "127.0.0.1"));
|
||||
assert!(cookie_for_host("Studio.Example.ts.net", "studio.example.ts.net"));
|
||||
assert!(cookie_for_host(".example.ts.net", "studio.example.ts.net"));
|
||||
assert!(cookie_for_host(".example.ts.net", "example.ts.net"));
|
||||
assert!(cookie_for_host("::1", "[::1]"));
|
||||
assert!(!cookie_for_host("atlas.example.ts.net", "studio.example.ts.net"));
|
||||
assert!(!cookie_for_host(".other.ts.net", "studio.example.ts.net"));
|
||||
assert!(!cookie_for_host("example.ts.net", "studio.example.ts.net"));
|
||||
assert!(!cookie_for_host("localhost", "127.0.0.1"));
|
||||
assert!(!cookie_for_host("", "127.0.0.1"));
|
||||
assert!(!cookie_for_host(".ample.ts.net", "studio.example.ts.net"));
|
||||
}
|
||||
}
|
||||
+2235
-689
File diff suppressed because it is too large.
Load diff
@@ -3,6 +3,8 @@
|
||||
use muda::accelerator::{Accelerator, Code, Modifiers};
|
||||
use muda::{AboutMetadata, CheckMenuItem, Menu, MenuItem, PredefinedMenuItem, Submenu};
|
||||
|
||||
use crate::tabs::{PALETTE, PALETTE_NAMES};
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::keep_awake::{self, Mode};
|
||||
use crate::logo::{self, BlinkStyle, Signal};
|
||||
@@ -21,11 +23,124 @@ pub mod menu_id {
|
||||
pub const DEVTOOLS: &str = "devtools";
|
||||
pub const HELP_DOCS: &str = "help-docs";
|
||||
pub const HELP_GITHUB: &str = "help-github";
|
||||
pub const TAB_NEW: &str = "tab-new";
|
||||
pub const TAB_CLOSE: &str = "tab-close";
|
||||
pub const TAB_REOPEN: &str = "tab-reopen";
|
||||
pub const TAB_OVERVIEW: &str = "tab-overview";
|
||||
pub const TAB_NEXT: &str = "tab-next";
|
||||
pub const TAB_PREVIOUS: &str = "tab-previous";
|
||||
pub const WINDOW_CLOSE: &str = "window-close";
|
||||
/// `tab-key-<n>`: the tab ⌘n selects (tabs::index_of_key).
|
||||
pub const TAB_KEY_PREFIX: &str = "tab-key-";
|
||||
/// `tab-menu:<tab>:<action>`: an item of a tab's right-click menu.
|
||||
pub const TAB_MENU_PREFIX: &str = "tab-menu:";
|
||||
}
|
||||
|
||||
/// What a tab's right-click menu asks for.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum TabAction {
|
||||
Rename,
|
||||
/// A palette colour, by index into `tabs::PALETTE`.
|
||||
Color(usize),
|
||||
Reload,
|
||||
/// Show the connect page in this tab (another server, or the same with
|
||||
/// another login).
|
||||
Reconnect,
|
||||
Close,
|
||||
CloseOthers,
|
||||
}
|
||||
|
||||
impl TabAction {
|
||||
fn id(self, tab: u64) -> String {
|
||||
let action = match self {
|
||||
TabAction::Rename => "rename".to_string(),
|
||||
TabAction::Color(i) => format!("color-{i}"),
|
||||
TabAction::Reload => "reload".to_string(),
|
||||
TabAction::Reconnect => "reconnect".to_string(),
|
||||
TabAction::Close => "close".to_string(),
|
||||
TabAction::CloseOthers => "close-others".to_string(),
|
||||
};
|
||||
format!("{}{tab}:{action}", menu_id::TAB_MENU_PREFIX)
|
||||
}
|
||||
|
||||
/// The tab and action of a right-click menu item's id.
|
||||
pub fn parse(id: &str) -> Option<(u64, TabAction)> {
|
||||
let (tab, action) = id.strip_prefix(menu_id::TAB_MENU_PREFIX)?.split_once(':')?;
|
||||
let tab = tab.parse().ok()?;
|
||||
let action = match action {
|
||||
"rename" => TabAction::Rename,
|
||||
"reload" => TabAction::Reload,
|
||||
"reconnect" => TabAction::Reconnect,
|
||||
"close" => TabAction::Close,
|
||||
"close-others" => TabAction::CloseOthers,
|
||||
other => {
|
||||
let i: usize = other.strip_prefix("color-")?.parse().ok()?;
|
||||
(i < PALETTE.len()).then_some(TabAction::Color(i))?
|
||||
}
|
||||
};
|
||||
Some((tab, action))
|
||||
}
|
||||
}
|
||||
|
||||
/// The ⌘ number of a `tab-key-<n>` item.
|
||||
pub fn tab_key(id: &str) -> Option<usize> {
|
||||
id.strip_prefix(menu_id::TAB_KEY_PREFIX)?
|
||||
.parse()
|
||||
.ok()
|
||||
.filter(|k| (1..=9).contains(k))
|
||||
}
|
||||
|
||||
/// The right-click menu of one tab. `server`: the tab shows a server (Reload
|
||||
/// and Connect to Another Server make sense); `others`: there are other tabs.
|
||||
pub fn tab_context_menu(tab: u64, color: &str, server: bool, others: bool) -> muda::Result<Menu> {
|
||||
let menu = Menu::new();
|
||||
menu.append(&MenuItem::with_id(
|
||||
TabAction::Rename.id(tab),
|
||||
"Rename Tab\u{2026}",
|
||||
true,
|
||||
None,
|
||||
))?;
|
||||
let colors = Submenu::new("Tab Color", true);
|
||||
for (i, (value, name)) in PALETTE.iter().zip(PALETTE_NAMES).enumerate() {
|
||||
let chosen = value.eq_ignore_ascii_case(color);
|
||||
colors.append(&CheckMenuItem::with_id(
|
||||
TabAction::Color(i).id(tab),
|
||||
name,
|
||||
true,
|
||||
chosen,
|
||||
None,
|
||||
))?;
|
||||
}
|
||||
menu.append(&colors)?;
|
||||
menu.append(&PredefinedMenuItem::separator())?;
|
||||
menu.append(&MenuItem::with_id(TabAction::Reload.id(tab), "Reload", server, None))?;
|
||||
menu.append(&MenuItem::with_id(
|
||||
TabAction::Reconnect.id(tab),
|
||||
"Connect This Tab to Another Server\u{2026}",
|
||||
server,
|
||||
None,
|
||||
))?;
|
||||
menu.append(&PredefinedMenuItem::separator())?;
|
||||
menu.append(&MenuItem::with_id(TabAction::Close.id(tab), "Close Tab", true, None))?;
|
||||
menu.append(&MenuItem::with_id(
|
||||
TabAction::CloseOthers.id(tab),
|
||||
"Close Other Tabs",
|
||||
others,
|
||||
None,
|
||||
))?;
|
||||
Ok(menu)
|
||||
}
|
||||
|
||||
pub struct AppMenu {
|
||||
pub bar: Menu,
|
||||
pub window_menu: Submenu,
|
||||
/// Server: the tab commands, then one item per tab (`set_tabs`).
|
||||
server_menu: Submenu,
|
||||
/// ⌘1 to ⌘9, made once and shown as many as there are tabs.
|
||||
tab_items: Vec<CheckMenuItem>,
|
||||
/// How many of `tab_items` are in the menu.
|
||||
tab_items_shown: usize,
|
||||
pub reopen: MenuItem,
|
||||
pub help_menu: Submenu,
|
||||
pub start_fullscreen: CheckMenuItem,
|
||||
/// The one switch for the logo. None on a Mac without a lit logo, which has no
|
||||
@@ -120,6 +235,34 @@ fn build_keep_awake(config: &Config) -> muda::Result<(Submenu, KeepAwakeMenu)> {
|
||||
))
|
||||
}
|
||||
|
||||
impl AppMenu {
|
||||
/// One item per tab under Server, as (name, in front), with ⌘1 to ⌘8 for
|
||||
/// the first eight and ⌘9 for the last (`tabs::key_of`). Items past nine
|
||||
/// tabs are left out, as Safari does.
|
||||
pub fn set_tabs(&mut self, tabs: &[(String, bool)]) {
|
||||
let len = tabs.len();
|
||||
let shown: Vec<(usize, &(String, bool))> = tabs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, t)| crate::tabs::key_of(i, len).map(|k| (k, t)))
|
||||
.collect();
|
||||
for item in self.tab_items.iter().take(self.tab_items_shown) {
|
||||
let _ = self.server_menu.remove(item);
|
||||
}
|
||||
self.tab_items_shown = 0;
|
||||
// Appended in key order, which is tab order.
|
||||
for (key, (name, active)) in shown {
|
||||
if let Some(item) = self.tab_items.get(key - 1) {
|
||||
item.set_text(name);
|
||||
item.set_checked(*active);
|
||||
if self.server_menu.append(item).is_ok() {
|
||||
self.tab_items_shown = self.tab_items_shown.max(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_menu(config: &Config) -> muda::Result<AppMenu> {
|
||||
let bar = Menu::new();
|
||||
let about = PredefinedMenuItem::about(
|
||||
@@ -243,6 +386,52 @@ pub fn build_menu(config: &Config) -> muda::Result<AppMenu> {
|
||||
logo_switch = Some(switch);
|
||||
logo_lid = Some(lid);
|
||||
}
|
||||
let cmd = |code| Some(Accelerator::new(Modifiers::META, code));
|
||||
let cmd_shift = |code| Some(Accelerator::new(Modifiers::META | Modifiers::SHIFT, code));
|
||||
let reopen = MenuItem::with_id(menu_id::TAB_REOPEN, "Reopen Closed Tab", false, cmd_shift(Code::KeyT));
|
||||
let server_menu = Submenu::with_items(
|
||||
"Server",
|
||||
true,
|
||||
&[
|
||||
&MenuItem::with_id(menu_id::TAB_NEW, "New Server Tab", true, cmd(Code::KeyT)),
|
||||
&MenuItem::with_id(menu_id::TAB_CLOSE, "Close Tab", true, cmd(Code::KeyW)),
|
||||
&reopen,
|
||||
&PredefinedMenuItem::separator(),
|
||||
&MenuItem::with_id(menu_id::TAB_OVERVIEW, "Show All Servers", true, cmd(Code::Digit0)),
|
||||
&MenuItem::with_id(
|
||||
menu_id::TAB_PREVIOUS,
|
||||
"Show Previous Tab",
|
||||
true,
|
||||
cmd_shift(Code::BracketLeft),
|
||||
),
|
||||
&MenuItem::with_id(menu_id::TAB_NEXT, "Show Next Tab", true, cmd_shift(Code::BracketRight)),
|
||||
&PredefinedMenuItem::separator(),
|
||||
],
|
||||
)?;
|
||||
const DIGITS: [Code; 9] = [
|
||||
Code::Digit1,
|
||||
Code::Digit2,
|
||||
Code::Digit3,
|
||||
Code::Digit4,
|
||||
Code::Digit5,
|
||||
Code::Digit6,
|
||||
Code::Digit7,
|
||||
Code::Digit8,
|
||||
Code::Digit9,
|
||||
];
|
||||
let tab_items = DIGITS
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, code)| {
|
||||
CheckMenuItem::with_id(
|
||||
format!("{}{}", menu_id::TAB_KEY_PREFIX, i + 1),
|
||||
"",
|
||||
true,
|
||||
false,
|
||||
cmd(*code),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let window_menu = Submenu::with_items(
|
||||
"Window",
|
||||
true,
|
||||
@@ -250,7 +439,9 @@ pub fn build_menu(config: &Config) -> muda::Result<AppMenu> {
|
||||
&PredefinedMenuItem::minimize(None),
|
||||
&PredefinedMenuItem::maximize(None),
|
||||
&PredefinedMenuItem::separator(),
|
||||
&PredefinedMenuItem::close_window(None),
|
||||
// Not the predefined Close Window: ⌘W closes a tab (Server menu),
|
||||
// as in Safari, so closing the window is ⇧⌘W.
|
||||
&MenuItem::with_id(menu_id::WINDOW_CLOSE, "Close Window", true, cmd_shift(Code::KeyW)),
|
||||
&PredefinedMenuItem::separator(),
|
||||
&PredefinedMenuItem::bring_all_to_front(None),
|
||||
],
|
||||
@@ -263,10 +454,14 @@ pub fn build_menu(config: &Config) -> muda::Result<AppMenu> {
|
||||
&MenuItem::with_id(menu_id::HELP_GITHUB, "Codeman on GitHub", true, None),
|
||||
],
|
||||
)?;
|
||||
bar.append_items(&[&app_menu, &edit, &view, &window_menu, &help_menu])?;
|
||||
bar.append_items(&[&app_menu, &edit, &view, &server_menu, &window_menu, &help_menu])?;
|
||||
Ok(AppMenu {
|
||||
bar,
|
||||
window_menu,
|
||||
server_menu,
|
||||
tab_items,
|
||||
tab_items_shown: 0,
|
||||
reopen,
|
||||
help_menu,
|
||||
start_fullscreen,
|
||||
logo_switch,
|
||||
@@ -275,3 +470,31 @@ pub fn build_menu(config: &Config) -> muda::Result<AppMenu> {
|
||||
logo_lid,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn tab_menu_ids_round_trip() {
|
||||
for action in [
|
||||
TabAction::Rename,
|
||||
TabAction::Color(0),
|
||||
TabAction::Color(5),
|
||||
TabAction::Reload,
|
||||
TabAction::Reconnect,
|
||||
TabAction::Close,
|
||||
TabAction::CloseOthers,
|
||||
] {
|
||||
assert_eq!(TabAction::parse(&action.id(42)), Some((42, action)));
|
||||
}
|
||||
assert_eq!(TabAction::parse("tab-menu:42:color-6"), None);
|
||||
assert_eq!(TabAction::parse("tab-menu:x:close"), None);
|
||||
assert_eq!(TabAction::parse("tab-menu:42:other"), None);
|
||||
assert_eq!(TabAction::parse("reload"), None);
|
||||
assert_eq!(tab_key("tab-key-1"), Some(1));
|
||||
assert_eq!(tab_key("tab-key-9"), Some(9));
|
||||
assert_eq!(tab_key("tab-key-0"), None);
|
||||
assert_eq!(tab_key("tab-key-10"), None);
|
||||
}
|
||||
}
|
||||
@@ -826,6 +826,141 @@ pub fn parse_ipc(frame_url: &str, body: &str, phase: &Phase, is_main_window: boo
|
||||
Some(Ipc::Host(cmd))
|
||||
}
|
||||
|
||||
/// The tab strip across the top of the window (assets/tabs.html).
|
||||
pub const STRIP_PAGE: &str = "codemanapp://localhost/tabs.html";
|
||||
/// The overview of every server (assets/overview.html).
|
||||
pub const OVERVIEW_PAGE: &str = "codemanapp://localhost/overview.html";
|
||||
|
||||
/// What the tab strip asks for. Tab ids are the app's own numbers; a stale or
|
||||
/// made-up one matches no tab and does nothing.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum StripCmd {
|
||||
Ready,
|
||||
Select(u64),
|
||||
Close(u64),
|
||||
New,
|
||||
Overview,
|
||||
/// Right-click on a tab: the native menu for it.
|
||||
Menu(u64),
|
||||
/// The name the user typed (cleaned by `tabs::clean_name`; empty puts the
|
||||
/// default back).
|
||||
Rename {
|
||||
id: u64,
|
||||
name: String,
|
||||
},
|
||||
Move {
|
||||
id: u64,
|
||||
to: usize,
|
||||
},
|
||||
/// A rename started: the strip takes the keyboard for its name field.
|
||||
Editing,
|
||||
/// A mouse-down on the strip's empty space: drag the window.
|
||||
Drag,
|
||||
/// A double-click there: what a title bar double-click does.
|
||||
Zoom,
|
||||
}
|
||||
|
||||
/// What the overview asks for.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum OverviewCmd {
|
||||
Ready,
|
||||
Open(u64),
|
||||
/// Show that tab and select the session in Codeman's page
|
||||
/// (`tabs::is_session_id` is checked before it goes anywhere).
|
||||
OpenSession {
|
||||
tab: u64,
|
||||
session: String,
|
||||
},
|
||||
New,
|
||||
Retry(u64),
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "cmd", rename_all = "camelCase", deny_unknown_fields)]
|
||||
enum RawStrip {
|
||||
Ready,
|
||||
Select { id: u64 },
|
||||
Close { id: u64 },
|
||||
New,
|
||||
Overview,
|
||||
Menu { id: u64 },
|
||||
Rename { id: u64, name: String },
|
||||
Move { id: u64, to: usize },
|
||||
Editing,
|
||||
Drag,
|
||||
Zoom,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "cmd", rename_all = "camelCase", deny_unknown_fields)]
|
||||
enum RawOverview {
|
||||
Ready,
|
||||
Open { tab: u64 },
|
||||
OpenSession { tab: u64, session: String },
|
||||
New,
|
||||
Retry { tab: u64 },
|
||||
}
|
||||
|
||||
/// Whether `frame_url` is exactly the bundled page `page` (a query or
|
||||
/// fragment does not matter).
|
||||
fn is_bundled_page(frame_url: &str, page: &str) -> bool {
|
||||
let (Ok(frame), Ok(page)) = (Url::parse(frame_url), Url::parse(page)) else {
|
||||
return false;
|
||||
};
|
||||
frame.scheme() == APP_SCHEME && frame.host_str() == page.host_str() && frame.path() == page.path()
|
||||
}
|
||||
|
||||
/// A message from the tab strip. Only its own page in its own web view is
|
||||
/// listened to: the caller passes only what came from the strip's web view,
|
||||
/// and the frame must be the strip page.
|
||||
pub fn parse_strip_ipc(frame_url: &str, body: &str) -> Option<StripCmd> {
|
||||
if body.len() > MAX_MESSAGE_LEN || !is_bundled_page(frame_url, STRIP_PAGE) {
|
||||
return None;
|
||||
}
|
||||
Some(match serde_json::from_str::<RawStrip>(body).ok()? {
|
||||
RawStrip::Ready => StripCmd::Ready,
|
||||
RawStrip::Select { id } => StripCmd::Select(id),
|
||||
RawStrip::Close { id } => StripCmd::Close(id),
|
||||
RawStrip::New => StripCmd::New,
|
||||
RawStrip::Overview => StripCmd::Overview,
|
||||
RawStrip::Menu { id } => StripCmd::Menu(id),
|
||||
RawStrip::Rename { id, name } if name.len() <= MAX_FIELD_LEN => StripCmd::Rename { id, name },
|
||||
RawStrip::Move { id, to } => StripCmd::Move { id, to },
|
||||
RawStrip::Editing => StripCmd::Editing,
|
||||
RawStrip::Drag => StripCmd::Drag,
|
||||
RawStrip::Zoom => StripCmd::Zoom,
|
||||
RawStrip::Rename { .. } => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// A message from the overview, under the same rule as the strip's.
|
||||
pub fn parse_overview_ipc(frame_url: &str, body: &str) -> Option<OverviewCmd> {
|
||||
if body.len() > MAX_MESSAGE_LEN || !is_bundled_page(frame_url, OVERVIEW_PAGE) {
|
||||
return None;
|
||||
}
|
||||
Some(match serde_json::from_str::<RawOverview>(body).ok()? {
|
||||
RawOverview::Ready => OverviewCmd::Ready,
|
||||
RawOverview::Open { tab } => OverviewCmd::Open(tab),
|
||||
RawOverview::OpenSession { tab, session } if session.len() <= MAX_FIELD_LEN => {
|
||||
OverviewCmd::OpenSession { tab, session }
|
||||
}
|
||||
RawOverview::New => OverviewCmd::New,
|
||||
RawOverview::Retry { tab } => OverviewCmd::Retry(tab),
|
||||
RawOverview::OpenSession { .. } => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The navigations the strip's and the overview's web views allow: their own
|
||||
/// bundled page and nothing else, so neither can ever show a server's page or
|
||||
/// another site.
|
||||
pub fn bundled_navigation(target: &str, page: &str) -> Navigation {
|
||||
if is_bundled_page(target, page) {
|
||||
Navigation::Allow
|
||||
} else {
|
||||
Navigation::Block
|
||||
}
|
||||
}
|
||||
|
||||
/// Only http(s) URLs ever reach the default browser (never `file:`, a custom
|
||||
/// app scheme, or anything `open` would hand to another program).
|
||||
pub fn external_url(target: &str) -> Option<Url> {
|
||||
@@ -1886,4 +2021,98 @@ mod tests {
|
||||
assert!(external_url("codemanapp://localhost/").is_none());
|
||||
assert!(external_url("vscode://file/x").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strip_messages_only_from_the_strip_page() {
|
||||
let strip = STRIP_PAGE;
|
||||
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"ready"}"#), Some(StripCmd::Ready));
|
||||
assert_eq!(
|
||||
parse_strip_ipc(strip, r#"{"cmd":"select","id":3}"#),
|
||||
Some(StripCmd::Select(3))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_strip_ipc(strip, r#"{"cmd":"close","id":3}"#),
|
||||
Some(StripCmd::Close(3))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_strip_ipc(strip, r#"{"cmd":"menu","id":3}"#),
|
||||
Some(StripCmd::Menu(3))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_strip_ipc(strip, r#"{"cmd":"rename","id":3,"name":"studio"}"#),
|
||||
Some(StripCmd::Rename {
|
||||
id: 3,
|
||||
name: "studio".into()
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
parse_strip_ipc(strip, r#"{"cmd":"move","id":3,"to":0}"#),
|
||||
Some(StripCmd::Move { id: 3, to: 0 })
|
||||
);
|
||||
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"drag"}"#), Some(StripCmd::Drag));
|
||||
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"zoom"}"#), Some(StripCmd::Zoom));
|
||||
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"editing"}"#), Some(StripCmd::Editing));
|
||||
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"new"}"#), Some(StripCmd::New));
|
||||
assert_eq!(
|
||||
parse_strip_ipc(strip, r#"{"cmd":"overview"}"#),
|
||||
Some(StripCmd::Overview)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_strip_ipc("codemanapp://localhost/tabs.html?x=1", r#"{"cmd":"new"}"#),
|
||||
Some(StripCmd::New)
|
||||
);
|
||||
// Other frames, other pages, other shapes.
|
||||
assert_eq!(parse_strip_ipc(CONNECT_PAGE, r#"{"cmd":"new"}"#), None);
|
||||
assert_eq!(parse_strip_ipc(OVERVIEW_PAGE, r#"{"cmd":"new"}"#), None);
|
||||
assert_eq!(parse_strip_ipc("http://localhost/tabs.html", r#"{"cmd":"new"}"#), None);
|
||||
assert_eq!(parse_strip_ipc("codemanapp://evil/tabs.html", r#"{"cmd":"new"}"#), None);
|
||||
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"select","id":-1}"#), None);
|
||||
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"select","id":"3"}"#), None);
|
||||
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"connect","url":"http://x/"}"#), None);
|
||||
let long = format!(
|
||||
r#"{{"cmd":"rename","id":1,"name":"{}"}}"#,
|
||||
"x".repeat(MAX_FIELD_LEN + 1)
|
||||
);
|
||||
assert_eq!(parse_strip_ipc(strip, &long), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overview_messages_only_from_the_overview_page() {
|
||||
let page = OVERVIEW_PAGE;
|
||||
assert_eq!(parse_overview_ipc(page, r#"{"cmd":"ready"}"#), Some(OverviewCmd::Ready));
|
||||
assert_eq!(
|
||||
parse_overview_ipc(page, r#"{"cmd":"open","tab":2}"#),
|
||||
Some(OverviewCmd::Open(2))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_overview_ipc(page, r#"{"cmd":"retry","tab":2}"#),
|
||||
Some(OverviewCmd::Retry(2))
|
||||
);
|
||||
assert_eq!(parse_overview_ipc(page, r#"{"cmd":"new"}"#), Some(OverviewCmd::New));
|
||||
assert_eq!(
|
||||
parse_overview_ipc(page, r#"{"cmd":"openSession","tab":2,"session":"abc-1"}"#),
|
||||
Some(OverviewCmd::OpenSession {
|
||||
tab: 2,
|
||||
session: "abc-1".into()
|
||||
})
|
||||
);
|
||||
assert_eq!(parse_overview_ipc(STRIP_PAGE, r#"{"cmd":"new"}"#), None);
|
||||
assert_eq!(parse_overview_ipc(CONNECT_PAGE, r#"{"cmd":"ready"}"#), None);
|
||||
assert_eq!(parse_overview_ipc(page, r#"{"cmd":"select","id":1}"#), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bundled_pages_navigate_nowhere_else() {
|
||||
assert_eq!(bundled_navigation(STRIP_PAGE, STRIP_PAGE), Navigation::Allow);
|
||||
assert_eq!(bundled_navigation(OVERVIEW_PAGE, STRIP_PAGE), Navigation::Block);
|
||||
assert_eq!(bundled_navigation(CONNECT_PAGE, STRIP_PAGE), Navigation::Block);
|
||||
assert_eq!(
|
||||
bundled_navigation("http://127.0.0.1:3000/", STRIP_PAGE),
|
||||
Navigation::Block
|
||||
);
|
||||
assert_eq!(bundled_navigation("about:blank", OVERVIEW_PAGE), Navigation::Block);
|
||||
// The connect page's own gate does not admit the two new pages.
|
||||
assert!(!is_connect_page(&Url::parse(STRIP_PAGE).unwrap()));
|
||||
assert!(!is_connect_page(&Url::parse(OVERVIEW_PAGE).unwrap()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,650 @@
|
||||
//! Server tabs: the pure half. One window holds a tab per Codeman server (or a
|
||||
//! "New server" tab that shows the connect page), a strip across the top of
|
||||
//! the window draws them (`assets/tabs.html`), and an overview of every server
|
||||
//! (`assets/overview.html`) can take the place of the active tab. Everything
|
||||
//! here is a decision with no window behind it, so it is unit-tested on its own:
|
||||
//! names, colours, order, which data store a server's pages use, and the state
|
||||
//! the two pages are sent.
|
||||
|
||||
use serde::Serialize;
|
||||
use url::{Host, Url};
|
||||
|
||||
use crate::agents::{Detail, SessionState};
|
||||
|
||||
/// The height of the tab strip, in points. The window's other web views start
|
||||
/// below it.
|
||||
pub const STRIP_HEIGHT: f64 = 38.0;
|
||||
/// Where the window's traffic lights go so they sit centred in the strip: the
|
||||
/// close button's left edge and the buttons' centre line, in points.
|
||||
pub const TRAFFIC_LIGHTS: (f64, f64) = (14.0, 19.0);
|
||||
/// The longest tab name the strip accepts, in characters.
|
||||
pub const MAX_NAME: usize = 40;
|
||||
/// How many session rows a card of the overview gets.
|
||||
pub const OVERVIEW_ROWS: usize = 4;
|
||||
/// How many closed tabs Reopen Closed Tab remembers.
|
||||
pub const MAX_CLOSED: usize = 10;
|
||||
|
||||
/// The colours a new tab is given, in turn: violet, cyan, emerald, pink,
|
||||
/// amber, slate. None of them is the red, amber dot or blue of a status badge
|
||||
/// at the same lightness, so a stripe never reads as an alert.
|
||||
pub const PALETTE: [&str; 6] = ["#a78bfa", "#22d3ee", "#34d399", "#f472b6", "#f59e0b", "#94a3b8"];
|
||||
/// The names the right-click menu gives the palette, in the same order.
|
||||
pub const PALETTE_NAMES: [&str; 6] = ["Violet", "Cyan", "Green", "Pink", "Amber", "Slate"];
|
||||
|
||||
/// A colour the strip may draw: `#rrggbb` and nothing else, so a value read
|
||||
/// from the settings file can never carry CSS.
|
||||
pub fn is_color(value: &str) -> bool {
|
||||
value.len() == 7 && value.starts_with('#') && value[1..].bytes().all(|b| b.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
/// The first palette colour no open tab uses, else the palette again in turn.
|
||||
pub fn next_color<'a>(used: impl IntoIterator<Item = &'a str>) -> String {
|
||||
let used: Vec<String> = used.into_iter().map(str::to_ascii_lowercase).collect();
|
||||
PALETTE
|
||||
.iter()
|
||||
.find(|c| !used.iter().any(|u| u == *c))
|
||||
.copied()
|
||||
.unwrap_or(PALETTE[used.len() % PALETTE.len()])
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// What a tab is called until the user names it: `This Mac` for a server on
|
||||
/// loopback, else the first label of its host name (`studio` for
|
||||
/// `studio.example.ts.net`), or the whole address for an IP literal. A port
|
||||
/// other than Codeman's 3000 (or the scheme's own) is added, so two servers on
|
||||
/// one machine do not look alike.
|
||||
pub fn default_name(url: &Url) -> String {
|
||||
let base = match url.host() {
|
||||
_ if crate::policy::is_loopback(url) => "This Mac".to_string(),
|
||||
Some(Host::Domain(name)) => name
|
||||
.split('.')
|
||||
.next()
|
||||
.filter(|l| !l.is_empty())
|
||||
.unwrap_or(name)
|
||||
.to_string(),
|
||||
Some(Host::Ipv4(ip)) => ip.to_string(),
|
||||
Some(Host::Ipv6(ip)) => format!("[{ip}]"),
|
||||
None => url.as_str().to_string(),
|
||||
};
|
||||
match url.port() {
|
||||
Some(port) if port != 3000 => format!("{base}:{port}"),
|
||||
_ => base,
|
||||
}
|
||||
}
|
||||
|
||||
/// A name the user typed, cleaned: trimmed, control characters dropped, cut at
|
||||
/// `MAX_NAME` characters. None when nothing is left, which puts the default
|
||||
/// name back.
|
||||
pub fn clean_name(raw: &str) -> Option<String> {
|
||||
let kept: String = raw.chars().filter(|c| !c.is_control()).collect();
|
||||
let trimmed: String = kept.trim().chars().take(MAX_NAME).collect();
|
||||
let trimmed = trimmed.trim_end().to_string();
|
||||
(!trimmed.is_empty()).then_some(trimmed)
|
||||
}
|
||||
|
||||
/// What a rename the strip finished does to a tab's own name: None, nothing
|
||||
/// (it ended without a change: Escape, or Enter on the same text, sends the
|
||||
/// name the tab shows, and kept, that would pin "New server" to a tab before
|
||||
/// it has a server); `Some(None)`, back to the default name (an empty name,
|
||||
/// or the default typed out); `Some(Some(name))`, that name.
|
||||
pub fn renamed(typed: &str, shown: &str, default: Option<&str>) -> Option<Option<String>> {
|
||||
let Some(name) = clean_name(typed) else {
|
||||
return Some(None);
|
||||
};
|
||||
if clean_name(shown).as_deref() == Some(name.as_str()) {
|
||||
return None;
|
||||
}
|
||||
Some((default != Some(name.as_str())).then_some(name))
|
||||
}
|
||||
|
||||
/// The identifier of the WebKit data store (cookies and local storage) that a
|
||||
/// server's pages use. Each server gets one of its own, so two servers on one
|
||||
/// host (a Codeman on port 3000 and a beta on 5000) never share a login cookie,
|
||||
/// which carries the same name on both and is not told apart by port. Derived
|
||||
/// from the server's address, so the same server finds its store, and with it
|
||||
/// Codeman's per-device settings, at every launch. Two 64-bit FNV-1a hashes
|
||||
/// with different starting values: stable across Rust releases, which the
|
||||
/// standard library's hasher is not promised to be.
|
||||
pub fn store_id(server: &str) -> [u8; 16] {
|
||||
fn fnv(bytes: &[u8], basis: u64) -> u64 {
|
||||
bytes
|
||||
.iter()
|
||||
.fold(basis, |hash, b| (hash ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3))
|
||||
}
|
||||
let bytes = server.as_bytes();
|
||||
let hi = fnv(bytes, 0xcbf2_9ce4_8422_2325);
|
||||
let lo = fnv(bytes, 0x8422_2325_cbf2_9ce4 ^ 0x5eed);
|
||||
let mut id = [0u8; 16];
|
||||
id[..8].copy_from_slice(&hi.to_be_bytes());
|
||||
id[8..].copy_from_slice(&lo.to_be_bytes());
|
||||
// A well-formed UUID: version 8 (custom), RFC 4122 variant.
|
||||
id[6] = (id[6] & 0x0f) | 0x80;
|
||||
id[8] = (id[8] & 0x3f) | 0x80;
|
||||
id
|
||||
}
|
||||
|
||||
/// Where `from` lands when the strip asks to move it to `to`, both indexes
|
||||
/// into a list of `len`. None for an index out of range or no move.
|
||||
pub fn moved(len: usize, from: usize, to: usize) -> Option<usize> {
|
||||
(from < len && to < len && from != to).then_some(to)
|
||||
}
|
||||
|
||||
/// The tab after (or before) `active` in a list of `len`, wrapping around.
|
||||
pub fn neighbour(len: usize, active: usize, forward: bool) -> Option<usize> {
|
||||
match len {
|
||||
0 => None,
|
||||
_ if forward => Some((active + 1) % len),
|
||||
_ => Some((active + len - 1) % len),
|
||||
}
|
||||
}
|
||||
|
||||
/// Which tab to show after closing the one at `closed` (of `len` before the
|
||||
/// close), when it was the active one: the tab that took its place, else the
|
||||
/// one before it.
|
||||
pub fn after_close(len: usize, closed: usize) -> Option<usize> {
|
||||
match len {
|
||||
0 | 1 => None,
|
||||
_ if closed + 1 < len => Some(closed),
|
||||
_ => Some(closed - 1),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `id` can be handed to Codeman's page as a session id: what Codeman
|
||||
/// makes (UUIDs) and nothing that could step out of a string.
|
||||
pub fn is_session_id(id: &str) -> bool {
|
||||
!id.is_empty() && id.len() <= 128 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||
}
|
||||
|
||||
/// What a tab shows.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Kind {
|
||||
/// The connect page, nothing chosen yet.
|
||||
Connect,
|
||||
/// A server's page is on its way; the connect page still shows.
|
||||
Loading,
|
||||
/// A server's page.
|
||||
Server,
|
||||
}
|
||||
|
||||
/// What the badges of a tab are counted from: the last status read of its
|
||||
/// server, and whether that server answers at all.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Seen {
|
||||
pub detail: Option<Detail>,
|
||||
/// The last few reads failed.
|
||||
pub offline: bool,
|
||||
/// The server refused the login: nothing is asked any more.
|
||||
pub refused: bool,
|
||||
}
|
||||
|
||||
/// One tab as the strip and the overview see it.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct View<'a> {
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
pub color: &'a str,
|
||||
pub kind: Kind,
|
||||
pub url: Option<&'a Url>,
|
||||
pub version: Option<&'a str>,
|
||||
pub seen: &'a Seen,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, PartialEq, Eq, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Counts {
|
||||
pub needs_you: usize,
|
||||
pub waiting: usize,
|
||||
pub working: usize,
|
||||
pub sessions: usize,
|
||||
}
|
||||
|
||||
fn counts(seen: &Seen) -> Counts {
|
||||
let Some(detail) = &seen.detail else {
|
||||
return Counts::default();
|
||||
};
|
||||
let of = |state: SessionState| detail.sessions.iter().filter(|s| s.state == state).count();
|
||||
Counts {
|
||||
needs_you: of(SessionState::Needs),
|
||||
waiting: of(SessionState::Waiting),
|
||||
working: of(SessionState::Working),
|
||||
sessions: detail.sessions.len(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct StripStatus {
|
||||
working: usize,
|
||||
waiting: usize,
|
||||
needs_you: usize,
|
||||
offline: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct StripTab<'a> {
|
||||
id: u64,
|
||||
name: &'a str,
|
||||
color: &'a str,
|
||||
active: bool,
|
||||
kind: Kind,
|
||||
local: bool,
|
||||
url: Option<&'a str>,
|
||||
key: Option<usize>,
|
||||
status: StripStatus,
|
||||
}
|
||||
|
||||
/// The ⌘ number of the tab at `index`: ⌘1 to ⌘8 for the first eight, ⌘9 for
|
||||
/// the last one, as in Safari.
|
||||
pub fn key_of(index: usize, len: usize) -> Option<usize> {
|
||||
match index {
|
||||
_ if index + 1 == len && len > 8 => Some(9),
|
||||
i if i < 8 => Some(i + 1),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The tab ⌘`key` selects in a list of `len`.
|
||||
pub fn index_of_key(key: usize, len: usize) -> Option<usize> {
|
||||
match key {
|
||||
9 if len > 0 => Some(len - 1),
|
||||
k @ 1..=8 if k <= len => Some(k - 1),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The strip's whole state (`assets/tabs.html`, message `state`).
|
||||
pub fn strip_state(tabs: &[View<'_>], active: Option<usize>, overview: bool, fullscreen: bool) -> serde_json::Value {
|
||||
let len = tabs.len();
|
||||
let list: Vec<StripTab<'_>> = tabs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, t)| {
|
||||
let c = counts(t.seen);
|
||||
StripTab {
|
||||
id: t.id,
|
||||
name: &t.name,
|
||||
color: t.color,
|
||||
active: !overview && active == Some(i),
|
||||
kind: t.kind,
|
||||
local: t.url.is_some_and(crate::policy::is_loopback),
|
||||
url: t.url.map(Url::as_str),
|
||||
key: key_of(i, len),
|
||||
status: StripStatus {
|
||||
working: c.working,
|
||||
waiting: c.waiting,
|
||||
needs_you: c.needs_you,
|
||||
offline: t.kind == Kind::Server && t.seen.offline,
|
||||
},
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
serde_json::json!({
|
||||
"type": "state",
|
||||
"tabs": list,
|
||||
"overviewActive": overview,
|
||||
"fullscreen": fullscreen,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Row<'a> {
|
||||
id: &'a str,
|
||||
name: &'a str,
|
||||
state: SessionState,
|
||||
text: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Card<'a> {
|
||||
tab: u64,
|
||||
name: &'a str,
|
||||
color: &'a str,
|
||||
url: Option<&'a str>,
|
||||
local: bool,
|
||||
key: Option<usize>,
|
||||
version: Option<&'a str>,
|
||||
kind: Kind,
|
||||
offline: bool,
|
||||
refused: bool,
|
||||
sessions: Vec<Row<'a>>,
|
||||
counts: Counts,
|
||||
}
|
||||
|
||||
/// The overview's whole state (`assets/overview.html`, message `state`): a
|
||||
/// card per tab, the servers that need someone first, then those with an agent
|
||||
/// waiting, then the rest in tab order. Each card lists its sessions most
|
||||
/// urgent first, `OVERVIEW_ROWS` at most.
|
||||
pub fn overview_state(tabs: &[View<'_>]) -> serde_json::Value {
|
||||
let len = tabs.len();
|
||||
let mut cards: Vec<(usize, Card<'_>)> = tabs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, t)| {
|
||||
let mut rows: Vec<Row<'_>> = t
|
||||
.seen
|
||||
.detail
|
||||
.iter()
|
||||
.flat_map(|d| d.sessions.iter())
|
||||
.map(|s| Row {
|
||||
id: &s.id,
|
||||
name: &s.name,
|
||||
state: s.state,
|
||||
text: &s.text,
|
||||
})
|
||||
.collect();
|
||||
rows.sort_by_key(|r| r.state.rank());
|
||||
rows.truncate(OVERVIEW_ROWS);
|
||||
(
|
||||
i,
|
||||
Card {
|
||||
tab: t.id,
|
||||
name: &t.name,
|
||||
color: t.color,
|
||||
url: t.url.map(Url::as_str),
|
||||
local: t.url.is_some_and(crate::policy::is_loopback),
|
||||
key: key_of(i, len),
|
||||
version: t.version,
|
||||
kind: t.kind,
|
||||
offline: t.kind == Kind::Server && t.seen.offline,
|
||||
refused: t.seen.refused,
|
||||
sessions: rows,
|
||||
counts: counts(t.seen),
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
cards.sort_by_key(|(i, card)| {
|
||||
let urgency = match (card.counts.needs_you, card.counts.waiting) {
|
||||
(n, _) if n > 0 => 0,
|
||||
(_, w) if w > 0 => 1,
|
||||
_ => 2,
|
||||
};
|
||||
(urgency, *i)
|
||||
});
|
||||
let servers: Vec<Card<'_>> = cards.into_iter().map(|(_, c)| c).collect();
|
||||
serde_json::json!({ "type": "state", "servers": servers })
|
||||
}
|
||||
|
||||
/// The window title while a tab shows: the page's own title, else the tab's
|
||||
/// name.
|
||||
pub fn window_title(page_title: Option<&str>, name: &str) -> String {
|
||||
match page_title.map(str::trim) {
|
||||
Some(t) if !t.is_empty() => t.to_string(),
|
||||
_ => name.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether two server addresses are on the same host (scheme and port aside):
|
||||
/// the case where, without a data store of their own, they would share a login
|
||||
/// cookie.
|
||||
pub fn same_host(a: &Url, b: &Url) -> bool {
|
||||
match (a.host_str(), b.host_str()) {
|
||||
(Some(x), Some(y)) => x.eq_ignore_ascii_case(y),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::agents::SessionRow;
|
||||
|
||||
fn u(s: &str) -> Url {
|
||||
Url::parse(s).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colours_are_hex_only() {
|
||||
assert!(is_color("#a78bfa"));
|
||||
assert!(is_color("#A78BFA"));
|
||||
assert!(!is_color("a78bfa"));
|
||||
assert!(!is_color("#a78bf"));
|
||||
assert!(!is_color("#a78bfg"));
|
||||
assert!(!is_color("red;background:url(x)"));
|
||||
assert!(!is_color("#a78bfa;"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_tabs_take_the_first_free_colour() {
|
||||
assert_eq!(next_color([]), PALETTE[0]);
|
||||
assert_eq!(next_color([PALETTE[0]]), PALETTE[1]);
|
||||
assert_eq!(next_color([PALETTE[1], "#A78BFA"]), PALETTE[2]);
|
||||
let all: Vec<&str> = PALETTE.to_vec();
|
||||
assert_eq!(next_color(all.clone()), PALETTE[0]);
|
||||
let mut seven = all;
|
||||
seven.push(PALETTE[0]);
|
||||
assert_eq!(next_color(seven), PALETTE[1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_names() {
|
||||
assert_eq!(default_name(&u("http://127.0.0.1:3000/")), "This Mac");
|
||||
assert_eq!(default_name(&u("http://localhost:3000/")), "This Mac");
|
||||
assert_eq!(default_name(&u("http://127.0.0.1:5000/")), "This Mac:5000");
|
||||
assert_eq!(default_name(&u("https://studio.example.ts.net/")), "studio");
|
||||
assert_eq!(default_name(&u("http://build-01.lan:3000/")), "build-01");
|
||||
assert_eq!(default_name(&u("http://192.168.1.40:3000/")), "192.168.1.40");
|
||||
assert_eq!(
|
||||
default_name(&u("http://192.168.1.40:8080/codeman/")),
|
||||
"192.168.1.40:8080"
|
||||
);
|
||||
assert_eq!(default_name(&u("http://[fd00::1]:3000/")), "[fd00::1]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_are_cleaned() {
|
||||
assert_eq!(clean_name(" studio ").as_deref(), Some("studio"));
|
||||
assert_eq!(clean_name("a\u{0}b\nc").as_deref(), Some("abc"));
|
||||
assert_eq!(clean_name(" "), None);
|
||||
assert_eq!(clean_name(""), None);
|
||||
let long = "x".repeat(100);
|
||||
assert_eq!(clean_name(&long).map(|n| n.chars().count()), Some(MAX_NAME));
|
||||
// Characters, not bytes: a multi-byte name is not cut inside a character.
|
||||
let wide = "ü".repeat(60);
|
||||
assert_eq!(clean_name(&wide).map(|n| n.chars().count()), Some(MAX_NAME));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renames() {
|
||||
// Escape on a new tab sends back what it shows: nothing changes.
|
||||
assert_eq!(renamed("New server", "New server", None), None);
|
||||
assert_eq!(renamed(" studio ", "studio", Some("studio")), None);
|
||||
assert_eq!(
|
||||
renamed("prod box", "studio", Some("studio")),
|
||||
Some(Some("prod box".into()))
|
||||
);
|
||||
// The default typed out, or nothing at all, is the default again.
|
||||
assert_eq!(renamed("studio", "prod box", Some("studio")), Some(None));
|
||||
assert_eq!(renamed(" ", "prod box", Some("studio")), Some(None));
|
||||
// A shown name longer than a name may be, sent back unchanged.
|
||||
let long = "x".repeat(60);
|
||||
assert_eq!(renamed(&long, &long, None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn store_ids_are_stable_and_distinct() {
|
||||
let a = store_id("http://127.0.0.1:3000/");
|
||||
assert_eq!(a, store_id("http://127.0.0.1:3000/"));
|
||||
assert_ne!(a, store_id("http://127.0.0.1:5000/"));
|
||||
assert_ne!(a, store_id("http://127.0.0.1:3000/x/"));
|
||||
// Version 8, RFC 4122 variant.
|
||||
assert_eq!(a[6] >> 4, 8);
|
||||
assert_eq!(a[8] >> 6, 0b10);
|
||||
// Pinned, so a change of the hash (which would cost every server its
|
||||
// local storage) fails here first.
|
||||
assert_eq!(
|
||||
store_id(""),
|
||||
[0xcb, 0xf2, 0x9c, 0xe4, 0x84, 0x22, 0x83, 0x25, 0x84, 0x22, 0x23, 0x25, 0xcb, 0xf2, 0xc2, 0x09]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn order_helpers() {
|
||||
assert_eq!(moved(3, 0, 2), Some(2));
|
||||
assert_eq!(moved(3, 1, 1), None);
|
||||
assert_eq!(moved(3, 3, 0), None);
|
||||
assert_eq!(moved(3, 0, 3), None);
|
||||
assert_eq!(neighbour(3, 2, true), Some(0));
|
||||
assert_eq!(neighbour(3, 0, false), Some(2));
|
||||
assert_eq!(neighbour(0, 0, true), None);
|
||||
assert_eq!(after_close(3, 0), Some(0));
|
||||
assert_eq!(after_close(3, 2), Some(1));
|
||||
assert_eq!(after_close(1, 0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_numbers() {
|
||||
assert_eq!(key_of(0, 3), Some(1));
|
||||
assert_eq!(key_of(2, 3), Some(3));
|
||||
assert_eq!(key_of(7, 12), Some(8));
|
||||
assert_eq!(key_of(8, 12), None);
|
||||
assert_eq!(key_of(11, 12), Some(9));
|
||||
assert_eq!(key_of(8, 9), Some(9));
|
||||
assert_eq!(index_of_key(1, 3), Some(0));
|
||||
assert_eq!(index_of_key(3, 3), Some(2));
|
||||
assert_eq!(index_of_key(4, 3), None);
|
||||
assert_eq!(index_of_key(9, 3), Some(2));
|
||||
assert_eq!(index_of_key(9, 0), None);
|
||||
assert_eq!(index_of_key(0, 3), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_ids() {
|
||||
assert!(is_session_id("0f8d0215-661e-4a1c-bfad-d7f6fd2ed4b5"));
|
||||
assert!(!is_session_id(""));
|
||||
assert!(!is_session_id("a'b"));
|
||||
assert!(!is_session_id("a\"); alert(1); (\""));
|
||||
assert!(!is_session_id(&"a".repeat(129)));
|
||||
}
|
||||
|
||||
fn row(id: &str, state: SessionState) -> SessionRow {
|
||||
SessionRow {
|
||||
id: id.into(),
|
||||
name: id.into(),
|
||||
state,
|
||||
text: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn seen(rows: Vec<SessionRow>) -> Seen {
|
||||
Seen {
|
||||
detail: Some(Detail { sessions: rows }),
|
||||
offline: false,
|
||||
refused: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strip_state_marks_the_active_tab_and_counts() {
|
||||
let a = u("http://127.0.0.1:3000/");
|
||||
let b = u("https://studio.example.ts.net/");
|
||||
let busy = seen(vec![
|
||||
row("1", SessionState::Working),
|
||||
row("2", SessionState::Needs),
|
||||
row("3", SessionState::Needs),
|
||||
row("4", SessionState::Waiting),
|
||||
]);
|
||||
let none = Seen {
|
||||
offline: true,
|
||||
..Seen::default()
|
||||
};
|
||||
let tabs = [
|
||||
View {
|
||||
id: 1,
|
||||
name: "This Mac".into(),
|
||||
color: PALETTE[0],
|
||||
kind: Kind::Server,
|
||||
url: Some(&a),
|
||||
version: None,
|
||||
seen: &busy,
|
||||
},
|
||||
View {
|
||||
id: 2,
|
||||
name: "studio".into(),
|
||||
color: PALETTE[1],
|
||||
kind: Kind::Server,
|
||||
url: Some(&b),
|
||||
version: None,
|
||||
seen: &none,
|
||||
},
|
||||
];
|
||||
let state = strip_state(&tabs, Some(1), false, true);
|
||||
assert_eq!(state["type"], "state");
|
||||
assert_eq!(state["fullscreen"], true);
|
||||
assert_eq!(state["tabs"][0]["active"], false);
|
||||
assert_eq!(state["tabs"][1]["active"], true);
|
||||
assert_eq!(state["tabs"][0]["local"], true);
|
||||
assert_eq!(state["tabs"][0]["status"]["needsYou"], 2);
|
||||
assert_eq!(state["tabs"][0]["status"]["waiting"], 1);
|
||||
assert_eq!(state["tabs"][0]["status"]["working"], 1);
|
||||
assert_eq!(state["tabs"][1]["status"]["offline"], true);
|
||||
assert_eq!(state["tabs"][1]["key"], 2);
|
||||
// The overview takes the place of the active tab.
|
||||
let state = strip_state(&tabs, Some(1), true, false);
|
||||
assert_eq!(state["tabs"][1]["active"], false);
|
||||
assert_eq!(state["overviewActive"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overview_puts_urgent_servers_and_sessions_first() {
|
||||
let a = u("http://127.0.0.1:3000/");
|
||||
let b = u("https://studio.example.ts.net/");
|
||||
let calm = seen(vec![row("w", SessionState::Working), row("i", SessionState::Idle)]);
|
||||
let urgent = seen(vec![
|
||||
row("i1", SessionState::Idle),
|
||||
row("i2", SessionState::Idle),
|
||||
row("w1", SessionState::Working),
|
||||
row("n1", SessionState::Needs),
|
||||
row("y1", SessionState::Waiting),
|
||||
row("i3", SessionState::Idle),
|
||||
]);
|
||||
let tabs = [
|
||||
View {
|
||||
id: 10,
|
||||
name: "This Mac".into(),
|
||||
color: PALETTE[0],
|
||||
kind: Kind::Server,
|
||||
url: Some(&a),
|
||||
version: Some("1.51.0"),
|
||||
seen: &calm,
|
||||
},
|
||||
View {
|
||||
id: 11,
|
||||
name: "studio".into(),
|
||||
color: PALETTE[1],
|
||||
kind: Kind::Server,
|
||||
url: Some(&b),
|
||||
version: None,
|
||||
seen: &urgent,
|
||||
},
|
||||
];
|
||||
let state = overview_state(&tabs);
|
||||
let servers = state["servers"].as_array().unwrap();
|
||||
assert_eq!(servers[0]["tab"], 11);
|
||||
assert_eq!(servers[0]["key"], 2);
|
||||
assert_eq!(servers[1]["tab"], 10);
|
||||
let rows: Vec<&str> = servers[0]["sessions"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|r| r["id"].as_str().unwrap())
|
||||
.collect();
|
||||
assert_eq!(rows, ["n1", "y1", "w1", "i1"]);
|
||||
assert_eq!(servers[0]["counts"]["sessions"], 6);
|
||||
assert_eq!(servers[0]["sessions"][0]["state"], "needs");
|
||||
assert_eq!(servers[1]["version"], "1.51.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn titles_and_hosts() {
|
||||
assert_eq!(window_title(Some(" Codeman "), "atlas"), "Codeman");
|
||||
assert_eq!(window_title(Some(""), "atlas"), "atlas");
|
||||
assert_eq!(window_title(None, "atlas"), "atlas");
|
||||
assert!(same_host(&u("http://127.0.0.1:3000/"), &u("http://127.0.0.1:5000/")));
|
||||
assert!(same_host(&u("http://Studio.lan:3000/"), &u("https://studio.lan/")));
|
||||
assert!(!same_host(&u("http://127.0.0.1:3000/"), &u("http://localhost:3000/")));
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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,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,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.1",
|
||||
"version": "1.52.1",
|
||||
"author": {
|
||||
"name": "Ark0N",
|
||||
"url": "https://github.com/Ark0N"
|
||||
|
||||
@@ -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',
|
||||
|
||||
+28
-21
@@ -1,20 +1,21 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* @fileoverview `npm run release`: `changeset publish` with `README.zh-CN.md` moved aside.
|
||||
* @fileoverview `npm run release`: `changeset publish` with the translated READMEs moved aside.
|
||||
*
|
||||
* npmjs.com renders the package's top-level `readme`, and npm picks it at publish time:
|
||||
* @npmcli/package-json's normalize globs `{README,README.*}` in the package root UNSORTED and
|
||||
* keeps the first `.md` it sees. With `README.zh-CN.md` next to `README.md` that was the
|
||||
* Chinese one on this machine and on CI, so npmjs.com showed the Chinese README for months.
|
||||
* Every translated root README (`README.zh-CN.md`, `README.ja.md`) is moved aside the same way.
|
||||
* `files` cannot help: npm-packlist always includes every root `README.*`.
|
||||
*
|
||||
* Renaming the file would break every link to it, so for the length of the publish only it
|
||||
* Renaming the files would break every link to them, so for the length of the publish only each
|
||||
* moves to a name npm does not treat as a readme (a leading dot), and is put back afterwards,
|
||||
* whatever the publish did. The move happens HERE, inside the publish command, never as a
|
||||
* step before `changesets/action` in release.yml: that action also runs the version path and
|
||||
* commits the working tree into its version PR, which would commit the deletion.
|
||||
*
|
||||
* A previous run killed between the move and the restore leaves the aside copy behind; the
|
||||
* A previous run killed between the move and the restore leaves an aside copy behind; the
|
||||
* next run puts it back first. `xterm-zerolag-input` (packages/) has only a README.md.
|
||||
*
|
||||
* node scripts/npm-release.mjs what the Release workflow runs (via `npm run release`)
|
||||
@@ -24,34 +25,40 @@ import { spawnSync } from 'node:child_process';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
export const HIDDEN_README = 'README.zh-CN.md';
|
||||
export const ASIDE_NAME = '.README.zh-CN.md.release-aside';
|
||||
export const HIDDEN_READMES = ['README.zh-CN.md', 'README.ja.md'];
|
||||
/** @param {string} name */
|
||||
export const asideName = (name) => `.${name}.release-aside`;
|
||||
export const HIDDEN_README = HIDDEN_READMES[0];
|
||||
export const ASIDE_NAME = asideName(HIDDEN_README);
|
||||
|
||||
/**
|
||||
* Runs `publish` with `HIDDEN_README` moved aside in `root`, restoring it afterwards, also
|
||||
* when `publish` fails or throws. Returns the exit code `publish` returned.
|
||||
* Runs `publish` with every `HIDDEN_READMES` file moved aside in `root`, restoring them
|
||||
* afterwards, also when `publish` fails or throws. Returns the exit code `publish` returned.
|
||||
*
|
||||
* @param {{ root: string, publish: () => number, log?: (msg: string) => void }} opts
|
||||
* @returns {number}
|
||||
*/
|
||||
export function publishWithReadmeAside({ root, publish, log = (msg) => console.log(msg) }) {
|
||||
const original = join(root, HIDDEN_README);
|
||||
const aside = join(root, ASIDE_NAME);
|
||||
if (existsSync(aside) && !existsSync(original)) {
|
||||
renameSync(aside, original);
|
||||
log(`npm-release: restored ${HIDDEN_README} left aside by an earlier run`);
|
||||
}
|
||||
const moved = existsSync(original);
|
||||
if (moved) {
|
||||
renameSync(original, aside);
|
||||
log(`npm-release: ${HIDDEN_README} moved aside so npm picks README.md as the readme`);
|
||||
}
|
||||
const moved = [];
|
||||
try {
|
||||
for (const name of HIDDEN_READMES) {
|
||||
const original = join(root, name);
|
||||
const aside = join(root, asideName(name));
|
||||
if (existsSync(aside) && !existsSync(original)) {
|
||||
renameSync(aside, original);
|
||||
log(`npm-release: restored ${name} left aside by an earlier run`);
|
||||
}
|
||||
if (existsSync(original)) {
|
||||
renameSync(original, aside);
|
||||
moved.push(name);
|
||||
log(`npm-release: ${name} moved aside so npm picks README.md as the readme`);
|
||||
}
|
||||
}
|
||||
return publish();
|
||||
} finally {
|
||||
if (moved) {
|
||||
renameSync(aside, original);
|
||||
log(`npm-release: ${HIDDEN_README} restored`);
|
||||
for (const name of moved) {
|
||||
renameSync(join(root, asideName(name)), join(root, name));
|
||||
log(`npm-release: ${name} restored`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -71,6 +71,20 @@ function renderToken(value: string, style: QuoteStyle | undefined): string {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The value an enum param resolves to: the caller's when it is a declared one, else the
|
||||
* default. Exported so `applyRootValues()` (root-launch.ts) judges the same value the
|
||||
* renderer is about to emit, rather than restating this rule.
|
||||
*/
|
||||
export function resolveEnumValue(
|
||||
spec: Extract<ParamSpec, { type: 'enum' }>,
|
||||
raw: string | boolean | undefined
|
||||
): string | undefined {
|
||||
if (raw === undefined) return spec.default;
|
||||
const s = String(raw);
|
||||
return spec.values.includes(s) ? s : spec.default;
|
||||
}
|
||||
|
||||
/** Resolve one parameter to a plain string, or undefined if it is unset / invalid. */
|
||||
function resolveParam(
|
||||
name: string,
|
||||
@@ -82,13 +96,10 @@ function resolveParam(
|
||||
if (spec.type === 'engine') return engineValues[spec.source];
|
||||
|
||||
const raw = params[name];
|
||||
if (raw === undefined) return spec.type === 'enum' ? spec.default : undefined;
|
||||
if (spec.type === 'enum') return resolveEnumValue(spec, raw);
|
||||
if (raw === undefined) return undefined;
|
||||
|
||||
if (spec.type === 'bool') return typeof raw === 'boolean' ? String(raw) : undefined;
|
||||
if (spec.type === 'enum') {
|
||||
const s = String(raw);
|
||||
return spec.values.includes(s) ? s : spec.default;
|
||||
}
|
||||
// token
|
||||
const s = String(raw);
|
||||
return matchesPattern(spec.pattern, s) ? s : undefined;
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* @fileoverview The launch params a CLI takes a different value for when it is started as
|
||||
* root. Pure: the caller says whether the launch runs as root, this module never asks.
|
||||
*
|
||||
* Claude Code refuses `--dangerously-skip-permissions` under uid 0 and exits, so a Codeman
|
||||
* server that runs as root (a VPS, an LXC container) showed a dead pane for every local
|
||||
* Claude session, the default permission mode being exactly that flag. Docker cases already
|
||||
* answer the same refusal for a root container with `overlays.docker.rootCommand`; this is
|
||||
* the host-level form, for a CLI the server process starts as its own child.
|
||||
*
|
||||
* Which value gives way to which is registry DATA (`ParamSpec.rootValue` on an enum param),
|
||||
* so no code here or at the call sites names a CLI. `applyRootValues()` runs BEFORE the argv
|
||||
* engine and only rewrites the param values handed to it: the engine, and with it every
|
||||
* command line of a launch that is not root, is untouched.
|
||||
*
|
||||
* ⚠️ Local launches only. A remote or Docker launch runs under another account, which the
|
||||
* server's uid says nothing about; those keep their own handling (`buildRemoteLaunchCommand`,
|
||||
* `rootCommand`). The callers decide that, by passing `runsAsRoot` false.
|
||||
*
|
||||
* @module config/cli-registry/root-launch
|
||||
*/
|
||||
|
||||
import { resolveEnumValue, type ParamValues } from './argv.js';
|
||||
import type { CliLaunch } from './types.js';
|
||||
|
||||
/** One param that was launched with its `rootValue` instead of the value it resolved to. */
|
||||
export interface RootValueChange {
|
||||
param: string;
|
||||
from: string;
|
||||
to: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply every declared `rootValue` to `params`.
|
||||
*
|
||||
* Returns the SAME `params` object when nothing changes (not root, or no param whose
|
||||
* resolved value has a replacement), so a caller can rely on a launch that is not root
|
||||
* rendering from exactly the values it passed in. Otherwise a copy, with `changes` naming
|
||||
* what was swapped so the caller can log it.
|
||||
*
|
||||
* The value judged is the one the renderer would emit: an absent or undeclared value counts
|
||||
* as the param's default, which is how the default permission mode is caught although no
|
||||
* caller ever sends it.
|
||||
*/
|
||||
export function applyRootValues(
|
||||
launch: CliLaunch,
|
||||
params: ParamValues,
|
||||
runsAsRoot: boolean
|
||||
): { params: ParamValues; changes: RootValueChange[] } {
|
||||
const changes: RootValueChange[] = [];
|
||||
if (!runsAsRoot) return { params, changes };
|
||||
let out = params;
|
||||
for (const [name, spec] of Object.entries(launch.params)) {
|
||||
if (spec.type !== 'enum' || !spec.rootValue) continue;
|
||||
const from = resolveEnumValue(spec, params[name]);
|
||||
if (from === undefined || !Object.hasOwn(spec.rootValue, from)) continue;
|
||||
const to = spec.rootValue[from];
|
||||
// Schema-validated at load; belt and braces, since a value outside `values` would
|
||||
// resolve back to the default, which is the very value being replaced.
|
||||
if (to === from || !spec.values.includes(to)) continue;
|
||||
if (out === params) out = { ...params };
|
||||
out[name] = to;
|
||||
changes.push({ param: name, from, to });
|
||||
}
|
||||
return { params: out, changes };
|
||||
}
|
||||
|
||||
/**
|
||||
* The one log line for a launch that took a `rootValue`. `what` names the launch ("Claude
|
||||
* Code session 0f9c2b14"); the wording stays free of any CLI's vocabulary because the
|
||||
* params and values in it are the registry's own.
|
||||
*/
|
||||
export function describeRootValueChanges(what: string, changes: readonly RootValueChange[]): string {
|
||||
const swapped = changes.map((c) => `${c.param} "${c.from}" as "${c.to}"`).join(', ');
|
||||
return (
|
||||
`${what} is launched with ${swapped}: the Codeman server runs as root (uid 0), and the CLI refuses ` +
|
||||
`the configured value under root. Run Codeman as a normal user to get the configured value back.`
|
||||
);
|
||||
}
|
||||
@@ -67,7 +67,13 @@ const condSchema: z.ZodType<import('./types.js').Cond> = z.lazy(() =>
|
||||
|
||||
const paramSpecSchema = z.union([
|
||||
z
|
||||
.object({ type: z.literal('enum'), values: z.array(z.string()).min(1).max(16), default: z.string().optional() })
|
||||
.object({
|
||||
type: z.literal('enum'),
|
||||
values: z.array(z.string()).min(1).max(16),
|
||||
default: z.string().optional(),
|
||||
// Cross-checked against `values` in launchSchema's superRefine below.
|
||||
rootValue: z.record(z.string(), z.string()).optional(),
|
||||
})
|
||||
.strict(),
|
||||
z.object({ type: z.literal('bool') }).strict(),
|
||||
z.object({ type: z.literal('token'), pattern: z.enum(TOKEN_PATTERNS as [string, ...string[]]) }).strict(),
|
||||
@@ -145,6 +151,29 @@ const launchSchema = z
|
||||
});
|
||||
}
|
||||
}
|
||||
// `rootValue` swaps one declared value for another when the server runs as root. A key or
|
||||
// a replacement outside `values` could never apply (or would launch with a value no arg
|
||||
// tests for), and a replacement that is itself replaced would make the outcome depend on
|
||||
// how many passes the reader makes.
|
||||
for (const [paramName, spec] of Object.entries(launch.params)) {
|
||||
if (spec.type !== 'enum' || !spec.rootValue) continue;
|
||||
for (const [from, to] of Object.entries(spec.rootValue)) {
|
||||
const path = ['params', paramName, 'rootValue', from];
|
||||
if (!spec.values.includes(from)) {
|
||||
ctx.addIssue({ code: 'custom', message: `rootValue key "${from}" is not one of this param's values`, path });
|
||||
}
|
||||
if (!spec.values.includes(to)) {
|
||||
ctx.addIssue({ code: 'custom', message: `rootValue "${to}" is not one of this param's values`, path });
|
||||
}
|
||||
if (to === from || Object.hasOwn(spec.rootValue, to)) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
message: `rootValue "${to}" must be a value that is launched as it is under root`,
|
||||
path,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (launch.legacyConfigAliases) {
|
||||
for (const paramName of Object.keys(launch.legacyConfigAliases)) {
|
||||
if (!paramNames.has(paramName)) {
|
||||
|
||||
@@ -142,6 +142,13 @@ const CLAUDE: CliEntry = {
|
||||
type: 'enum',
|
||||
values: ['dangerously-skip-permissions', 'auto', 'normal', 'allowedTools'],
|
||||
default: 'dangerously-skip-permissions',
|
||||
// ⚠️ Claude Code REFUSES the bypass flag under uid 0 ("cannot be used with root/sudo
|
||||
// privileges for security reasons") and exits, so under a server that runs as root (a
|
||||
// VPS, an LXC container) every local session was a dead pane, this being the default.
|
||||
// There it starts as `normal` and asks. The same refusal `overlays.docker.rootCommand`
|
||||
// below answers for a root container; the other three modes do not carry the flag
|
||||
// and stay as they are. Never force the bypass back on with `IS_SANDBOX`.
|
||||
rootValue: { 'dangerously-skip-permissions': 'normal' },
|
||||
},
|
||||
allowedTools: { type: 'token', pattern: 'tool-list' },
|
||||
model: { type: 'token', pattern: 'model-claude' },
|
||||
|
||||
@@ -45,7 +45,25 @@ export type EngineValue =
|
||||
* the only ones that need a pattern; `engine` params are produced in code.
|
||||
*/
|
||||
export type ParamSpec =
|
||||
| { type: 'enum'; values: string[]; default?: string }
|
||||
| {
|
||||
type: 'enum';
|
||||
values: string[];
|
||||
default?: string;
|
||||
/**
|
||||
* The value this param takes INSTEAD when the Codeman server process runs as uid 0 and
|
||||
* the launch is LOCAL (the CLI is then a child of that process, so it runs as root too).
|
||||
* Keyed by the value the param would otherwise resolve to, the default included; a
|
||||
* value with no key is launched as it is.
|
||||
*
|
||||
* For a value the CLI REFUSES under root, where the alternative is a pane that dies at
|
||||
* once. It is the host-level form of `overlays.docker.rootCommand`, which answers the
|
||||
* same refusal for a container whose exec user is uid 0. Remote and Docker launches
|
||||
* never read it: the server's uid says nothing about the account on the other side.
|
||||
* Applied by `applyRootValues()` (root-launch.ts); the schema requires every key and
|
||||
* every replacement to be one of `values`, and no replacement to be replaced again.
|
||||
*/
|
||||
rootValue?: Record<string, string>;
|
||||
}
|
||||
| { type: 'bool' }
|
||||
| { type: 'token'; pattern: TokenPattern }
|
||||
| { type: 'engine'; source: EngineValue };
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
/**
|
||||
* @fileoverview Trusted reverse-proxy identity (multi-user mode, opt-in, off by default).
|
||||
*
|
||||
* Lets an authenticating reverse proxy on the same host (oauth2-proxy behind Caddy or
|
||||
* nginx, Apache mod_auth_openidc, Authelia, ...) sign users in through an identity
|
||||
* provider such as Entra ID, Google or Keycloak, instead of the Basic-auth password
|
||||
* prompt. The proxy authenticates the person and forwards two headers:
|
||||
*
|
||||
* X-Codeman-Proxy-Secret: <the shared secret>
|
||||
* X-Codeman-User: <codeman username>
|
||||
*
|
||||
* Codeman accepts the identity only when ALL of these hold:
|
||||
* - multi-user mode is on (the username must name an existing, enabled account; there
|
||||
* is no auto-provisioning, so an admin still decides who has an account);
|
||||
* - a secret is configured: at least 32 printable ASCII characters, from
|
||||
* `CODEMAN_TRUSTED_PROXY_SECRET_FILE` (preferred) or `CODEMAN_TRUSTED_PROXY_SECRET`;
|
||||
* - the request arrives over a loopback socket (`req.ip`, which ignores
|
||||
* X-Forwarded-For because Fastify runs with `trustProxy: false`);
|
||||
* - the presented secret matches (timing-safe).
|
||||
*
|
||||
* What the secret does and does not separate: every process on the host reaches the
|
||||
* loopback port, so loopback alone proves nothing, and the secret is what a local process
|
||||
* lacks. It is not a boundary against code that can read the secret file or Codeman's
|
||||
* memory, i.e. anything running as Codeman's OS account (see the multi-user threat
|
||||
* model: sessions share that account). To keep it out of the obvious places, the value
|
||||
* is read ONCE and both `CODEMAN_TRUSTED_PROXY_SECRET` and
|
||||
* `CODEMAN_TRUSTED_PROXY_SECRET_FILE` are then deleted from `process.env`, because every
|
||||
* session Codeman spawns inherits that environment. The file's resolved path stays in
|
||||
* this module (`trustedProxySecretFilePath`, `trustedProxySecretFileRealPath`) for the
|
||||
* sensitive-path blocklist.
|
||||
*
|
||||
* A configured setup that can't be used stops the server from starting
|
||||
* (`trustedProxyConfigError`, thrown from `WebServer.start()`), so a typo never falls
|
||||
* back silently to password sign-in.
|
||||
*
|
||||
* The two headers are taken off every request before anything else sees them
|
||||
* (`takeTrustedProxyHeaders`, called from the first auth hook), so nothing downstream,
|
||||
* e.g. the web-tab relay, can forward or log them.
|
||||
*/
|
||||
|
||||
import { readFileSync, realpathSync, statSync } from 'node:fs';
|
||||
import type { IncomingHttpHeaders } from 'node:http';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
/** Header carrying the shared secret that proves the request came through the proxy. */
|
||||
export const TRUSTED_PROXY_SECRET_HEADER = 'x-codeman-proxy-secret';
|
||||
|
||||
/** Default header carrying the authenticated Codeman username. */
|
||||
export const DEFAULT_TRUSTED_PROXY_USER_HEADER = 'x-codeman-user';
|
||||
|
||||
/** Minimum secret length; a shorter secret stops the server from starting. */
|
||||
export const TRUSTED_PROXY_SECRET_MIN_LENGTH = 32;
|
||||
|
||||
/**
|
||||
* The username header is deleted from EVERY request (see takeTrustedProxyHeaders), so it
|
||||
* must never be a header anything else needs. Allowed by shape, not by a deny list of
|
||||
* standard headers: an `X-...` extension header (minus the reserved ones below) or the
|
||||
* conventional `Remote-User`.
|
||||
*/
|
||||
const USER_HEADER_RE = /^x-[a-z0-9][a-z0-9-]*$/;
|
||||
/** Identity headers authenticating proxies commonly send; allowed despite the reserved prefix. */
|
||||
const ALLOWED_FORWARDED_IDENTITY_HEADERS = new Set([
|
||||
'x-forwarded-user',
|
||||
'x-forwarded-email',
|
||||
'x-forwarded-preferred-username',
|
||||
]);
|
||||
const RESERVED_USER_HEADER_PREFIXES = ['x-forwarded-', 'x-codeman-'];
|
||||
const RESERVED_USER_HEADERS = new Set([
|
||||
'x-real-ip',
|
||||
'x-requested-with',
|
||||
'x-http-method-override',
|
||||
'x-csrf-token',
|
||||
'x-xsrf-token',
|
||||
]);
|
||||
|
||||
/** Resolved trusted-proxy configuration, or null when the feature is off. */
|
||||
export interface TrustedProxyConfig {
|
||||
secret: string;
|
||||
/** Lower-cased header name the username is read from. */
|
||||
userHeader: string;
|
||||
}
|
||||
|
||||
interface LoadedSecret {
|
||||
secret?: string;
|
||||
/** Why a configured secret can't be used (never contains the secret). */
|
||||
problem?: string;
|
||||
/** Absolute path of `CODEMAN_TRUSTED_PROXY_SECRET_FILE`, when it was set. */
|
||||
filePath?: string;
|
||||
/** That path with symlinks resolved, when it could be resolved. */
|
||||
fileRealPath?: string;
|
||||
}
|
||||
|
||||
let loaded: LoadedSecret | null = null;
|
||||
|
||||
/**
|
||||
* Read the secret once, then delete `CODEMAN_TRUSTED_PROXY_SECRET` and
|
||||
* `CODEMAN_TRUSTED_PROXY_SECRET_FILE` from `process.env` so sessions spawned later don't
|
||||
* inherit either. Cached for the process lifetime.
|
||||
*/
|
||||
function loadSecret(): LoadedSecret {
|
||||
if (loaded) return loaded;
|
||||
const inline = process.env.CODEMAN_TRUSTED_PROXY_SECRET?.trim();
|
||||
const file = process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE?.trim();
|
||||
delete process.env.CODEMAN_TRUSTED_PROXY_SECRET;
|
||||
delete process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE;
|
||||
const filePath = file ? resolve(file) : undefined;
|
||||
const fileRealPath = filePath ? realPathOrUndefined(filePath) : undefined;
|
||||
|
||||
let secret: string | undefined;
|
||||
let problem: string | undefined;
|
||||
if (inline && file) {
|
||||
problem = 'both CODEMAN_TRUSTED_PROXY_SECRET and CODEMAN_TRUSTED_PROXY_SECRET_FILE are set; set only one';
|
||||
} else if (file) {
|
||||
try {
|
||||
secret = readFileSync(file, 'utf-8').trim() || undefined;
|
||||
if (!secret) problem = `CODEMAN_TRUSTED_PROXY_SECRET_FILE (${file}) is empty`;
|
||||
// POSIX modes only; Windows reports synthetic ones.
|
||||
else if (process.platform !== 'win32' && (statSync(file).mode & 0o077) !== 0) {
|
||||
problem = `CODEMAN_TRUSTED_PROXY_SECRET_FILE (${file}) is readable by other users; chmod 600 it`;
|
||||
}
|
||||
} catch (err) {
|
||||
problem = `cannot read CODEMAN_TRUSTED_PROXY_SECRET_FILE (${file}): ${(err as NodeJS.ErrnoException).code ?? 'error'}`;
|
||||
}
|
||||
} else if (inline) {
|
||||
secret = inline;
|
||||
}
|
||||
if (secret && !problem) {
|
||||
if (secret.length < TRUSTED_PROXY_SECRET_MIN_LENGTH) {
|
||||
problem = `the trusted-proxy secret is shorter than ${TRUSTED_PROXY_SECRET_MIN_LENGTH} characters (generate one with: openssl rand -hex 32)`;
|
||||
} else if (!/^[\x21-\x7e]+$/.test(secret)) {
|
||||
// Header bytes arrive as latin1 and the env/file value as UTF-8, so anything outside
|
||||
// printable ASCII could never match.
|
||||
problem =
|
||||
'the trusted-proxy secret must be printable ASCII without spaces (generate one with: openssl rand -hex 32)';
|
||||
}
|
||||
}
|
||||
loaded = { secret, problem, filePath, fileRealPath };
|
||||
return loaded;
|
||||
}
|
||||
|
||||
function realPathOrUndefined(path: string): string | undefined {
|
||||
try {
|
||||
return realpathSync(path);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the secret now and remove both variables from `process.env`. Called first in
|
||||
* `WebServer.start()` and again (a no-op then) at auth setup, before any session is
|
||||
* spawned or restored, in every mode.
|
||||
*/
|
||||
export function initTrustedProxySecret(): void {
|
||||
loadSecret();
|
||||
}
|
||||
|
||||
/**
|
||||
* Absolute path of the configured secret file, or null. After the secret was read the
|
||||
* variable is gone from `process.env`, so this answers from the cached value; before
|
||||
* that, from the environment. Never reads the file.
|
||||
*/
|
||||
export function trustedProxySecretFilePath(): string | null {
|
||||
if (loaded) return loaded.filePath ?? null;
|
||||
const file = process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE?.trim();
|
||||
return file ? resolve(file) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The secret file's path with symlinks resolved, or null (not configured, or it can't be
|
||||
* resolved). Resolved once when the secret is read; before that, from the environment.
|
||||
*/
|
||||
export function trustedProxySecretFileRealPath(): string | null {
|
||||
if (loaded) return loaded.fileRealPath ?? null;
|
||||
const file = trustedProxySecretFilePath();
|
||||
return (file && realPathOrUndefined(file)) ?? null;
|
||||
}
|
||||
|
||||
/** Test-only: forget the cached secret so the next call re-reads the environment. */
|
||||
export function resetTrustedProxySecretForTests(): void {
|
||||
loaded = null;
|
||||
}
|
||||
|
||||
/** The configured username header (lower-cased), or the default. Not validated. */
|
||||
function rawUserHeader(): string {
|
||||
return process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER?.trim().toLowerCase() || DEFAULT_TRUSTED_PROXY_USER_HEADER;
|
||||
}
|
||||
|
||||
/** Why the configured username header can't be used, or null when it is fine. */
|
||||
function userHeaderProblem(name: string): string | null {
|
||||
if (name === DEFAULT_TRUSTED_PROXY_USER_HEADER || name === 'remote-user') return null;
|
||||
if (ALLOWED_FORWARDED_IDENTITY_HEADERS.has(name)) return null;
|
||||
if (!USER_HEADER_RE.test(name)) {
|
||||
return `CODEMAN_TRUSTED_PROXY_USER_HEADER (${name}) must be an X-... header or Remote-User`;
|
||||
}
|
||||
if (RESERVED_USER_HEADERS.has(name) || RESERVED_USER_HEADER_PREFIXES.some((p) => name.startsWith(p))) {
|
||||
return `CODEMAN_TRUSTED_PROXY_USER_HEADER may not be ${name} (reserved)`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The username header to strip and read: the configured one when it is usable, the default
|
||||
* otherwise. Resolve it once (at auth setup) and pass it to `takeTrustedProxyHeaders`. A
|
||||
* rejected name is never used, so a careless setting can't strip a header others need.
|
||||
*/
|
||||
export function resolveTrustedProxyUserHeader(): string {
|
||||
const name = rawUserHeader();
|
||||
return userHeaderProblem(name) ? DEFAULT_TRUSTED_PROXY_USER_HEADER : name;
|
||||
}
|
||||
|
||||
/**
|
||||
* The active configuration, or null when the feature is off: no usable secret, an
|
||||
* unusable username header, or single-user mode (no named accounts to map onto). The
|
||||
* unusable cases also stop the start (`trustedProxyConfigError`); this is the second layer.
|
||||
*/
|
||||
export function getTrustedProxyConfig(multiUser: boolean): TrustedProxyConfig | null {
|
||||
const { secret, problem } = loadSecret();
|
||||
if (!multiUser || !secret || problem) return null;
|
||||
const userHeader = rawUserHeader();
|
||||
if (userHeaderProblem(userHeader)) return null;
|
||||
return { secret, userHeader };
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a configured trusted-proxy setup can't be used, as the message for the start-up
|
||||
* refusal, or null when it is fine (not configured, or valid). Never includes the secret.
|
||||
* Refused: both secret variables set; a secret file that can't be read, is empty or is
|
||||
* readable by group or others (not checked on Windows); a secret shorter than 32
|
||||
* characters or not printable ASCII; a secret with multi-user mode off; and a
|
||||
* `CODEMAN_TRUSTED_PROXY_USER_HEADER` the validation rejects (set at all, secret or not).
|
||||
*/
|
||||
export function trustedProxyConfigError(multiUser: boolean): string | null {
|
||||
const { secret, problem } = loadSecret();
|
||||
let reason: string | null = null;
|
||||
if (problem) reason = problem;
|
||||
else if (secret && !multiUser) reason = 'a trusted-proxy secret is set but multi-user mode is off';
|
||||
else if (process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER?.trim()) reason = userHeaderProblem(rawUserHeader());
|
||||
return reason
|
||||
? `Trusted-proxy sign-in is misconfigured: ${reason}. Fix or remove the setting and start again.`
|
||||
: null;
|
||||
}
|
||||
|
||||
/** What a request presented, after `takeTrustedProxyHeaders` removed the headers. */
|
||||
export interface PresentedProxyHeaders {
|
||||
/** True when the secret header was present at all, even empty. */
|
||||
secretPresent: boolean;
|
||||
/** The presented secret (duplicates joined with ", ", so they never match). */
|
||||
secret: string;
|
||||
/**
|
||||
* The presented username exactly as sent ('' when absent). The auth hook normalizes and
|
||||
* validates it with the user store's own rule. A duplicated header arrives joined
|
||||
* ("alice, bob"), which that rule rejects, so it is refused with 403.
|
||||
*/
|
||||
user: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The two other views Node keeps of a request's headers, beside `headers`: the flat
|
||||
* `[name, value, ...]` list as received and the per-name arrays. Both are optional
|
||||
* because a light-my-request message (`app.inject`) may lack `headersDistinct`.
|
||||
*/
|
||||
export interface RawHeaderViews {
|
||||
headers?: IncomingHttpHeaders;
|
||||
rawHeaders?: string[];
|
||||
headersDistinct?: NodeJS.Dict<string[]>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove `names` (lowercase) from `raw.rawHeaders` and `raw.headersDistinct`, in place.
|
||||
*
|
||||
* ⚠️ Order matters on a real `http.IncomingMessage`: its `headers` and `headersDistinct`
|
||||
* getters are LAZY and walk `rawHeaders` up to a header count stored when the request was
|
||||
* parsed, so a getter that first runs after a splice reads past the shortened array and
|
||||
* throws. Both are therefore read (and so cached) BEFORE `rawHeaders` shrinks, and later
|
||||
* reads return the cached, already stripped objects.
|
||||
*/
|
||||
function stripRawHeaderViews(raw: RawHeaderViews, names: readonly string[]): void {
|
||||
void raw.headers;
|
||||
const distinct = raw.headersDistinct;
|
||||
if (distinct && typeof distinct === 'object') {
|
||||
for (const name of names) delete distinct[name];
|
||||
}
|
||||
const list = raw.rawHeaders;
|
||||
if (!Array.isArray(list)) return;
|
||||
for (let i = list.length - 2; i >= 0; i -= 2) {
|
||||
const name = list[i];
|
||||
if (typeof name === 'string' && names.includes(name.toLowerCase())) list.splice(i, 2);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the trusted-proxy headers and DELETE them from `headers`, so nothing that later
|
||||
* copies request headers (the web-tab relay, logging) ever sees the secret. Removes the
|
||||
* secret header, the default username header and `userHeader` (from
|
||||
* `resolveTrustedProxyUserHeader`, so always a usable name), whether or not the feature is
|
||||
* on: a proxy may send them to an instance that has it off. Given the raw message (`raw`,
|
||||
* the auth hook passes `req.raw`), it removes them from `rawHeaders` and `headersDistinct`
|
||||
* too, so no view of the request still holds the secret.
|
||||
*/
|
||||
export function takeTrustedProxyHeaders(
|
||||
headers: IncomingHttpHeaders,
|
||||
userHeader: string = DEFAULT_TRUSTED_PROXY_USER_HEADER,
|
||||
raw?: RawHeaderViews
|
||||
): PresentedProxyHeaders {
|
||||
const rawSecret = headers[TRUSTED_PROXY_SECRET_HEADER];
|
||||
const rawUser = headers[userHeader];
|
||||
if (raw) stripRawHeaderViews(raw, [TRUSTED_PROXY_SECRET_HEADER, DEFAULT_TRUSTED_PROXY_USER_HEADER, userHeader]);
|
||||
delete headers[TRUSTED_PROXY_SECRET_HEADER];
|
||||
delete headers[DEFAULT_TRUSTED_PROXY_USER_HEADER];
|
||||
delete headers[userHeader];
|
||||
|
||||
return {
|
||||
secretPresent: rawSecret !== undefined,
|
||||
secret: Array.isArray(rawSecret) ? rawSecret.join(', ') : (rawSecret ?? ''),
|
||||
user: Array.isArray(rawUser) ? rawUser.join(', ') : (rawUser ?? ''),
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -14,12 +14,50 @@ import { getAugmentedPath } from './utils/index.js';
|
||||
import { compareVersions } from './utils/dependency-checker.js';
|
||||
import { dataPath } from './config/instance.js';
|
||||
import { getCli } from './config/cli-registry/registry.js';
|
||||
import { applyRootValues, describeRootValueChanges } from './config/cli-registry/root-launch.js';
|
||||
import { serverRunsAsRoot } from './utils/server-uid.js';
|
||||
|
||||
/** Narrow a registry value back to the wire type; anything else keeps the caller's own mode. */
|
||||
function isClaudeMode(value: unknown): value is ClaudeMode {
|
||||
return value === 'dangerously-skip-permissions' || value === 'auto' || value === 'normal' || value === 'allowedTools';
|
||||
}
|
||||
|
||||
/**
|
||||
* The permission mode a claude process started DIRECTLY by this server gets (the direct-PTY
|
||||
* fallback and the one-shot `-p` run, both children of the server process).
|
||||
*
|
||||
* Under a server that runs as root the bypass mode gives way to the registry's declared
|
||||
* `rootValue` (`normal`): Claude Code exits on `--dangerously-skip-permissions` under uid 0.
|
||||
* The tmux path applies the same registry data through `serverRootSpawnOptions()`; this is
|
||||
* its counterpart for the two launches that never reach the argv engine. Pure: the caller
|
||||
* says whether the server is root, and `onChange` gets the log line when the mode moved.
|
||||
*/
|
||||
export function directLaunchClaudeMode(
|
||||
claudeMode: ClaudeMode,
|
||||
runsAsRoot: boolean,
|
||||
onChange?: (line: string) => void
|
||||
): ClaudeMode {
|
||||
const launch = getCli('claude')?.launch;
|
||||
if (!launch) return claudeMode;
|
||||
const { params, changes } = applyRootValues(launch, { claudeMode }, runsAsRoot);
|
||||
const effective = params.claudeMode;
|
||||
if (changes.length === 0 || !isClaudeMode(effective)) return claudeMode;
|
||||
onChange?.(describeRootValueChanges('A directly started Claude Code process', changes));
|
||||
return effective;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build Claude CLI permission flags based on the configured mode.
|
||||
* Returns an array of args to pass to the CLI.
|
||||
*
|
||||
* ⚠️ Both direct launches (`buildInteractiveArgs`, `buildPromptArgs`) get their flags here,
|
||||
* so this is where the root downgrade is applied for them: see `directLaunchClaudeMode`.
|
||||
* The uid is asked at call time (`serverRunsAsRoot()`), never cached.
|
||||
*/
|
||||
function buildPermissionArgs(claudeMode: ClaudeMode, allowedTools?: string): string[] {
|
||||
function buildPermissionArgs(configuredMode: ClaudeMode, allowedTools?: string): string[] {
|
||||
const claudeMode = directLaunchClaudeMode(configuredMode, serverRunsAsRoot(), (line) =>
|
||||
console.warn(`[Session] ${line}`)
|
||||
);
|
||||
switch (claudeMode) {
|
||||
case 'dangerously-skip-permissions':
|
||||
return ['--dangerously-skip-permissions'];
|
||||
|
||||
@@ -21,6 +21,7 @@ import { getDiscordStartupHint } from './discord-bridge.js';
|
||||
import type { CliEntry } from './config/cli-registry/types.js';
|
||||
import { renderLaunch, type EngineValues, type ParamValues } from './config/cli-registry/argv.js';
|
||||
import { matchesPattern } from './config/cli-registry/patterns.js';
|
||||
import { applyRootValues, type RootValueChange } from './config/cli-registry/root-launch.js';
|
||||
import { buildAdvisorSettings, buildEffortCliArgs, sanitizeCliSessionName } from './session-cli-builder.js';
|
||||
import { compareVersions } from './utils/dependency-checker.js';
|
||||
import { resolveSessionCliVersion } from './utils/cli-resolver.js';
|
||||
@@ -77,6 +78,16 @@ export interface SpawnBridgeOptions {
|
||||
* passed) by TmuxManager._resolveIdleCompactionOptOut, which records it on the mux record.
|
||||
*/
|
||||
idleCompactionOff?: boolean;
|
||||
/**
|
||||
* True when this command will run as a child of a server process whose uid is 0: a LOCAL
|
||||
* launch under a root server. Params that declare a `rootValue` then take it (see
|
||||
* config/cli-registry/root-launch.ts). Decided by the caller, never here: this bridge also
|
||||
* renders commands that run under another account (the remote omp relaunch), where the
|
||||
* server's uid means nothing. Absent or false leaves the command byte-identical.
|
||||
*/
|
||||
runsAsServerRoot?: boolean;
|
||||
/** Told which params took their `rootValue`, so the launch site can log it. Never called with none. */
|
||||
onRootValue?: (changes: RootValueChange[]) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -209,7 +220,14 @@ function gateVersion(entry: CliEntry, explicit: string | null | undefined): stri
|
||||
export function buildSpawnCommandFromRegistry(entry: CliEntry, options: SpawnBridgeOptions): string | undefined {
|
||||
if (entry.kind === 'shell' || entry.launch.variants.length === 0) return undefined;
|
||||
|
||||
const params = buildParamsFromLegacyConfig(entry, legacyConfigFor(entry, options));
|
||||
// A value the CLI refuses under root gives way to its declared `rootValue` before the engine
|
||||
// sees it. Not root: `applyRootValues` hands back the very object it was given.
|
||||
const { params, changes: rootChanges } = applyRootValues(
|
||||
entry.launch,
|
||||
buildParamsFromLegacyConfig(entry, legacyConfigFor(entry, options)),
|
||||
options.runsAsServerRoot === true
|
||||
);
|
||||
if (rootChanges.length > 0) options.onRootValue?.(rootChanges);
|
||||
|
||||
const engineValues: EngineValues = {
|
||||
sessionId: options.sessionId,
|
||||
|
||||
+39
-3
@@ -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';
|
||||
|
||||
+269
-95
@@ -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,
|
||||
@@ -81,6 +81,8 @@ import {
|
||||
} from './session-cli-registry-bridge.js';
|
||||
import { keepWarmOn } from './prompt-cache-keepwarm.js';
|
||||
import type { CliEntry } from './config/cli-registry/types.js';
|
||||
import { describeRootValueChanges, type RootValueChange } from './config/cli-registry/root-launch.js';
|
||||
import { serverRunsAsRoot } from './utils/server-uid.js';
|
||||
import {
|
||||
resolveStatusLineCliCommand,
|
||||
readPlanUsageTelemetryEnabled,
|
||||
@@ -277,19 +279,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 +316,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 +381,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 +398,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 +478,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 } : {}),
|
||||
@@ -1201,6 +1260,44 @@ export function decideIdleCompactionOptOut(o: {
|
||||
);
|
||||
}
|
||||
|
||||
/** What `serverRootSpawnOptions()` adds to a `buildSpawnCommand` call; empty for every launch that is not root. */
|
||||
export interface ServerRootSpawnOptions {
|
||||
runsAsServerRoot?: true;
|
||||
onRootValue?: (changes: RootValueChange[]) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The `buildSpawnCommand` options for a launch under a Codeman server that itself runs as
|
||||
* root (uid 0), which is common on a VPS and in an LXC container.
|
||||
*
|
||||
* A CLI started locally is the server's child and runs as root too, and Claude Code exits
|
||||
* on `--dangerously-skip-permissions` there, so its default launch was a dead pane. With
|
||||
* these options a param that declares a `rootValue` takes it (registry data, see
|
||||
* config/cli-registry/root-launch.ts), and the swap is logged once per launch.
|
||||
*
|
||||
* ⚠️ The ONE place the tmux launch path asks for the uid. `createSession` and `respawnPane`
|
||||
* both spread the result into `buildSpawnCommand`, and every local tmux launch (new
|
||||
* session, resume, dead-pane respawn, `restartCli()`, cron, quick-start, reboot restore) is
|
||||
* one of those two calls. The two launches with no tmux (direct-PTY fallback, one-shot) get
|
||||
* the same registry data in `buildPermissionArgs()` (session-cli-builder.ts).
|
||||
* ⚠️ `launchedElsewhere` (remote, Docker, adopted) returns nothing: that CLI runs under
|
||||
* another account, and the local command built for it is never used. Docker answers the
|
||||
* same refusal with `overlays.docker.rootCommand`, by the CONTAINER's uid.
|
||||
* ⚠️ Not root returns `{}`, so the command line stays byte-identical.
|
||||
*/
|
||||
export function serverRootSpawnOptions(o: {
|
||||
mode: SessionMode;
|
||||
sessionId: string;
|
||||
launchedElsewhere: boolean;
|
||||
}): ServerRootSpawnOptions {
|
||||
if (o.launchedElsewhere || !serverRunsAsRoot()) return {};
|
||||
const what = `${getCli(o.mode)?.label ?? o.mode} session ${o.sessionId.slice(0, 8)}`;
|
||||
return {
|
||||
runsAsServerRoot: true,
|
||||
onRootValue: (changes) => console.warn(`[TmuxManager] ${describeRootValueChanges(what, changes)}`),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildSpawnCommand(options: {
|
||||
mode: SessionMode;
|
||||
sessionId: string;
|
||||
@@ -1235,6 +1332,14 @@ export function buildSpawnCommand(options: {
|
||||
* gate measuring the RIGHT binary, the local one.
|
||||
*/
|
||||
claudeCliVersion?: string | null;
|
||||
/**
|
||||
* The command will run as a child of a server process whose uid is 0, so a param declaring
|
||||
* a `rootValue` takes it. Only ever supplied through `serverRootSpawnOptions()`, which the
|
||||
* two local launch sites spread in; absent, the command is byte-identical.
|
||||
*/
|
||||
runsAsServerRoot?: boolean;
|
||||
/** Told which params took their `rootValue` (see `serverRootSpawnOptions`). */
|
||||
onRootValue?: (changes: RootValueChange[]) => void;
|
||||
}): string {
|
||||
// Every CLI's command shape is registry DATA, rendered by the argv engine — see
|
||||
// config/cli-registry/argv.ts for why config can never contain shell text. A `shell`-kind
|
||||
@@ -2674,6 +2779,8 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
statusLineCommand,
|
||||
idleCompactionOff,
|
||||
sessionName: cliName,
|
||||
// A local launch under a server that runs as root: see serverRootSpawnOptions.
|
||||
...serverRootSpawnOptions({ mode, sessionId, launchedElsewhere: !!(remote || docker || adopt) }),
|
||||
});
|
||||
|
||||
const config = niceConfig || DEFAULT_NICE_CONFIG;
|
||||
@@ -2868,24 +2975,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 };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2996,6 +3105,8 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
statusLineCommand,
|
||||
idleCompactionOff,
|
||||
sessionName: cliName,
|
||||
// Same as createSession: a respawn under a root server must not bring the refused value back.
|
||||
...serverRootSpawnOptions({ mode, sessionId, launchedElsewhere: !!(remote || docker || adopt) }),
|
||||
});
|
||||
const config = niceConfig || DEFAULT_NICE_CONFIG;
|
||||
const cmd = wrapWithNice(baseCmd, config);
|
||||
@@ -3148,6 +3259,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 +3318,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 +3352,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 +3528,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 +3597,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 +3660,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 +3673,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 +3711,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 +3737,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 +4060,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 +4079,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 });
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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)?$/;
|
||||
|
||||
/**
|
||||
@@ -1172,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.
|
||||
*
|
||||
|
||||
@@ -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 */
|
||||
|
||||
@@ -50,6 +50,12 @@ export interface UsersFile {
|
||||
export interface AuthUser {
|
||||
username: string;
|
||||
role: UserRole;
|
||||
/**
|
||||
* True when a trusted reverse proxy vouched for this request (see
|
||||
* src/config/trusted-proxy.ts), so no Codeman password was involved. Absent for
|
||||
* cookie, Basic and QR sign-ins.
|
||||
*/
|
||||
viaTrustedProxy?: boolean;
|
||||
}
|
||||
|
||||
/** Admin-facing projection of a user: never carries the password hash. */
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
export { BufferAccumulator } from './buffer-accumulator.js';
|
||||
export { CleanupManager } from './cleanup-manager.js';
|
||||
export { Debouncer, KeyedDebouncer } from './debouncer.js';
|
||||
export { KeyedThrottle } from './keyed-throttle.js';
|
||||
export { startEventLoopMonitor } from './event-loop-monitor.js';
|
||||
export type { EventLoopMonitorHandle } from './event-loop-monitor.js';
|
||||
export { StaleExpirationMap } from './stale-expiration-map.js';
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* @fileoverview Per-key throttle: at most one send per key per interval, and the last call in a
|
||||
* burst is never lost.
|
||||
*
|
||||
* The first call for a key in a quiet period sends at once. A call inside the interval after a
|
||||
* send schedules one trailing send at the interval's end, and later calls collapse into it while
|
||||
* it is pending. The trailing send runs the newest `send` it was given. Timers are unref'd, so a
|
||||
* pending send never holds the process open. Its method names match KeyedDebouncer's
|
||||
* (debouncer.ts): `cancelKey()` forgets one key, and `dispose()` forgets them all, which is how
|
||||
* it integrates with CleanupManager.
|
||||
*
|
||||
* @module utils/keyed-throttle
|
||||
*/
|
||||
|
||||
interface ThrottleState {
|
||||
lastAt: number;
|
||||
timer: NodeJS.Timeout | null;
|
||||
send: () => void;
|
||||
}
|
||||
|
||||
export class KeyedThrottle<K = string> {
|
||||
private readonly state = new Map<K, ThrottleState>();
|
||||
|
||||
constructor(private readonly intervalMs: number) {}
|
||||
|
||||
/** Send for `key` now if its interval has passed, else once at the interval's end. */
|
||||
fire(key: K, send: () => void): void {
|
||||
let entry = this.state.get(key);
|
||||
if (!entry) {
|
||||
entry = { lastAt: 0, timer: null, send };
|
||||
this.state.set(key, entry);
|
||||
}
|
||||
entry.send = send;
|
||||
// A trailing send is already scheduled, and it covers this call.
|
||||
if (entry.timer) return;
|
||||
const wait = entry.lastAt + this.intervalMs - Date.now();
|
||||
if (wait <= 0) {
|
||||
entry.lastAt = Date.now();
|
||||
send();
|
||||
return;
|
||||
}
|
||||
const scheduled = entry;
|
||||
scheduled.timer = setTimeout(() => {
|
||||
scheduled.timer = null;
|
||||
scheduled.lastAt = Date.now();
|
||||
scheduled.send();
|
||||
}, wait);
|
||||
scheduled.timer.unref?.();
|
||||
}
|
||||
|
||||
/** Forget `key`, dropping its pending trailing send. */
|
||||
cancelKey(key: K): void {
|
||||
const entry = this.state.get(key);
|
||||
if (entry?.timer) clearTimeout(entry.timer);
|
||||
this.state.delete(key);
|
||||
}
|
||||
|
||||
/** Forget every key, dropping every pending send. The CleanupManager integration point. */
|
||||
dispose(): void {
|
||||
for (const entry of this.state.values()) {
|
||||
if (entry.timer) clearTimeout(entry.timer);
|
||||
}
|
||||
this.state.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* @fileoverview Whether the Codeman server process itself runs as root (uid 0).
|
||||
*
|
||||
* A CLI the server starts LOCALLY is its child, so it runs under the same uid, and some
|
||||
* CLIs refuse part of their own command line there: Claude Code exits on
|
||||
* `--dangerously-skip-permissions` under root ("cannot be used with root/sudo privileges").
|
||||
* A server installed and started as root is common on a VPS and in an LXC container, and
|
||||
* there every such session showed a dead pane.
|
||||
*
|
||||
* The answer is read at CALL time, never cached in a module-level const: every local launch
|
||||
* asks again, and a test stands in for the uid through `stubServerUidForTest()`.
|
||||
*
|
||||
* Test hermeticity: under vitest the real uid is never consulted (`false` unless a test
|
||||
* stubbed one), so the suite gives the same command lines when it is run as root, in a
|
||||
* container for instance.
|
||||
*
|
||||
* @module utils/server-uid
|
||||
*/
|
||||
|
||||
/** A test's stand-in for the process uid: `null` = no stub, `undefined` = a platform with no uid. */
|
||||
let stubbedUid: number | undefined | null = null;
|
||||
|
||||
/**
|
||||
* True when this process runs as uid 0. False on a platform with no uid (`process.getuid`
|
||||
* is absent on Windows).
|
||||
*/
|
||||
export function serverRunsAsRoot(): boolean {
|
||||
if (stubbedUid !== null) return stubbedUid === 0;
|
||||
if (process.env.VITEST) return false;
|
||||
return typeof process.getuid === 'function' && process.getuid() === 0;
|
||||
}
|
||||
|
||||
/** Test seam: answer as if the server ran under `uid`; `null` puts the hermetic default back. */
|
||||
export function stubServerUidForTest(uid: number | undefined | null): void {
|
||||
stubbedUid = uid;
|
||||
}
|
||||
+14
-6
@@ -10,10 +10,12 @@
|
||||
|
||||
**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
|
||||
|
||||
**Chat view** (`chat-view.js`, per-device `chatViewDefault`, default OFF, never on phones; design in [`docs/chat-view-plan.md`](../../docs/chat-view-plan.md)): a local or Docker Claude session in the main view can show its conversation, read from the transcript, as text; to type, the user switches to the Terminal view. `chatViewEligible()` takes the modes whose CLI declares `transcript: 'claude-jsonl'` (`window.__codemanChatViewModes`, never a mode id) and refuses a remote or an adopted session and a phone. The per-device `showChatViewSwitch` (default OFF, owner decision for 1.52.1: only an explicit `true` shows the switch, read as `=== true`, so nobody sees it without choosing it) shows or hides only the Chat / Terminal switch; the view and Alt+Shift+C work either way. ⚠️ The terminal stays mounted, attached and sized under the chat layer, so switching views never resizes the PTY. Focus that lands on the hidden terminal moves to the conversation, and `body.chat-view-showing` hides the keyboard accessory bar and, on touch devices, the CJK input field while Chat shows, because both write into the pane. While the tile grid owns the terminal, the chat view is hidden whatever the session's choice (`_tilesOwnTerminal()`, synced from tile-grid.js). A pending `permission_prompt` or `elicitation_dialog` hook shows a notice whose button switches to the terminal. Codeman's keep-alive turn shows no status line. i18n.js skips the `data-i18n-skip` conversation, so the strings drawn there go through `_chatViewT()`. Tests: `test/chat-view.test.ts`, `test/chat-view-i18n.test.ts`.
|
||||
|
||||
**Terminal touch gestures: link taps and text selection**: on touch devices xterm's linkifier and SelectionService never see the gesture, so both are driven explicitly (terminal-ui.js). ⚠️ A tap activates the link under it through the SAME provider as the hover linkifier (`_terminalLinkAtPoint`), synchronously inside `touchend` (keeps the user gesture `window.open` needs) and BEFORE any mouse report; the caret's logical line (`_tapIsOnCaretLine`) and TUI-owned rows (`_isActionableMobileTerminalTap`) keep their meaning. ⚠️ Gate on the caret line, never on tap intent (a shell calls every tap `'input'`). ⚠️ Long-press selects via xterm's public `select()`; keep the three guards: suppress the compat mouse pair after `touchend`, the bounded focus guard + `contextmenu` suppression for the platform long-press, and no closing `terminal.focus()` on phones. ⚠️ A sideways drag belongs to the session swipe (`SwipeHandler`, mobile-handlers.js): the touch handler locks the dominant axis on the first travel past the tap slop (`panAxis`: `y` scrolls, `x` pans a terminal wider than its box, `swipe` otherwise) and publishes it as `app._terminalGestureAxis`; a `swipe` drag neither scrolls nor ends as a tap on the session being left until it passes the swipe's own vertical drift limit (`SwipeHandler.maxVerticalDrift`), where it is handed back to the scroll as `y` (a scroll that opens on a thumb arc), and the swipe stands aside for `x`/`y`, a touch selection, a second finger and surfaces with controls of their own (`IGNORE_SELECTOR`; the phone overview and welcome screen are deliberately not listed). A swipe is 80 px within 500 ms with at most 50 px of vertical drift at any point; a touch starting outside the terminal (the home screen) resets the published axis, and a lift the terminal consumed (`defaultPrevented`, its selection gesture) is never a swipe (`test/session-swipe-gesture.test.ts`). Tests: `test/terminal-touch-tap.test.ts`. → [architecture-invariants#terminal-touch-gestures-link-taps-and-text-selection](../../docs/architecture-invariants.md#terminal-touch-gestures-link-taps-and-text-selection)
|
||||
|
||||
**Auto Copy (copy-on-select)** (`autoCopySelection`, per-device, default OFF): a finished terminal selection lands on the clipboard with no keystroke. ⚠️ Copy at the END of a gesture, never in `onSelectionChange` (per-cell); it only arms `_autoCopyPending` and a document-level `mouseup` flushes. ⚠️ The flush must be SYNCHRONOUS in the handler (both clipboard paths need user activation); never defer it to a timer. ⚠️ Touch needs its own calls from `_endTouchSelectionGesture()`/`_selectTouchSelectionLine()` (no mouseup arrives). ⚠️ Unlike `copyTerminalSelection()`, never clear the selection or focus the terminal; restore prior focus. Guards are pure in `decideAutoCopy()` (constants.js, 1M-char cap, refused not truncated). Tests: `test/terminal-auto-copy.test.ts`. → [architecture-invariants#auto-copy-copy-on-select](../../docs/architecture-invariants.md#auto-copy-copy-on-select)
|
||||
@@ -32,13 +34,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 +60,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`, `cjkInputHoldUntilEnter`, 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**, among others, `skin`, `showFileViewerButton`, `showCronButton`, `webglRendererEnabled`, `localEchoEnabled`, `keyboardHoldsRows`, `cjkInputEnabled`, `cjkInputHoldUntilEnter`, `extendedKeyboardBar`, `historyReloadAction`, `chatViewDefault`, or `showChatViewSwitch`, so sending one of those is a validation error. Others (`showResponseViewer`, `showPlanUsageLimits`, `language`, and many `show*` keys) ARE in the schema and do persist server-side; they are per-device by client policy only. ⚠️ Adding a new per-device setting means deciding **both** questions: membership in `displayKeys`, and presence in the schema.
|
||||
|
||||
**Settings surface** (`#appSettingsModal` + `#sessionOptionsModal` + `#createCaseModal`): one `set-*` language shared through a single `:is(...)` id scope in styles.css. App Settings' rail is a table of contents over ONE scrolling document (`switchSettingsTab` scrolls); Session Options and Add Case really switch (`switchOptionsTab` / `switchCaseModalTab`), and their larger per-modal size blocks are the design, not drift. ⚠️ **The load/save contract is `getElementById` by id**: renaming or dropping a control id silently stops it loading or saving. ⚠️ The Session Options "Session" entry still keys off `context` (label-only rename). ⚠️ Add Case keeps its legacy `.form-row` markup via an adapter; every `<details>` there needs `.set-adv-chev` plus both marker suppressions. ⚠️ Model cards and the effort segment are views over hidden `<select>`s, which stay the source of truth. ⚠️ `.modal-tabs*` classes are retired; `admin-ui.js` needs `.set-rail-items` + `.set-doc` to survive any restructure. Guard: `test/app-settings-structure.test.ts`. → [architecture-invariants#settings-surface-app-settings-session-options-add-case](../../docs/architecture-invariants.md#settings-surface-app-settings-session-options-add-case)
|
||||
|
||||
@@ -76,7 +82,7 @@ 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)
|
||||
|
||||
@@ -86,7 +92,7 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
||||
|
||||
**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. 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) and then Enter.
|
||||
**`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.
|
||||
|
||||
@@ -94,6 +100,8 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
||||
|
||||
**SSE staleness watchdog** (`computeSseStale()` in constants.js, `_checkSseStale()` + a 5s interval in app.js): an `EventSource` can stop delivering without erroring, so the client forces a reconnect when nothing arrives. ⚠️ The server keepalive must stay the named `sse:heartbeat` event (`cleanupDeadClients()`, sse-stream-manager.ts), never an SSE comment, which `EventSource` cannot observe; its no-op client listener must stay registered. ⚠️ Judge staleness only while `connected` and online (the loop breaker). ⚠️ The liveness stamp lives inside `addListener`. ⚠️ Clear the interval only at the top of `connectSSE()`, or intervals stack. ⚠️ The watchdog cannot see an attempt that never OPENS (no response headers: no `open`, no `error`, never `connected`), so each attempt is bounded by `SSE_CONNECT_TIMEOUT_MS` (15s, `CodemanSseStale.CONNECT_TIMEOUT_MS`) and then retried through `_handleSseConnectionFailure()`, the same backoff `onerror` uses. Its timer is cleared at the top of `connectSSE()` BEFORE the offline early return, on `open`, and in `_handleSseConnectionFailure()`; the timer and the handler both ignore an `EventSource` that has been replaced. The window `offline` handler leaves it running on purpose (`navigator.onLine` can report offline on a working network). Tests: `test/sse-connect-timeout.test.ts`. → [architecture-invariants#sse-staleness-watchdog](../../docs/architecture-invariants.md#sse-staleness-watchdog)
|
||||
|
||||
**Z-index layers** (keep new overlays consistent with this stack): local echo overlay (7; with local echo on it also draws the iOS IME composition preview, as an underlined tail after its pending text via `setComposition`), iOS IME composition preview span when local echo is off (6 inside `.xterm-helpers`, whose own z-index 5 is its EFFECTIVE layer, so it sits UNDER the overlay and must never be used while the overlay shows text), terminal touch-selection bar (900, below floating agent windows), subagent windows + split picker menu + Tiles count menu (1000), mobile/tablet fixed header (1200), modals on ≤768px (1300, must beat the fixed header), log viewers (2000), connection-loss overlay (2500), image popups (3000), response viewer (5000, backdrop 4999), folder grid (5090, above the response viewer it opens from, below the file preview its tiles open), file-preview overlay (5100, must outrank the response viewer that launches it), toasts/path picker (10000+), custom-model center-status banner (10001; its `[hidden]` must re-assert `display: none` or `dismiss()` leaves an invisible click-blocker), custom-model swap-confirm/context-warning modals (10010). → [architecture-invariants#z-index-layers](../../docs/architecture-invariants.md#z-index-layers)
|
||||
**Codex file previews** (`codexFilePreviewsEnabled`, App Settings > Header buttons > Codex files, per-device display key, absent from `SettingsUpdateSchema`, default OFF; `_codexFilePreviewsEnabled()` in app.js is the ONE reader): a session whose CLI publishes `transcript: 'codex-rollout'` opens the files Codex links in the file preview. The served CLI catalog (`window.__codemanCliCatalog`, server.ts) carries `transcript` for that check (`_supportsCodexResponseFiles()`), never a CLI id, and `_syncCliLaunchCatalog()` keeps it across a Settings refresh. A click on an underlined label in the pane is resolved against the conversation (`last-response?context=full`, cached per session while idle until the next `lastSubmitAt`, `_codexResponseMessages()`) and opens only a single, unambiguous, previewable file, else it is forwarded to Codex as before. All of it is behind the setting (owner decision for 1.52.1: the in-pane click too, gated in `_handleDesktopTerminalClick()`), four things absent while it is off: that in-pane click (every click then goes on to Codex), the Response files header button (`toggleResponseViewer(true)`; marker `btn-response-files--hidden` for the setting, `hidden` for the capability, and `mobile.css` hides it on phones regardless, pinned by `test/mobile-header-buttons-policy.test.ts`), the Codex SIDEBAR file tabs (`codexSidebarFileRow()` in terminal-ui.js: with the setting on, `registerFilePathLinkProvider` drops its links on those rows, which are Codex chrome, and a click there is taken by `_codexTerminalLinkLabel()`; off, the row keeps its ordinary links and its click reaches Codex), and the Dock control. ⚠️ Docking MOVES `#filePreviewOverlay` out of its home and after `.terminal-wrap` (`_setFilePreviewDocked()`), only when the wrap is a direct child of `.main` without `.tiles-active`/`.webview-active` and the window is 1180px or wider; otherwise the preview floats. It moves back on close, on Escape inside it, when a split opens (`openSplitPane()` undocks first, or `closeSplitPane()` would remove the overlay with the split container) and when the setting is switched off. Tests: `test/codex-file-previews-setting.test.ts` (off-state of all three), `test/response-viewer-file-links.test.ts`, `test/terminal-link-provider-target.test.ts`, `test/terminal-touch-tap.test.ts`, `test/file-preview-window.test.ts`.
|
||||
|
||||
**Z-index layers** (keep new overlays consistent with this stack): local echo overlay (7; with local echo on it also draws the iOS IME composition preview, as an underlined tail after its pending text via `setComposition`), iOS IME composition preview span when local echo is off (6 inside `.xterm-helpers`, whose own z-index 5 is its EFFECTIVE layer, so it sits UNDER the overlay and must never be used while the overlay shows text), chat view (20, covering the terminal inside `.terminal-wrap`) and its Chat / Terminal switch (21, above it), terminal touch-selection bar (900, below floating agent windows), subagent windows + split picker menu + Tiles count menu (1000), mobile/tablet fixed header (1200), modals on ≤768px (1300, must beat the fixed header), log viewers (2000), connection-loss overlay (2500), image popups (3000), response viewer (5000, backdrop 4999), folder grid (5090, above the response viewer it opens from, below the file preview its tiles open), file-preview overlay (5100, must outrank the response viewer that launches it; DOCKED it is `z-index: auto`, page content beside the terminal, so it sits under every modal and the response viewer, pinned in `test/file-preview-window.test.ts`), toasts/path picker (10000+), custom-model center-status banner (10001; its `[hidden]` must re-assert `display: none` or `dismiss()` leaves an invisible click-blocker), custom-model swap-confirm/context-warning modals (10010). → [architecture-invariants#z-index-layers](../../docs/architecture-invariants.md#z-index-layers)
|
||||
|
||||
**Keyboard shortcuts**: Escape (close), Ctrl+? (shortcut overlay), Ctrl/Cmd/Alt+K (session palette), Ctrl+Tab (next), Alt+[/] (prev/next tab), Alt+1-9 (switch tab), Ctrl+Shift+{/} (move tab left/right), Shift+Enter or Ctrl+Enter (newline), Ctrl+C (copy selection, else interrupt) / Ctrl+Shift+C (copy, never interrupts), Ctrl+L (clear), Ctrl+Shift+R (restore size), Ctrl+Shift+V (voice input), Ctrl/Cmd +/- (font), Shift+Wheel (local scrollback when mouse passthrough is active), Shift+drag (start a selection in a stripped-DECSET pane, where xterm's own Shift branch is unreachable and a Shift+drag used to select nothing; `_installShiftDragSelection`), right-click (copy the selection, the mintty/PuTTY convention, since xterm paints into a canvas and the native menu has no Copy for it; with nothing selected the native menu is left alone). Rebindable via the registry. ⚠️ **Ctrl+W is deliberately NOT bound** (owner decision): it is delete-word in every shell and agent CLI, and as Close Session it killed sessions with no confirm; `close-session` keeps `bindings: []` and stays bindable (`test/ctrl-w-never-closes.test.ts`).
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* @fileoverview A Claude pane's report of its live conversation: the conversation id and the
|
||||
* transcript path that Claude Code hands to every hook and to the statusline command.
|
||||
*
|
||||
* Two routes receive the report. `POST /api/hook-event` gets it from every hook Codeman
|
||||
* installs. `POST /api/status-telemetry` gets it from the statusline exporter, and Claude Code
|
||||
* runs the statusline command again about a second after a `/clear` (measured on 2.1.332), so
|
||||
* the server learns of the new conversation before the next prompt without a hook of its own.
|
||||
*
|
||||
* Both reports are first-hand: they come from the CLI process in the pane, addressed by the
|
||||
* pane's own `$CODEMAN_SESSION_ID`, so no cwd or timestamp guess is involved.
|
||||
*
|
||||
* @dependency web/schemas.ts (isValidWorkingDir), docker-hosts.ts (the Docker resume seed and the
|
||||
* container's Claude folder)
|
||||
*/
|
||||
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { CONTAINER_CLAUDE_DIR, persistDockerCaseClaudeSessionId } from '../docker-hosts.js';
|
||||
import { getDataDir } from '../config/instance.js';
|
||||
import { isValidWorkingDir } from './schemas.js';
|
||||
import type { Session } from '../session.js';
|
||||
import type { ConfigPort, SessionPort } from './ports/index.js';
|
||||
|
||||
/**
|
||||
* The host path of a transcript a pane reported. Claude in a Docker case runs with
|
||||
* `HOME=/home/agent`, so it reports `/home/agent/.claude/projects/...`, a path that does not exist
|
||||
* on the host. The case mounts the host's `~/.claude/projects` at that folder
|
||||
* (resolveDockerClaudeArtifacts in docker-hosts.ts), so the same file is under the host's folder.
|
||||
* Every other path is returned as reported.
|
||||
*/
|
||||
export function hostTranscriptPath(session: Pick<Session, 'docker'> | undefined, reported: string): string {
|
||||
if (!session?.docker) return reported;
|
||||
const containerProjects = `${CONTAINER_CLAUDE_DIR}/projects/`;
|
||||
if (!reported.startsWith(containerProjects)) return reported;
|
||||
const rest = reported.slice(containerProjects.length);
|
||||
// A `..` segment would leave the projects folder; such a path is left as reported.
|
||||
if (rest.split('/').some((part) => part === '..' || part === '')) return reported;
|
||||
return join(homedir(), '.claude', 'projects', rest);
|
||||
}
|
||||
|
||||
/** The two fields of a hook or statusline payload that name the conversation. */
|
||||
export interface ClaudeConversationReport {
|
||||
session_id?: unknown;
|
||||
transcript_path?: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* How long after a session's last accepted move a statusline report may not move it back to an
|
||||
* earlier conversation. The exporter's POST is bounded by `curl --max-time 5` (hooks-config.ts),
|
||||
* so a report sent before the newest move lands within this window.
|
||||
*/
|
||||
const STATUSLINE_REORDER_WINDOW_MS = 10_000;
|
||||
|
||||
/**
|
||||
* Sessions whose conversation moved since their last `prompt_submitted` hook. The statusline can
|
||||
* adopt a `/clear` successor before the next prompt's hook arrives, so that hook would see no
|
||||
* change in its own report; it asks {@link takeConversationMove} instead.
|
||||
*/
|
||||
const conversationMoves = new WeakSet<Session>();
|
||||
|
||||
/** When each session last moved to another conversation, for {@link STATUSLINE_REORDER_WINDOW_MS}. */
|
||||
const lastConversationMoveAt = new WeakMap<Session, number>();
|
||||
|
||||
/**
|
||||
* Report whether the session's conversation moved since the last call for it, and forget the move.
|
||||
* The hook route calls it for each `prompt_submitted`, to record a `/clear` successor's first prompt.
|
||||
*/
|
||||
export function takeConversationMove(session: Session | undefined): boolean {
|
||||
return !!session && conversationMoves.delete(session);
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow the conversation a Claude pane reports: point the session's transcript watcher at the
|
||||
* reported file, adopt the reported conversation id, and persist the session when the id moved.
|
||||
* Returns true when the conversation changed.
|
||||
*
|
||||
* `forwardOnly` refuses a report that names an earlier conversation of the session's chain while
|
||||
* the session's last move is less than {@link STATUSLINE_REORDER_WINDOW_MS} old.
|
||||
*/
|
||||
export function noteClaudeConversationReport(
|
||||
ctx: SessionPort & Pick<ConfigPort, 'startTranscriptWatcher'>,
|
||||
sessionId: string,
|
||||
report: ClaudeConversationReport | null | undefined,
|
||||
options: { forwardOnly?: boolean } = {}
|
||||
): boolean {
|
||||
if (!report) return false;
|
||||
|
||||
// The statusline exporter can post out of order, because it backgrounds the POST when it wraps
|
||||
// the user's own statusline. So a statusline report moves the session back to an earlier
|
||||
// conversation, as a `/resume` makes, only when the last move is more than the window old.
|
||||
// Inside the window the move waits for the next hook or the next statusline report after it.
|
||||
if (options.forwardOnly && typeof report.session_id === 'string' && report.session_id) {
|
||||
const reported = ctx.sessions.get(sessionId);
|
||||
const chain = reported?.claudeSessionChain;
|
||||
if (
|
||||
reported &&
|
||||
chain &&
|
||||
chain.includes(report.session_id) &&
|
||||
chain[chain.length - 1] !== report.session_id &&
|
||||
Date.now() - (lastConversationMoveAt.get(reported) ?? 0) < STATUSLINE_REORDER_WINDOW_MS
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Watch the reported transcript when its path is safe. The watcher ignores a path it already watches.
|
||||
if (typeof report.transcript_path === 'string') {
|
||||
const transcriptPath = hostTranscriptPath(ctx.sessions.get(sessionId), report.transcript_path);
|
||||
if (isValidWorkingDir(transcriptPath)) ctx.startTranscriptWatcher(sessionId, transcriptPath);
|
||||
}
|
||||
|
||||
// Sync Claude's current conversation id. Interactive PTY mode never emits `session_id` on
|
||||
// stdout, so these reports are the only reliable way to learn that the user ran `/clear`,
|
||||
// which starts a new conversation file.
|
||||
if (typeof report.session_id !== 'string' || !report.session_id) return false;
|
||||
const session = ctx.sessions.get(sessionId);
|
||||
if (!session) return false;
|
||||
const prevClaudeSessionId = session.claudeSessionId;
|
||||
const prevChainLength = session.claudeSessionChain.length;
|
||||
// FIRST-HAND, so the response viewer can stop guessing (see resolveActiveClaudeSessionIdFromHistory).
|
||||
session.adoptClaudeSessionId(report.session_id, { firstHand: true });
|
||||
if (session.claudeSessionId === prevClaudeSessionId && session.claudeSessionChain.length === prevChainLength) {
|
||||
return false;
|
||||
}
|
||||
// Persist when the conversation actually moved: `/clear` emits no completion event, so without
|
||||
// this the successor id is lost on restart and recovery falls back to the launch conversation.
|
||||
ctx.persistSessionState(session);
|
||||
conversationMoves.add(session);
|
||||
lastConversationMoveAt.set(session, Date.now());
|
||||
// Docker sessions: keep the case's resume seed following the LIVE conversation, so a container
|
||||
// stop or reboot relaunch resumes the right transcript.
|
||||
if (session.docker && session.claudeSessionId && session.claudeSessionId !== prevClaudeSessionId) {
|
||||
void persistDockerCaseClaudeSessionId(getDataDir(), session.docker.containerName, session.claudeSessionId).catch(
|
||||
() => {}
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
/**
|
||||
* @fileoverview A Claude transcript read into the Response Viewer's messages, incrementally.
|
||||
*
|
||||
* `GET /api/sessions/:id/last-response` answers the Response Viewer, the Discord bridge and the
|
||||
* chat view from a Claude session's transcript, an append-only JSONL file that grows past 200 MB
|
||||
* on long sessions. The chat view asks again on every `transcript:update`, up to once per 750 ms
|
||||
* per session while a turn runs. A read that parsed the whole file each time held the event loop
|
||||
* for 375 ms on a 66 MB transcript and 1.5 s on a 219 MB one, which froze every terminal and SSE
|
||||
* stream on the server.
|
||||
*
|
||||
* {@link ClaudeTranscriptReader} keeps the parser's state and the byte offset it reached for each
|
||||
* transcript path, in a small LRU. A read parses only the bytes appended since the last one, in
|
||||
* chunks with an await between them, so even the first read of a large file never holds the event
|
||||
* loop for long. It starts again from byte 0 when the file shrank, was replaced by another file,
|
||||
* or no longer holds the bytes it ended on. Reads of one path that overlap share one pass.
|
||||
*
|
||||
* The parser consumes whole lines only. A last line without its newline is parsed on a copy of
|
||||
* the state for that one answer, and parsed for good once its newline arrives, so the answer
|
||||
* always equals a parse of the whole file.
|
||||
*
|
||||
* @dependency prompt-cache-keepwarm.ts (KEEP_WARM_NUDGE), utils/lru-map.ts
|
||||
*/
|
||||
|
||||
import fs from 'node:fs/promises';
|
||||
import { KEEP_WARM_NUDGE } from '../prompt-cache-keepwarm.js';
|
||||
import { LRUMap } from '../utils/lru-map.js';
|
||||
|
||||
export interface ClaudeResponseMessage {
|
||||
kind: 'prompt' | 'response';
|
||||
label: 'Prompt' | 'Response';
|
||||
role: 'user' | 'assistant';
|
||||
text: string;
|
||||
timestamp?: string;
|
||||
turn: number;
|
||||
queued?: boolean;
|
||||
/**
|
||||
* Part of a keep-warm turn (prompt-cache-keepwarm.ts): Codeman sent the prompt, not the user,
|
||||
* and the reply is its "ok". The chat view leaves such turns out, as Read My Mind does.
|
||||
*/
|
||||
keepAlive?: boolean;
|
||||
}
|
||||
|
||||
/** The last assistant text of a transcript and every message, as the route answers them. */
|
||||
export interface ClaudeResponseTranscript {
|
||||
text: string;
|
||||
timestamp: string;
|
||||
messages: ClaudeResponseMessage[];
|
||||
}
|
||||
|
||||
interface ClaudeTranscriptEntry {
|
||||
type?: string;
|
||||
timestamp?: string;
|
||||
isMeta?: boolean;
|
||||
isSidechain?: boolean;
|
||||
isCompactSummary?: boolean;
|
||||
message?: { content?: unknown };
|
||||
// A prompt typed while Claude is working is absorbed mid-turn and recorded
|
||||
// ONLY here — the CLI never re-emits it as a `user` row. Every field stays
|
||||
// optional and unvalidated: `queued_command` is not a documented CLI
|
||||
// contract, so a missing/renamed field must mean "skip", which is also what
|
||||
// the CLI's own non-human queue entries (commandMode 'task-notification',
|
||||
// no `origin` key) require. Shape observed on Claude Code 2.1.220-2.1.251.
|
||||
attachment?: {
|
||||
type?: string;
|
||||
prompt?: string;
|
||||
commandMode?: string;
|
||||
timestamp?: string;
|
||||
origin?: { kind?: string };
|
||||
};
|
||||
}
|
||||
|
||||
function extractClaudeText(content: unknown, separator: string): string {
|
||||
if (typeof content === 'string') return content;
|
||||
if (!Array.isArray(content)) return '';
|
||||
return content
|
||||
.filter(
|
||||
(block): block is { type: string; text: string } =>
|
||||
!!block &&
|
||||
typeof block === 'object' &&
|
||||
(block as { type?: string }).type === 'text' &&
|
||||
typeof (block as { text?: string }).text === 'string'
|
||||
)
|
||||
.map((block) => block.text)
|
||||
.join(separator);
|
||||
}
|
||||
|
||||
function isClaudeSyntheticUserMessage(entry: ClaudeTranscriptEntry, text: string): boolean {
|
||||
if (entry.isMeta || entry.isCompactSummary) return true;
|
||||
return /^(?:<local-command|<command-name>|<task-notification>|<system-reminder>|<teammate-message\b|Another Claude session sent a message:|Base directory for this skill:)/i.test(
|
||||
text
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Claude writes an append-only event log: tool results arrive as user rows,
|
||||
* thinking/tool_use rows carry no text, and a prompt typed while the agent is
|
||||
* working is only ever recorded as an `attachment/queued_command` row. But one
|
||||
* assistant row IS one whole model message: measured across ~/.claude/projects
|
||||
* (CLI 2.1.220-2.1.251) no assistant row carries more than one content block
|
||||
* and no message id carries more than one text block, so there is nothing to
|
||||
* reassemble. Emit one card per row and group them with `turn` instead of
|
||||
* concatenating a human turn's replies into a single card (#169), which fused
|
||||
* up to 74 distinct model messages into one card. Splitting is safe for
|
||||
* markdown: no adjacent pair of assistant text rows in the corpus continues a
|
||||
* table, a list, or an open code fence.
|
||||
*
|
||||
* The state is the parse so far, fed one line at a time, so a reader can stop at the end of the
|
||||
* file and go on from there when it grows.
|
||||
*/
|
||||
export class ClaudeResponseParser {
|
||||
private lastText = '';
|
||||
private lastTimestamp = '';
|
||||
private messages: ClaudeResponseMessage[] = [];
|
||||
// #169's replay guards, kept: they now SKIP a duplicated row instead of
|
||||
// concatenating it into the previous card.
|
||||
private currentUserFragments = new Set<string>();
|
||||
private currentAssistantFragments = new Set<string>();
|
||||
// Turn 0 is reserved for anything emitted before the first human prompt.
|
||||
private turn = 0;
|
||||
// Whether the current turn opened with Codeman's keep-warm nudge.
|
||||
private keepAliveTurn = false;
|
||||
|
||||
/** A parser in the same state, for parsing a line that may not be finished yet. */
|
||||
clone(): ClaudeResponseParser {
|
||||
const copy = new ClaudeResponseParser();
|
||||
copy.lastText = this.lastText;
|
||||
copy.lastTimestamp = this.lastTimestamp;
|
||||
copy.messages = this.messages.slice();
|
||||
copy.currentUserFragments = new Set(this.currentUserFragments);
|
||||
copy.currentAssistantFragments = new Set(this.currentAssistantFragments);
|
||||
copy.turn = this.turn;
|
||||
copy.keepAliveTurn = this.keepAliveTurn;
|
||||
return copy;
|
||||
}
|
||||
|
||||
/** The parse so far. The messages array is a copy, so a later line never changes an answer. */
|
||||
result(): ClaudeResponseTranscript {
|
||||
return { text: this.lastText, timestamp: this.lastTimestamp, messages: this.messages.slice() };
|
||||
}
|
||||
|
||||
/** Feed text holding whole lines separated by `\n`. */
|
||||
feedLines(text: string): void {
|
||||
for (const line of text.split('\n')) this.feedLine(line);
|
||||
}
|
||||
|
||||
private pushUserMessage(text: string, timestamp: string | undefined, queued: boolean): void {
|
||||
// A run of consecutive human inputs (a mid-turn queued burst) is ONE turn,
|
||||
// so the viewer renders it under one badge instead of one badge per line.
|
||||
// The keep-warm nudge never joins an earlier user run: the turn before it
|
||||
// may have ended without assistant text (an interrupt before Claude wrote
|
||||
// anything, or a turn of tool calls only), and its reply belongs to the
|
||||
// keep-alive turn, not to the user's prompt.
|
||||
const isNudge = text === KEEP_WARM_NUDGE;
|
||||
if (isNudge || this.messages.at(-1)?.role !== 'user') {
|
||||
this.turn += 1;
|
||||
this.keepAliveTurn = isNudge;
|
||||
} else if (!isNudge) {
|
||||
// A prompt the user queued during the keep-warm turn makes the turn theirs.
|
||||
this.keepAliveTurn = false;
|
||||
}
|
||||
const message: ClaudeResponseMessage = {
|
||||
kind: 'prompt',
|
||||
label: 'Prompt',
|
||||
role: 'user',
|
||||
text,
|
||||
timestamp,
|
||||
turn: this.turn,
|
||||
};
|
||||
if (queued) message.queued = true;
|
||||
if (isNudge) message.keepAlive = true;
|
||||
this.messages.push(message);
|
||||
this.currentUserFragments.add(text);
|
||||
this.currentAssistantFragments.clear();
|
||||
}
|
||||
|
||||
feedLine(line: string): void {
|
||||
if (!line) return;
|
||||
let entry: ClaudeTranscriptEntry;
|
||||
try {
|
||||
entry = JSON.parse(line) as ClaudeTranscriptEntry;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
// Sidechains belong to agents/forks, not the main conversation. Meta user
|
||||
// rows include repeated image dimensions and other UI-generated context.
|
||||
if (entry.isSidechain) return;
|
||||
|
||||
// A prompt typed while Claude is working is absorbed mid-turn and lives
|
||||
// ONLY in an attachment row, so it was lost outright. `origin.kind` and
|
||||
// `commandMode` separate the human's queue entries from the CLI's own:
|
||||
// measured over 57 real transcripts on 2026-09-01, 322 queued_command rows
|
||||
// split 163 `prompt`/`human` and 159 `task-notification`, and not one of
|
||||
// those 159 carries an `origin` key. The 163 human rows become 162 user
|
||||
// cards here — one is a verbatim repeat inside a still-unanswered user run
|
||||
// and is collapsed by the dedup guard below — out of 353 user cards total.
|
||||
if (entry.type === 'attachment') {
|
||||
const queued = entry.attachment;
|
||||
if (!queued || queued.type !== 'queued_command') return;
|
||||
if (queued.origin?.kind !== 'human' || queued.commandMode !== 'prompt') return;
|
||||
const text = typeof queued.prompt === 'string' ? queued.prompt.trim() : '';
|
||||
if (!text || isClaudeSyntheticUserMessage(entry, text)) return;
|
||||
if (this.currentUserFragments.has(text)) return;
|
||||
this.pushUserMessage(text, queued.timestamp || entry.timestamp, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (entry.type === 'user') {
|
||||
const text = extractClaudeText(entry.message?.content, '\n').trim();
|
||||
// A tool_result block has no text block and naturally drops out here.
|
||||
if (!text || isClaudeSyntheticUserMessage(entry, text)) return;
|
||||
// Claude replays the initial user row while restoring a transcript, and
|
||||
// a CLI that also wrote an absorbed prompt as a user row would double it.
|
||||
// Both collapse here. The same prompt sent again AFTER a reply is a
|
||||
// legitimate second turn, because that reply cleared the set.
|
||||
if (this.currentUserFragments.has(text)) return;
|
||||
this.pushUserMessage(text, entry.timestamp, false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (entry.type !== 'assistant') return;
|
||||
const text = extractClaudeText(entry.message?.content, '\n\n').trim();
|
||||
if (!text) return;
|
||||
this.lastText = text;
|
||||
this.lastTimestamp = entry.timestamp || '';
|
||||
|
||||
// Replayed snapshots repeat an identical text block inside one turn.
|
||||
if (this.currentAssistantFragments.has(text)) return;
|
||||
const response: ClaudeResponseMessage = {
|
||||
kind: 'response',
|
||||
label: 'Response',
|
||||
role: 'assistant',
|
||||
text,
|
||||
timestamp: entry.timestamp,
|
||||
turn: this.turn,
|
||||
};
|
||||
if (this.keepAliveTurn) response.keepAlive = true;
|
||||
this.messages.push(response);
|
||||
this.currentAssistantFragments.add(text);
|
||||
this.currentUserFragments.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/** Parse a whole transcript at once. */
|
||||
export function parseClaudeResponseTranscript(content: string): ClaudeResponseTranscript {
|
||||
const parser = new ClaudeResponseParser();
|
||||
parser.feedLines(content);
|
||||
return parser.result();
|
||||
}
|
||||
|
||||
/** How many bytes before the offset a reader compares, to notice a file rewritten in place. */
|
||||
const CHECK_BYTES = 64;
|
||||
|
||||
interface CachedTranscript {
|
||||
parser: ClaudeResponseParser | null;
|
||||
dev: number;
|
||||
ino: number;
|
||||
/** The byte just after the last newline the parser consumed. */
|
||||
offset: number;
|
||||
/** The bytes that ended at `offset` when the parser reached it. */
|
||||
check: Buffer;
|
||||
running: Promise<ClaudeResponseTranscript> | null;
|
||||
queued: Promise<ClaudeResponseTranscript> | null;
|
||||
}
|
||||
|
||||
export interface ClaudeTranscriptReaderOptions {
|
||||
/** How many transcripts keep their parse. */
|
||||
maxEntries?: number;
|
||||
/** How many bytes one read call takes, and so how much one synchronous parse step covers. */
|
||||
chunkBytes?: number;
|
||||
}
|
||||
|
||||
/** Reads Claude transcripts, parsing each file's new bytes only. See the file overview. */
|
||||
export class ClaudeTranscriptReader {
|
||||
private readonly cache: LRUMap<string, CachedTranscript>;
|
||||
private readonly chunkBytes: number;
|
||||
|
||||
constructor(options: ClaudeTranscriptReaderOptions = {}) {
|
||||
this.cache = new LRUMap({ maxSize: options.maxEntries ?? 16 });
|
||||
this.chunkBytes = options.chunkBytes ?? 1024 * 1024;
|
||||
}
|
||||
|
||||
/**
|
||||
* The transcript at `path`, parsed to its current end. Rejects when the file cannot be read.
|
||||
*
|
||||
* A read asked for while another runs waits for it and then parses what was appended meanwhile,
|
||||
* so it never answers from before its own request. Every read asked for during that wait
|
||||
* shares the one pass that follows.
|
||||
*/
|
||||
read(path: string): Promise<ClaudeResponseTranscript> {
|
||||
let entry = this.cache.get(path);
|
||||
if (!entry) {
|
||||
entry = { parser: null, dev: 0, ino: 0, offset: 0, check: Buffer.alloc(0), running: null, queued: null };
|
||||
this.cache.set(path, entry);
|
||||
}
|
||||
const cached = entry;
|
||||
if (cached.queued) return cached.queued;
|
||||
if (cached.running) {
|
||||
cached.queued = cached.running
|
||||
.catch(() => undefined)
|
||||
.then(() => {
|
||||
cached.queued = null;
|
||||
return this.start(path, cached);
|
||||
});
|
||||
return cached.queued;
|
||||
}
|
||||
return this.start(path, cached);
|
||||
}
|
||||
|
||||
private start(path: string, entry: CachedTranscript): Promise<ClaudeResponseTranscript> {
|
||||
entry.running = this.update(path, entry).finally(() => {
|
||||
entry.running = null;
|
||||
});
|
||||
return entry.running;
|
||||
}
|
||||
|
||||
private async update(path: string, entry: CachedTranscript): Promise<ClaudeResponseTranscript> {
|
||||
const handle = await fs.open(path, 'r');
|
||||
try {
|
||||
const stat = await handle.stat();
|
||||
if (!stat.isFile()) throw new Error(`not a file: ${path}`);
|
||||
|
||||
let reset = !entry.parser || stat.dev !== entry.dev || stat.ino !== entry.ino || stat.size < entry.offset;
|
||||
if (!reset && entry.check.length > 0) {
|
||||
const now = Buffer.alloc(entry.check.length);
|
||||
const { bytesRead } = await handle.read(now, 0, now.length, entry.offset - now.length);
|
||||
reset = bytesRead !== now.length || !now.equals(entry.check);
|
||||
}
|
||||
if (reset || !entry.parser) {
|
||||
entry.parser = new ClaudeResponseParser();
|
||||
entry.dev = stat.dev;
|
||||
entry.ino = stat.ino;
|
||||
entry.offset = 0;
|
||||
entry.check = Buffer.alloc(0);
|
||||
}
|
||||
const parser = entry.parser;
|
||||
|
||||
// Read to the size the stat saw; bytes written after it wait for the next read.
|
||||
let position = entry.offset;
|
||||
let carry = Buffer.alloc(0);
|
||||
while (position < stat.size) {
|
||||
const chunk = Buffer.allocUnsafe(Math.min(this.chunkBytes, stat.size - position));
|
||||
const { bytesRead } = await handle.read(chunk, 0, chunk.length, position);
|
||||
if (bytesRead === 0) break;
|
||||
position += bytesRead;
|
||||
const data =
|
||||
carry.length > 0 ? Buffer.concat([carry, chunk.subarray(0, bytesRead)]) : chunk.subarray(0, bytesRead);
|
||||
// A newline byte never occurs inside a multi-byte UTF-8 character, so cutting there is safe.
|
||||
const newline = data.lastIndexOf(0x0a);
|
||||
if (newline === -1) {
|
||||
carry = data;
|
||||
continue;
|
||||
}
|
||||
parser.feedLines(data.toString('utf8', 0, newline));
|
||||
entry.offset = position - (data.length - newline - 1);
|
||||
entry.check = Buffer.from(data.subarray(Math.max(0, newline + 1 - CHECK_BYTES), newline + 1));
|
||||
carry = Buffer.from(data.subarray(newline + 1));
|
||||
}
|
||||
|
||||
if (carry.length === 0) return parser.result();
|
||||
const unfinished = parser.clone();
|
||||
unfinished.feedLine(carry.toString('utf8'));
|
||||
return unfinished.result();
|
||||
} catch (err) {
|
||||
// A parse left part-way is not trusted: the next read starts from byte 0.
|
||||
entry.parser = null;
|
||||
throw err;
|
||||
} finally {
|
||||
await handle.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
+279
-17
@@ -10,6 +10,7 @@
|
||||
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
|
||||
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
||||
import { posix } from 'node:path';
|
||||
import { StaleExpirationMap } from '../../utils/index.js';
|
||||
import type { AuthSessionRecord } from '../ports/auth-port.js';
|
||||
import { isAllowedRequestHost, isAllowedRequestOrigin, type HostPolicy } from '../network-auth-policy.js';
|
||||
@@ -22,9 +23,25 @@ import {
|
||||
} from '../../config/auth-config.js';
|
||||
import { getHookSecret, HOOK_SECRET_HEADER } from '../../config/hook-secret.js';
|
||||
import { isMultiUserMode } from '../../config/multiuser.js';
|
||||
import { findUser, setPassword, touchLastLogin, verifyPassword } from '../../user-store.js';
|
||||
import {
|
||||
getTrustedProxyConfig,
|
||||
initTrustedProxySecret,
|
||||
resolveTrustedProxyUserHeader,
|
||||
takeTrustedProxyHeaders,
|
||||
type PresentedProxyHeaders,
|
||||
type TrustedProxyConfig,
|
||||
} from '../../config/trusted-proxy.js';
|
||||
import {
|
||||
findUser,
|
||||
isValidUsername,
|
||||
normalizeUsername,
|
||||
setPassword,
|
||||
touchLastLogin,
|
||||
verifyPassword,
|
||||
} from '../../user-store.js';
|
||||
import { webviewCapabilities } from '../../webview-capabilities.js';
|
||||
import { capabilityFromHtmlViewPath, htmlViewCapabilities } from '../../html-view-capabilities.js';
|
||||
import { capabilityFromHtmlViewPath, HTML_VIEW_PREFIX, htmlViewCapabilities } from '../../html-view-capabilities.js';
|
||||
import { WEBVIEW_PROXY_PREFIX } from '../../config/webview-limits.js';
|
||||
import {
|
||||
capabilityFromProxyPath,
|
||||
capabilityFromReferer,
|
||||
@@ -56,6 +73,8 @@ interface AuthState {
|
||||
userFailures: StaleExpirationMap<string, number> | null;
|
||||
/** Per-(username, client IP) Basic-auth failure bucket (multi-user only). */
|
||||
userIpFailures: StaleExpirationMap<string, number> | null;
|
||||
/** Wrong trusted-proxy secret presentations, per client IP (multi-user + proxy secret only). */
|
||||
proxySecretFailures: StaleExpirationMap<string, number> | null;
|
||||
}
|
||||
|
||||
/** Rate-limit response for a client that exceeded the failure cap. */
|
||||
@@ -66,6 +85,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;
|
||||
@@ -112,9 +137,7 @@ function checkHookSecretBypass(
|
||||
hookSecretFailures: StaleExpirationMap<string, number>
|
||||
): 'bypass' | 'rejected' | 'continue' {
|
||||
if ((req.url === '/api/hook-event' || req.url === '/api/status-telemetry') && req.method === 'POST') {
|
||||
const ip = req.ip;
|
||||
const isLoopback = ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1';
|
||||
if (isLoopback) {
|
||||
if (isLoopbackIp(req.ip)) {
|
||||
const presented = Buffer.from(req.headers[HOOK_SECRET_HEADER.toLowerCase()]?.toString() ?? '');
|
||||
const expected = Buffer.from(getHookSecret());
|
||||
if (presented.length === expected.length && timingSafeEqual(presented, expected)) {
|
||||
@@ -135,6 +158,111 @@ function checkHookSecretBypass(
|
||||
return 'continue';
|
||||
}
|
||||
|
||||
/** Whether a socket address is loopback. The one test both secret-gated paths (hook, proxy) use. */
|
||||
function isLoopbackIp(ip: string): boolean {
|
||||
return ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1';
|
||||
}
|
||||
|
||||
/**
|
||||
* The trusted-proxy headers each request presented, keyed by request. Filled by the first
|
||||
* auth hook (`registerTrustedProxyHeaderStrip`), which also deletes the headers from the
|
||||
* request; read by `checkTrustedProxyIdentity`. A WeakMap, so nothing outlives the request.
|
||||
*/
|
||||
const presentedProxyHeaders = new WeakMap<FastifyRequest, PresentedProxyHeaders>();
|
||||
|
||||
/** Minimum interval between `touchLastLogin` writes for proxy sign-ins, per user. */
|
||||
const PROXY_LAST_LOGIN_INTERVAL_MS = 15 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* Take the trusted-proxy headers off EVERY request before any other auth logic, route or
|
||||
* exemption (web-tab relay, HTML view, QR) can see them, in every auth mode. Registered
|
||||
* first in `registerAuthMiddleware`, i.e. right after the Host guard.
|
||||
*/
|
||||
function registerTrustedProxyHeaderStrip(app: FastifyInstance): void {
|
||||
const userHeader = resolveTrustedProxyUserHeader();
|
||||
app.addHook('onRequest', (req, _reply, done) => {
|
||||
presentedProxyHeaders.set(req, takeTrustedProxyHeaders(req.headers, userHeader, req.raw));
|
||||
done();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Trusted reverse-proxy identity (see src/config/trusted-proxy.ts). Returns:
|
||||
* - 'continue' : no proxy secret header; fall through to cookie / Basic auth
|
||||
* - 'authenticated' : req.authUser is set from the proxy's username header
|
||||
* - 'rejected' : a reply was already sent
|
||||
*
|
||||
* Fails CLOSED once the secret header is present at all, even empty: a wrong secret or a
|
||||
* non-loopback source (401), or a missing username, one the user store's rule rejects,
|
||||
* or one with no enabled account (403, no challenge) is refused outright and never falls
|
||||
* through to the cookie or Basic paths, so a misconfigured proxy cannot silently degrade
|
||||
* into some other identity. A username header WITHOUT the secret header is ignored
|
||||
* (normal auth applies).
|
||||
*
|
||||
* The username is matched exactly, by the store's own rule (`normalizeUsername`, then
|
||||
* `isValidUsername`): no cutting at `@`, no character replacement. A duplicated header
|
||||
* arrives joined ("alice, bob") and fails that rule.
|
||||
*
|
||||
* The secret is compared BEFORE the failure bucket is consulted, like the hook secret:
|
||||
* a correct secret always passes, so local junk requests (which share 127.0.0.1 with
|
||||
* the proxy) cannot lock sign-in out. Only failures are counted and throttled, in their
|
||||
* own per-IP bucket, so a broken proxy cannot lock out the Basic or hook paths either.
|
||||
*/
|
||||
async function checkTrustedProxyIdentity(
|
||||
req: FastifyRequest,
|
||||
reply: FastifyReply,
|
||||
config: TrustedProxyConfig,
|
||||
proxySecretFailures: StaleExpirationMap<string, number>,
|
||||
lastLoginTouched: Map<string, number>
|
||||
): Promise<'continue' | 'authenticated' | 'rejected'> {
|
||||
const presented = presentedProxyHeaders.get(req);
|
||||
if (!presented?.secretPresent) return 'continue';
|
||||
|
||||
const clientIp = req.ip;
|
||||
const given = Buffer.from(presented.secret);
|
||||
const expected = Buffer.from(config.secret);
|
||||
const secretOk = isLoopbackIp(clientIp) && given.length === expected.length && timingSafeEqual(given, expected);
|
||||
if (!secretOk) {
|
||||
const failures = proxySecretFailures.get(clientIp) ?? 0;
|
||||
if (failures >= AUTH_FAILURE_MAX) {
|
||||
sendAuthRateLimit(reply, proxySecretFailures, clientIp);
|
||||
return 'rejected';
|
||||
}
|
||||
proxySecretFailures.set(clientIp, failures + 1);
|
||||
reply.code(401).send('Unauthorized: trusted proxy secret rejected');
|
||||
return 'rejected';
|
||||
}
|
||||
|
||||
// The proxy vouched for the request, so none of the refusals below is a failed guess:
|
||||
// 403, no challenge, no bucket.
|
||||
const username = normalizeUsername(presented.user);
|
||||
if (!username) {
|
||||
reply.code(403).send('Forbidden: trusted proxy sent no username');
|
||||
return 'rejected';
|
||||
}
|
||||
let user: Awaited<ReturnType<typeof findUser>>;
|
||||
try {
|
||||
user = isValidUsername(username) ? await findUser(username) : undefined;
|
||||
} catch {
|
||||
reply.code(503).send('Service Unavailable: user store unreadable');
|
||||
return 'rejected';
|
||||
}
|
||||
if (!user || user.disabled) {
|
||||
reply.code(403).send('Forbidden: no enabled Codeman account for this user');
|
||||
return 'rejected';
|
||||
}
|
||||
// No mustChangePassword lockbox: the person did not sign in with a Codeman password,
|
||||
// so a pending one-time password has nothing to do with this request.
|
||||
req.authUser = { username: user.username, role: user.role, viaTrustedProxy: true };
|
||||
// Keep "last login" meaningful for proxy sign-ins, without a store write per request.
|
||||
const now = Date.now();
|
||||
if (now - (lastLoginTouched.get(user.username) ?? 0) >= PROXY_LAST_LOGIN_INTERVAL_MS) {
|
||||
lastLoginTouched.set(user.username, now);
|
||||
void touchLastLogin(user.username).catch(() => {});
|
||||
}
|
||||
return 'authenticated';
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests that a `mustChangePassword` user may still reach: the identity probe,
|
||||
* the password-change endpoint, and any non-API path (static assets / index.html,
|
||||
@@ -269,6 +397,80 @@ export function isLostWebviewRootFrame(req: FastifyRequest): boolean {
|
||||
return !carriesAuthCredentials(req.headers, AUTH_COOKIE_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Which capability prefix a request falls under, judged the way a reverse proxy's path
|
||||
* matcher does: query dropped, percent-decoded once, dot segments and doubled slashes
|
||||
* resolved, case-insensitive. A proxy forwards everything it matches this way WITHOUT its
|
||||
* sign-in, so the refusal below must recognise every such spelling, not only the literal
|
||||
* one Codeman's own routes use. Any token shape counts: a malformed token is still a
|
||||
* request the proxy let through.
|
||||
*
|
||||
* `rawUrl` has been through `stripBasePath()`, which removes the mount prefix only in its
|
||||
* literal spelling, so under `basePath` a re-spelled prefix (`/CODEMAN/webview/x`,
|
||||
* `/%63odeman/...`, `//codeman/...`, `/x/../codeman/...`) is still in front. So the
|
||||
* normalised path is judged as it is first, and only when that is no capability path and
|
||||
* it starts with the lower-cased base path, once more with the base path removed once.
|
||||
* Either match counts. As it is comes first because the literal prefix may already be
|
||||
* gone: under a mount named `/webview`, `/webview/webview/x` arrives as `/webview/x`, and
|
||||
* removing the base again would lose the capability prefix itself.
|
||||
*/
|
||||
export function capabilityPrefixOf(rawUrl: string, basePath = ''): 'webview' | 'html-view' | null {
|
||||
let path = rawUrl.split('?')[0];
|
||||
try {
|
||||
path = decodeURIComponent(path);
|
||||
} catch {
|
||||
// Malformed escape: judge the raw path.
|
||||
}
|
||||
// Fold U+0130 (capital I with dot above) to a plain "i" first: Go's lowercasing, which
|
||||
// Caddy's matcher uses, does that, while toLowerCase() yields "i" + U+0307 and would miss
|
||||
// the prefix. Written as an escape so Unicode normalisation can't split it.
|
||||
path = posix
|
||||
.normalize(path)
|
||||
.replace(/\u0130/g, 'i')
|
||||
.toLowerCase();
|
||||
const asIs = capabilityPrefixOfNormalised(path);
|
||||
if (asIs) return asIs;
|
||||
const base = basePath.toLowerCase();
|
||||
return base && path.startsWith(`${base}/`) ? capabilityPrefixOfNormalised(path.slice(base.length)) : null;
|
||||
}
|
||||
|
||||
function capabilityPrefixOfNormalised(path: string): 'webview' | 'html-view' | null {
|
||||
if (path.startsWith(`${WEBVIEW_PROXY_PREFIX}/`)) return 'webview';
|
||||
if (path.startsWith(`${HTML_VIEW_PREFIX}/`)) return 'html-view';
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A request under a capability prefix (`/webview/...`, `/html-view/...`, judged by
|
||||
* `capabilityPrefixOf`) that the capability exemptions above did NOT let through: no live
|
||||
* capability, whatever the token looks like (or a method the exemption never covers).
|
||||
* Refused here with what the route answers an authenticated caller for an unknown
|
||||
* capability (403 for a web tab, 404 for an HTML view), WITHOUT a Basic challenge and
|
||||
* WITHOUT counting a failure.
|
||||
*
|
||||
* Only used when trusted-proxy sign-in is configured. There, these paths reach Codeman
|
||||
* WITHOUT the proxy's own sign-in (their sandboxed frames carry no credentials, so the
|
||||
* proxy has to let them through; see the trusted-proxy docs). Falling through to the
|
||||
* credential checks would expose the password check and a `WWW-Authenticate` prompt to
|
||||
* anyone who can reach the proxy, and let anonymous requests fill the per-IP failure
|
||||
* bucket, which behind the proxy is always 127.0.0.1, locking out Basic sign-in from
|
||||
* loopback. Without a proxy, these paths keep the normal 401 challenge.
|
||||
*
|
||||
* @returns true when the reply was sent.
|
||||
*/
|
||||
function serveRefusedCapabilityPath(req: FastifyRequest, reply: FastifyReply, basePath = ''): boolean {
|
||||
const kind = capabilityPrefixOf(req.url ?? '', basePath);
|
||||
if (kind === 'webview') {
|
||||
reply.code(403).type('text/plain').send('Forbidden: unknown or expired webview capability');
|
||||
return true;
|
||||
}
|
||||
if (kind === 'html-view') {
|
||||
reply.code(404).header('Content-Type', 'text/plain; charset=utf-8').send('Not found');
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Send the static recovery page (lostWebviewFramePage) with its own CSP, uncached. */
|
||||
export function sendLostWebviewFramePage(reply: FastifyReply): FastifyReply {
|
||||
reply.header('content-security-policy', LOST_FRAME_PAGE_CSP);
|
||||
@@ -323,12 +525,18 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean, bas
|
||||
hookSecretFailures: null,
|
||||
userFailures: null,
|
||||
userIpFailures: null,
|
||||
proxySecretFailures: null,
|
||||
};
|
||||
|
||||
// Always declare req.authUser so downstream reads are safe (single-user leaves it
|
||||
// undefined; the ownership helpers then default to a synthetic admin).
|
||||
if (!app.hasRequestDecorator('authUser')) app.decorateRequest('authUser', undefined);
|
||||
|
||||
// First, in every auth mode: take the trusted-proxy headers off the request, so no
|
||||
// later hook, exemption or route (e.g. the web-tab relay) can forward the secret.
|
||||
registerTrustedProxyHeaderStrip(app);
|
||||
initTrustedProxySecret();
|
||||
|
||||
const multiUser = isMultiUserMode();
|
||||
const authPassword = process.env.CODEMAN_PASSWORD;
|
||||
|
||||
@@ -357,9 +565,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,
|
||||
@@ -387,6 +597,15 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean, bas
|
||||
ttlMs: AUTH_FAILURE_WINDOW_MS,
|
||||
refreshOnGet: false,
|
||||
});
|
||||
// Trusted reverse-proxy identity (opt-in). Its own failure bucket, like the hook
|
||||
// secret's, so wrong proxy secrets never count against the Basic login path.
|
||||
const trustedProxy = getTrustedProxyConfig(true);
|
||||
if (trustedProxy) {
|
||||
state.proxySecretFailures = new StaleExpirationMap<string, number>({
|
||||
ttlMs: AUTH_FAILURE_WINDOW_MS,
|
||||
refreshOnGet: false,
|
||||
});
|
||||
}
|
||||
registerMultiUserAuthHook(
|
||||
app,
|
||||
https,
|
||||
@@ -395,7 +614,10 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean, bas
|
||||
hookSecretFailures,
|
||||
state.userFailures,
|
||||
state.userIpFailures,
|
||||
basePath
|
||||
basePath,
|
||||
trustedProxy && state.proxySecretFailures
|
||||
? { config: trustedProxy, failures: state.proxySecretFailures, lastLoginTouched: new Map<string, number>() }
|
||||
: null
|
||||
);
|
||||
return state;
|
||||
}
|
||||
@@ -485,6 +707,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 +727,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;
|
||||
@@ -517,7 +748,12 @@ function registerMultiUserAuthHook(
|
||||
hookSecretFailures: StaleExpirationMap<string, number>,
|
||||
userFailures: StaleExpirationMap<string, number>,
|
||||
userIpFailures: StaleExpirationMap<string, number>,
|
||||
basePath = ''
|
||||
basePath = '',
|
||||
trustedProxy: {
|
||||
config: TrustedProxyConfig;
|
||||
failures: StaleExpirationMap<string, number>;
|
||||
lastLoginTouched: Map<string, number>;
|
||||
} | null = null
|
||||
): void {
|
||||
const setSessionCookie = (reply: FastifyReply, token: string) =>
|
||||
reply.setCookie(AUTH_COOKIE_NAME, token, {
|
||||
@@ -622,8 +858,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) => {
|
||||
@@ -642,6 +877,25 @@ function registerMultiUserAuthHook(
|
||||
if (hasValidHtmlViewCapability(req)) return;
|
||||
// A web-tab frame that lost its prefix: hand it back to its tab, no credentials involved.
|
||||
if (serveLostWebviewFrame(req, reply)) return;
|
||||
// Behind an authenticating proxy, capability paths reach Codeman without the proxy's
|
||||
// sign-in: refuse a non-exempt one with the route's own answer, no challenge, no count.
|
||||
if (trustedProxy && serveRefusedCapabilityPath(req, reply, basePath)) return;
|
||||
|
||||
// 0. Trusted reverse-proxy identity, checked BEFORE the cookie: when the proxy
|
||||
// vouches for a person on this request, that is authoritative, and a stale cookie
|
||||
// from an earlier Basic login in the same browser must not override it. No cookie
|
||||
// is minted: the proxy presents the identity on every new request and WebSocket
|
||||
// upgrade. A stream that is already open is not re-checked.
|
||||
if (trustedProxy) {
|
||||
const proxied = await checkTrustedProxyIdentity(
|
||||
req,
|
||||
reply,
|
||||
trustedProxy.config,
|
||||
trustedProxy.failures,
|
||||
trustedProxy.lastLoginTouched
|
||||
);
|
||||
if (proxied !== 'continue') return;
|
||||
}
|
||||
|
||||
const clientIp = req.ip;
|
||||
|
||||
@@ -703,6 +957,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 +1009,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);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+571
-68
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,571 @@
|
||||
/**
|
||||
* @fileoverview Chat view: a session's conversation, rendered like the Response Viewer, as the
|
||||
* session's main view (docs/chat-view-plan.md, phase 1).
|
||||
*
|
||||
* The agent keeps running in its tmux pane. The chat view is a second way to look at that pane:
|
||||
* it covers the terminal (which stays mounted, attached and sized, so the PTY is never resized
|
||||
* by a view switch) and draws the conversation from the session's transcript.
|
||||
*
|
||||
* - Which sessions can have it: those whose run mode Codeman reads from a Claude-format
|
||||
* transcript (`window.__codemanChatViewModes`, published from the `transcript` capability,
|
||||
* never an id list here), local or Docker, not remote and not adopted, and not on a phone.
|
||||
* - Which view a session shows: the per-device choice remembered for that session
|
||||
* (`codeman:chatViewModes` in localStorage), else the per-device setting `chatViewDefault`
|
||||
* (default off, so a session opens in Terminal until the user picks Chat).
|
||||
* - The Chat / Terminal switch: shown on an eligible session only when the per-device setting
|
||||
* `showChatViewSwitch` is true (default off: an absent key means hidden, so nobody sees the
|
||||
* switch without choosing it). Hidden, it changes nothing else: the session keeps its view,
|
||||
* and Alt+Shift+C still switches.
|
||||
* - Live updates: the conversation is re-read (debounced) on the session's `transcript:update`,
|
||||
* `session:working` and `session:idle`. Nothing is read while the chat view is hidden.
|
||||
* - Typing: the chat view has no message box yet, so the user types in the terminal. A focus
|
||||
* that lands on the hidden terminal moves to the conversation, so keys never reach the pane
|
||||
* unseen.
|
||||
* - A dialog in the pane (permission, question, plan approval) shows as a notice with a button
|
||||
* that switches to the terminal, where it is answered.
|
||||
*
|
||||
* Messages are model and user text: they go through the Response Viewer's sanitising markdown
|
||||
* pipeline (`_buildResponseViewerMessage`), and everything else is set with `textContent`.
|
||||
*
|
||||
* @mixin Extends CodemanApp.prototype via Object.assign
|
||||
* @dependency app.js (this.activeSessionId, this.sessions, this.pendingHooks, _buildResponseViewerMessage,
|
||||
* _bindResponseViewerInteractions, _getResponseViewerAgentLabel)
|
||||
* @dependency constants.js (CodemanChatView)
|
||||
* @dependency api-client.js at runtime (this._apiJson)
|
||||
* @loadorder 12.595 of 16, after local-model-ui.js, before entrance-animations.js
|
||||
*/
|
||||
|
||||
const CHAT_VIEW_MODES_KEY = 'codeman:chatViewModes';
|
||||
/** Wait after an update before re-reading, so a burst of events costs one read. */
|
||||
const CHAT_VIEW_RELOAD_DEBOUNCE_MS = 250;
|
||||
|
||||
Object.assign(CodemanApp.prototype, {
|
||||
// ─── Eligibility and choice ──────────────────────────────────
|
||||
|
||||
/** Whether `sessionId` can show the chat view on this device. */
|
||||
chatViewEligible(sessionId) {
|
||||
const session = sessionId ? this.sessions?.get(sessionId) : null;
|
||||
if (!session) return false;
|
||||
const modes = Array.isArray(window.__codemanChatViewModes) ? window.__codemanChatViewModes : [];
|
||||
if (!session.mode || !modes.includes(session.mode)) return false;
|
||||
// A remote session's transcript lives on its host, and an adopted one has none Codeman can name.
|
||||
if (session.remote || session.adopt) return false;
|
||||
// Phones keep the terminal and its keyboard bars (phase 3 lays the chat view out for them),
|
||||
// whatever their orientation or fold: a phone turned to landscape is still a phone.
|
||||
if (typeof MobileDetection !== 'undefined') {
|
||||
const phone = MobileDetection.isHandheldDevice?.() ?? MobileDetection.getDeviceType?.() === 'mobile';
|
||||
if (phone) return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
|
||||
/** The per-device choice for each session, `{ [sessionId]: 'chat' | 'terminal' }`. */
|
||||
_chatViewStoredModes() {
|
||||
try {
|
||||
const parsed = JSON.parse(localStorage.getItem(CHAT_VIEW_MODES_KEY) || '{}');
|
||||
return parsed && typeof parsed === 'object' ? parsed : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
},
|
||||
|
||||
_chatViewStoreModes(modes) {
|
||||
try {
|
||||
localStorage.setItem(CHAT_VIEW_MODES_KEY, JSON.stringify(modes));
|
||||
} catch {
|
||||
// Storage blocked: the choice lasts for this page load only.
|
||||
}
|
||||
},
|
||||
|
||||
/** 'chat' or 'terminal' for `sessionId`. */
|
||||
chatViewModeFor(sessionId) {
|
||||
const stored = this._chatViewStoredModes()[sessionId];
|
||||
if (stored === 'chat' || stored === 'terminal') return stored;
|
||||
if (this._chatViewMemoryModes?.has(sessionId)) return this._chatViewMemoryModes.get(sessionId);
|
||||
return this.loadAppSettingsFromStorage?.().chatViewDefault === true ? 'chat' : 'terminal';
|
||||
},
|
||||
|
||||
setChatViewMode(sessionId, mode) {
|
||||
if (!sessionId || (mode !== 'chat' && mode !== 'terminal')) return;
|
||||
if (!this._chatViewMemoryModes) this._chatViewMemoryModes = new Map();
|
||||
this._chatViewMemoryModes.set(sessionId, mode);
|
||||
const modes = this._chatViewStoredModes();
|
||||
modes[sessionId] = mode;
|
||||
this._chatViewStoreModes(modes);
|
||||
if (sessionId === this.activeSessionId) this._chatViewSync({ focus: true });
|
||||
},
|
||||
|
||||
/**
|
||||
* Called after each init (app.js) with the server's session list: drop the view choice of every
|
||||
* session not in it. A session deleted while no page was open sends this page no event.
|
||||
*/
|
||||
_chatViewPruneModes(liveIds) {
|
||||
for (const id of [...(this._chatViewMemoryModes?.keys() ?? [])]) {
|
||||
if (!liveIds.has(id)) this._chatViewMemoryModes.delete(id);
|
||||
}
|
||||
const modes = this._chatViewStoredModes();
|
||||
const kept = Object.fromEntries(Object.entries(modes).filter(([id]) => liveIds.has(id)));
|
||||
if (Object.keys(kept).length !== Object.keys(modes).length) this._chatViewStoreModes(kept);
|
||||
},
|
||||
|
||||
/** Whether this device shows the Chat / Terminal switch. Off by default: an absent setting means it does not. */
|
||||
_chatViewSwitchShown() {
|
||||
return this.loadAppSettingsFromStorage?.().showChatViewSwitch === true;
|
||||
},
|
||||
|
||||
/** The Alt+Shift+C action: flip the active session between Chat and Terminal. */
|
||||
toggleChatView() {
|
||||
const id = this.activeSessionId;
|
||||
if (!this.chatViewEligible(id) || this._tilesOwnTerminal?.()) return;
|
||||
this.setChatViewMode(id, this.chatViewModeFor(id) === 'chat' ? 'terminal' : 'chat');
|
||||
},
|
||||
|
||||
/**
|
||||
* True when `e` is the chat view toggle chord and it applies here, so the xterm key handler
|
||||
* swallows it. Outside a session that can show the chat view, the chord reaches the terminal.
|
||||
*/
|
||||
shouldToggleChatViewFromShortcut(e) {
|
||||
if (!e || (!e.ctrlKey && !e.metaKey && !e.altKey)) return false;
|
||||
if (!this.chatViewEligible(this.activeSessionId) || this._tilesOwnTerminal?.()) return false;
|
||||
if (typeof this.getShortcutRegistry !== 'function' || typeof this.matchesShortcutEvent !== 'function') return false;
|
||||
const shortcut = this.getShortcutRegistry().find((s) => s.id === 'toggle-chat-view');
|
||||
if (!shortcut || shortcut.disabled) return false;
|
||||
return this.matchesShortcutEvent(e, shortcut);
|
||||
},
|
||||
|
||||
// ─── DOM ─────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* `text` in the page's language. i18n.js translates the DOM as it changes, but it skips every
|
||||
* <textarea> and the `data-i18n-skip` conversation, so the strings drawn there are looked up here.
|
||||
*/
|
||||
_chatViewT(text, vars) {
|
||||
return window.CodemanI18n?.t?.(text, vars) ?? text;
|
||||
},
|
||||
|
||||
_chatViewEnsureDom() {
|
||||
if (this._chatView) return this._chatView;
|
||||
const wrap = document.querySelector('.terminal-wrap');
|
||||
if (!wrap) return null;
|
||||
|
||||
const toggle = document.createElement('div');
|
||||
toggle.className = 'chat-view-toggle';
|
||||
toggle.setAttribute('role', 'group');
|
||||
toggle.setAttribute('aria-label', 'Session view');
|
||||
toggle.hidden = true;
|
||||
const chatBtn = document.createElement('button');
|
||||
chatBtn.type = 'button';
|
||||
chatBtn.className = 'chat-view-toggle-btn';
|
||||
chatBtn.dataset.mode = 'chat';
|
||||
chatBtn.textContent = 'Chat';
|
||||
chatBtn.title = 'Show the conversation (Alt+Shift+C)';
|
||||
const termBtn = document.createElement('button');
|
||||
termBtn.type = 'button';
|
||||
termBtn.className = 'chat-view-toggle-btn';
|
||||
termBtn.dataset.mode = 'terminal';
|
||||
termBtn.textContent = 'Terminal';
|
||||
termBtn.title = 'Show the terminal (Alt+Shift+C)';
|
||||
toggle.append(chatBtn, termBtn);
|
||||
toggle.addEventListener('click', (ev) => {
|
||||
const btn = ev.target.closest('.chat-view-toggle-btn');
|
||||
if (btn && this.activeSessionId) this.setChatViewMode(this.activeSessionId, btn.dataset.mode);
|
||||
});
|
||||
|
||||
const root = document.createElement('section');
|
||||
root.className = 'chat-view';
|
||||
root.setAttribute('aria-label', 'Conversation');
|
||||
root.hidden = true;
|
||||
|
||||
// The Response Viewer's body class: the chat view renders exactly as the viewer does.
|
||||
const scroller = document.createElement('div');
|
||||
scroller.className = 'chat-view-scroll response-viewer-body';
|
||||
scroller.setAttribute('data-i18n-skip', '');
|
||||
// Focusable, so a focus taken from the hidden terminal has somewhere to go.
|
||||
scroller.tabIndex = -1;
|
||||
const thread = document.createElement('div');
|
||||
thread.className = 'chat-view-thread';
|
||||
const empty = document.createElement('p');
|
||||
empty.className = 'chat-view-empty';
|
||||
empty.hidden = true;
|
||||
scroller.append(thread, empty);
|
||||
|
||||
const dialog = document.createElement('div');
|
||||
dialog.className = 'chat-view-dialog';
|
||||
dialog.setAttribute('role', 'status');
|
||||
dialog.hidden = true;
|
||||
const dialogText = document.createElement('span');
|
||||
dialogText.className = 'chat-view-dialog-text';
|
||||
dialogText.textContent = 'Claude is waiting for your answer in the terminal.';
|
||||
const dialogBtn = document.createElement('button');
|
||||
dialogBtn.type = 'button';
|
||||
dialogBtn.className = 'chat-view-btn chat-view-btn-primary';
|
||||
dialogBtn.textContent = 'Open terminal';
|
||||
dialogBtn.addEventListener('click', () => {
|
||||
const id = this.activeSessionId;
|
||||
if (!id) return;
|
||||
this.setChatViewMode(id, 'terminal');
|
||||
this.terminal?.focus?.();
|
||||
});
|
||||
dialog.append(dialogText, dialogBtn);
|
||||
|
||||
const status = document.createElement('div');
|
||||
status.className = 'chat-view-status';
|
||||
status.setAttribute('role', 'status');
|
||||
status.setAttribute('aria-live', 'polite');
|
||||
status.hidden = true;
|
||||
const statusDot = document.createElement('span');
|
||||
statusDot.className = 'chat-view-status-dot';
|
||||
statusDot.setAttribute('aria-hidden', 'true');
|
||||
const statusBody = document.createElement('div');
|
||||
statusBody.className = 'chat-view-status-body';
|
||||
const statusText = document.createElement('div');
|
||||
statusText.className = 'chat-view-status-text';
|
||||
statusBody.append(statusText);
|
||||
status.append(statusDot, statusBody);
|
||||
|
||||
// The status line follows the last message, inside the scrolling area, so an eye watching
|
||||
// the newest output finds it there and not at the bottom of the window.
|
||||
scroller.insertBefore(status, empty);
|
||||
root.append(scroller, dialog);
|
||||
wrap.append(root, toggle);
|
||||
|
||||
// Keys must never reach the hidden terminal: a focus that lands there (a click-through, a
|
||||
// code path that refocuses the terminal after a load) moves to the conversation. That covers
|
||||
// #terminalContainer and #cjkInput, which takes terminal.focus() while CJK input is on and
|
||||
// sits outside the container, under the chat layer.
|
||||
const redirectFocus = () => {
|
||||
if (this._chatViewShowing()) this._chatView?.scroller.focus({ preventScroll: true });
|
||||
};
|
||||
document.getElementById('terminalContainer')?.addEventListener('focusin', redirectFocus);
|
||||
document.getElementById('cjkInput')?.addEventListener('focusin', redirectFocus);
|
||||
|
||||
// A file dropped on the conversation or on the Chat / Terminal switch must not make the
|
||||
// browser open it and leave Codeman. Nothing is uploaded here: an upload would type the file's
|
||||
// path into the hidden pane, and attaching belongs to the message box (docs/chat-view-plan.md,
|
||||
// phase 1 step 2). The no-drop cursor tells a user who drags a file here that Chat takes none.
|
||||
const refuseDragOver = (ev) => {
|
||||
ev.preventDefault();
|
||||
if (ev.dataTransfer) ev.dataTransfer.dropEffect = 'none';
|
||||
};
|
||||
const refuseDrop = (ev) => ev.preventDefault();
|
||||
for (const target of [root, toggle]) {
|
||||
target.addEventListener('dragover', refuseDragOver);
|
||||
target.addEventListener('drop', refuseDrop);
|
||||
}
|
||||
|
||||
this._chatView = {
|
||||
root,
|
||||
toggle,
|
||||
chatBtn,
|
||||
termBtn,
|
||||
scroller,
|
||||
thread,
|
||||
empty,
|
||||
dialog,
|
||||
status,
|
||||
statusText,
|
||||
sessionId: null,
|
||||
keys: [],
|
||||
reloadTimer: null,
|
||||
statusTimer: null,
|
||||
loading: false,
|
||||
reloadAgain: false,
|
||||
};
|
||||
return this._chatView;
|
||||
},
|
||||
|
||||
/** Whether the chat view is what the main area shows right now. */
|
||||
_chatViewShowing() {
|
||||
return !!this._chatView && !this._chatView.root.hidden;
|
||||
},
|
||||
|
||||
/** Whether keyboard focus sits in the terminal: inside #terminalContainer, or on #cjkInput. */
|
||||
_chatViewFocusInTerminal() {
|
||||
const active = document.activeElement;
|
||||
if (!active) return false;
|
||||
if (active.id === 'cjkInput') return true;
|
||||
return !!document.getElementById('terminalContainer')?.contains(active);
|
||||
},
|
||||
|
||||
// ─── Sync with the active session ────────────────────────────
|
||||
|
||||
/** app.js selectSession(): the active session changed. */
|
||||
onChatViewActiveSession() {
|
||||
this._chatViewSync({ focus: true });
|
||||
},
|
||||
|
||||
/**
|
||||
* Show or hide the toggle and the chat view for the active session, and (re)load the
|
||||
* conversation when the chat view starts showing a session.
|
||||
*/
|
||||
_chatViewSync(opts = {}) {
|
||||
const id = this.activeSessionId;
|
||||
const eligible = this.chatViewEligible(id);
|
||||
if (!eligible && !this._chatView) return;
|
||||
const view = this._chatViewEnsureDom();
|
||||
if (!view) return;
|
||||
// Focus follows the app's tab-switch rule, as the terminal's does.
|
||||
const focus = !!opts.focus && (this._shouldFocusTerminalForTabSwitch?.() ?? true);
|
||||
const mode = eligible ? this.chatViewModeFor(id) : 'terminal';
|
||||
// The tile grid owns the terminal area while it is open, and its tiles are terminals: the
|
||||
// chat view stays hidden, whatever the active session's choice (tile-grid.js syncs it).
|
||||
const showChat = eligible && mode === 'chat' && !this._tilesOwnTerminal?.();
|
||||
|
||||
// The setting hides only the switch: the session keeps its view, and Alt+Shift+C still works.
|
||||
view.toggle.hidden = !eligible || !this._chatViewSwitchShown();
|
||||
view.chatBtn.setAttribute('aria-pressed', String(showChat));
|
||||
view.termBtn.setAttribute('aria-pressed', String(!showChat));
|
||||
view.toggle.classList.toggle('chat-view-toggle--over-chat', showChat);
|
||||
|
||||
const wasShowing = !view.root.hidden;
|
||||
const previousId = view.sessionId;
|
||||
view.root.hidden = !showChat;
|
||||
document.querySelector('.terminal-wrap')?.classList.toggle('chat-view-active', showChat);
|
||||
// styles.css hides the keyboard accessory bar while this is set: its keys write into the pane.
|
||||
document.body.classList.toggle('chat-view-showing', showChat);
|
||||
if (!showChat) {
|
||||
if (view.statusTimer) {
|
||||
clearInterval(view.statusTimer);
|
||||
view.statusTimer = null;
|
||||
}
|
||||
if (wasShowing && focus && eligible) this.terminal?.focus?.();
|
||||
return;
|
||||
}
|
||||
|
||||
if (previousId !== id) {
|
||||
view.sessionId = id;
|
||||
view.keys = [];
|
||||
view.thread.replaceChildren();
|
||||
view.empty.hidden = true;
|
||||
}
|
||||
const agent = this._getResponseViewerAgentLabel?.() || 'Claude';
|
||||
view.root.querySelector('.chat-view-dialog-text').textContent =
|
||||
`${agent} is waiting for your answer in the terminal.`;
|
||||
this._chatViewSyncDialog(id);
|
||||
this._chatViewRenderStatus();
|
||||
if (previousId !== id || !wasShowing) this._chatViewReload({ immediate: true });
|
||||
// A terminal that already has focus fires no new focusin, so hardware-keyboard input would
|
||||
// keep reaching the pane behind the chat view. Move that focus now, whatever the tab-switch
|
||||
// rule says: focusing the conversation opens no soft keyboard.
|
||||
if (this._chatViewFocusInTerminal()) view.scroller.focus({ preventScroll: true });
|
||||
if (focus) requestAnimationFrame(() => view.scroller.focus({ preventScroll: true }));
|
||||
},
|
||||
|
||||
/** Hide everything (home screen, session gone). */
|
||||
_chatViewHide() {
|
||||
if (!this._chatView) return;
|
||||
if (this._chatView.statusTimer) {
|
||||
clearInterval(this._chatView.statusTimer);
|
||||
this._chatView.statusTimer = null;
|
||||
}
|
||||
this._chatView.root.hidden = true;
|
||||
this._chatView.toggle.hidden = true;
|
||||
document.querySelector('.terminal-wrap')?.classList.remove('chat-view-active');
|
||||
document.body.classList.remove('chat-view-showing');
|
||||
},
|
||||
|
||||
/**
|
||||
* Called when a session is deleted (app.js): forget its turn state. The view choice stays, because
|
||||
* a detach sends the same event and the session can be attached again; `_chatViewPruneModes`
|
||||
* drops the choices of sessions that are gone.
|
||||
*/
|
||||
_chatViewForget(sessionId) {
|
||||
this._chatViewTurnStarts?.delete(sessionId);
|
||||
this._chatViewIdleSeen?.delete(sessionId);
|
||||
this._chatViewKeepAliveTurns?.delete(sessionId);
|
||||
if (this._chatView?.sessionId === sessionId) {
|
||||
this._chatView.sessionId = null;
|
||||
this._chatView.keys = [];
|
||||
this._chatView.thread.replaceChildren();
|
||||
}
|
||||
},
|
||||
|
||||
// ─── Events ──────────────────────────────────────────────────
|
||||
|
||||
/** SSE `transcript:update`: new transcript lines for `data.sessionId`. */
|
||||
_onChatViewTranscriptUpdate(data) {
|
||||
if (data?.sessionId && data.sessionId === this._chatView?.sessionId && this._chatViewShowing()) {
|
||||
this._chatViewReload();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* app.js `_onSessionIdle` / `_onSessionWorking`: a turn started or ended. `keepAlive` marks
|
||||
* Codeman's own keep-warm turn, which the conversation hides: the status line stays hidden
|
||||
* for it.
|
||||
*/
|
||||
onChatViewTurnEvent(sessionId, idle, keepAlive) {
|
||||
if (!this._chatViewTurnStarts) this._chatViewTurnStarts = new Map();
|
||||
if (!this._chatViewIdleSeen) this._chatViewIdleSeen = new Set();
|
||||
if (!this._chatViewKeepAliveTurns) this._chatViewKeepAliveTurns = new Set();
|
||||
if (!idle && keepAlive) this._chatViewKeepAliveTurns.add(sessionId);
|
||||
else this._chatViewKeepAliveTurns.delete(sessionId);
|
||||
// A turn's start is "now" only when this page saw the session idle first. A working event
|
||||
// for a session already busy when the page loaded (or the server restarted) says nothing
|
||||
// about when its turn began, so the status line falls back to the last Enter.
|
||||
if (!idle && this._chatViewIdleSeen.has(sessionId)) {
|
||||
this._chatViewIdleSeen.delete(sessionId);
|
||||
this._chatViewTurnStarts.set(sessionId, Date.now());
|
||||
}
|
||||
if (idle) {
|
||||
this._chatViewIdleSeen.add(sessionId);
|
||||
this._chatViewTurnStarts.delete(sessionId);
|
||||
}
|
||||
if (sessionId !== this._chatView?.sessionId || !this._chatViewShowing()) return;
|
||||
this._chatViewRenderStatus();
|
||||
this._chatViewReload();
|
||||
},
|
||||
|
||||
/** app.js updateTabAlertFromHooks(): a dialog appeared or was answered. */
|
||||
onChatViewHooksChanged(sessionId) {
|
||||
if (sessionId !== this._chatView?.sessionId || !this._chatViewShowing()) return;
|
||||
this._chatViewSyncDialog(sessionId);
|
||||
},
|
||||
|
||||
/** Whether the pane shows a dialog (permission, question, plan approval), answered in the terminal. */
|
||||
_chatViewDialogPending(sessionId) {
|
||||
const hooks = this.pendingHooks?.get(sessionId);
|
||||
return !!hooks && (hooks.has('permission_prompt') || hooks.has('elicitation_dialog'));
|
||||
},
|
||||
|
||||
_chatViewSyncDialog(sessionId) {
|
||||
const view = this._chatView;
|
||||
if (!view) return;
|
||||
view.dialog.hidden = !this._chatViewDialogPending(sessionId);
|
||||
},
|
||||
|
||||
/** Whether `sessionId` runs a turn the chat view shows: busy, and not Codeman's keep-alive turn. */
|
||||
_chatViewBusy(sessionId) {
|
||||
if (this._chatViewKeepAliveTurns?.has(sessionId)) return false;
|
||||
return this.sessions?.get(sessionId)?.status === 'busy';
|
||||
},
|
||||
|
||||
_chatViewRenderStatus() {
|
||||
const view = this._chatView;
|
||||
if (!view) return;
|
||||
const session = this.sessions?.get(view.sessionId);
|
||||
const busy = this._chatViewBusy(view.sessionId);
|
||||
// Keep the view pinned to the bottom when the status line appears under the last message,
|
||||
// if the reader was already there.
|
||||
const scroller = view.scroller;
|
||||
const atBottom = scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 48;
|
||||
view.status.hidden = !busy;
|
||||
if (!busy && view.sessionId) {
|
||||
if (!this._chatViewIdleSeen) this._chatViewIdleSeen = new Set();
|
||||
this._chatViewIdleSeen.add(view.sessionId);
|
||||
}
|
||||
if (busy) {
|
||||
const activity = this._chatViewT('Working');
|
||||
// The turn's start: seen live (session:working after idle), else the last Enter (a page
|
||||
// loaded mid-turn), else unknown and left out.
|
||||
const startedAt = this._chatViewTurnStarts?.get(view.sessionId) || session?.lastSubmitAt || 0;
|
||||
view.statusText.textContent = startedAt
|
||||
? `${activity} · ${window.CodemanChatView.elapsed(Date.now() - startedAt)}`
|
||||
: activity;
|
||||
}
|
||||
// The running time ticks once a second, only while the status line is on screen.
|
||||
const ticking = busy && this._chatViewShowing();
|
||||
if (ticking && !view.statusTimer) view.statusTimer = setInterval(() => this._chatViewRenderStatus(), 1000);
|
||||
if (!ticking && view.statusTimer) {
|
||||
clearInterval(view.statusTimer);
|
||||
view.statusTimer = null;
|
||||
}
|
||||
if (atBottom) scroller.scrollTop = scroller.scrollHeight;
|
||||
},
|
||||
|
||||
// ─── Reading and drawing the conversation ────────────────────
|
||||
|
||||
/** Re-read the conversation, debounced unless `immediate`. One read at a time. */
|
||||
_chatViewReload(opts = {}) {
|
||||
const view = this._chatView;
|
||||
if (!view || !view.sessionId) return;
|
||||
clearTimeout(view.reloadTimer);
|
||||
if (opts.immediate) {
|
||||
this._chatViewFetch();
|
||||
return;
|
||||
}
|
||||
view.reloadTimer = setTimeout(() => this._chatViewFetch(), CHAT_VIEW_RELOAD_DEBOUNCE_MS);
|
||||
},
|
||||
|
||||
async _chatViewFetch() {
|
||||
const view = this._chatView;
|
||||
if (!view || !view.sessionId || !this._chatViewShowing()) return;
|
||||
if (view.loading) {
|
||||
view.reloadAgain = true;
|
||||
return;
|
||||
}
|
||||
const sessionId = view.sessionId;
|
||||
view.loading = true;
|
||||
try {
|
||||
const data = await this._apiJson(`/api/sessions/${encodeURIComponent(sessionId)}/last-response?context=full`);
|
||||
// A read that finished after the user moved on is dropped.
|
||||
if (view.sessionId !== sessionId || !this._chatViewShowing()) return;
|
||||
if (data && Array.isArray(data.messages)) this._chatViewRender(data.messages);
|
||||
} finally {
|
||||
view.loading = false;
|
||||
if (view.reloadAgain) {
|
||||
view.reloadAgain = false;
|
||||
this._chatViewReload();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
_chatViewRender(rawMessages) {
|
||||
const view = this._chatView;
|
||||
const helpers = window.CodemanChatView;
|
||||
if (!view || !helpers) return;
|
||||
const messages = helpers.visibleMessages(rawMessages);
|
||||
const keys = messages.map(helpers.messageKey);
|
||||
const plan = helpers.renderPlan(view.keys, keys);
|
||||
view.empty.hidden = messages.length > 0;
|
||||
if (messages.length === 0) view.empty.textContent = this._chatViewT('No messages yet.');
|
||||
if (plan.mode === 'none') return;
|
||||
|
||||
const scroller = view.scroller;
|
||||
const atBottom = scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 48;
|
||||
const firstDraw = view.keys.length === 0;
|
||||
const from = plan.mode === 'append' ? plan.from : 0;
|
||||
if (plan.mode === 'replace') view.thread.replaceChildren();
|
||||
|
||||
const agentLabel = this._getResponseViewerAgentLabel?.() || 'Claude';
|
||||
const fragment = document.createDocumentFragment();
|
||||
for (let i = from; i < messages.length; i++) {
|
||||
const msg = messages[i];
|
||||
const previous = i > 0 ? messages[i - 1] : null;
|
||||
// Same rule as the Response Viewer's full view: one badge per speaker per turn.
|
||||
const continuation =
|
||||
!!previous && previous.role === msg.role && typeof msg.turn === 'number' && previous.turn === msg.turn;
|
||||
fragment.appendChild(this._chatViewBuildMessage(msg, agentLabel, continuation));
|
||||
}
|
||||
view.thread.appendChild(fragment);
|
||||
view.keys = keys;
|
||||
this._bindResponseViewerInteractions?.(view.thread);
|
||||
if (firstDraw || atBottom) scroller.scrollTop = scroller.scrollHeight;
|
||||
},
|
||||
|
||||
/** One drawn message. A long prompt folds to its first lines. */
|
||||
_chatViewBuildMessage(msg, agentLabel, continuation) {
|
||||
const meta = { ...msg, continuation };
|
||||
if (msg.role !== 'user') return this._buildResponseViewerMessage(msg.text, 'assistant', agentLabel, meta);
|
||||
const text = window.CodemanChatView.promptText(msg.text);
|
||||
const fold = window.CodemanChatView.promptFold(text);
|
||||
const el = this._buildResponseViewerMessage(fold.head, 'user', agentLabel, meta);
|
||||
if (!fold.folded) return el;
|
||||
el.classList.add('chat-view-msg-folded');
|
||||
const more = document.createElement('button');
|
||||
more.type = 'button';
|
||||
more.className = 'chat-view-show-all';
|
||||
more.textContent = this._chatViewT(`Show all (${fold.totalLines} ${fold.totalLines === 1 ? 'line' : 'lines'})`);
|
||||
// Unfold in place, keeping the badge the element shows now.
|
||||
more.addEventListener('click', () => {
|
||||
const full = this._buildResponseViewerMessage(text, 'user', agentLabel, {
|
||||
...meta,
|
||||
continuation: el.classList.contains('rv-msg-cont'),
|
||||
});
|
||||
el.replaceChildren(...full.childNodes);
|
||||
el.classList.remove('chat-view-msg-folded');
|
||||
});
|
||||
el.appendChild(more);
|
||||
return el;
|
||||
},
|
||||
});
|
||||
@@ -1514,6 +1514,95 @@ function findMarkdownAnchorTarget(root, href) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// ─── Chat view (chat-view.js) ─────────────────────────────────────────────────
|
||||
// Pure halves of the chat view, the rendered conversation that replaces the terminal
|
||||
// as a session's main view (docs/chat-view-plan.md). The module owns the DOM; these
|
||||
// decide what it shows, so a test can pin them without a browser.
|
||||
|
||||
/** A prompt longer than this many lines, or characters, is folded. */
|
||||
const CHAT_PROMPT_FOLD_LINES = 12;
|
||||
const CHAT_PROMPT_FOLD_CHARS = 2400;
|
||||
/** What a folded prompt still shows. */
|
||||
const CHAT_PROMPT_HEAD_LINES = 6;
|
||||
const CHAT_PROMPT_HEAD_CHARS = 800;
|
||||
|
||||
/**
|
||||
* The messages the chat view draws, in order: prompts and answers with text, without
|
||||
* the keep-warm turns Codeman sends on its own (`keepAlive`, set by the transcript reader).
|
||||
*/
|
||||
function chatViewVisibleMessages(messages) {
|
||||
if (!Array.isArray(messages)) return [];
|
||||
return messages.filter(
|
||||
(m) =>
|
||||
!!m &&
|
||||
(m.role === 'user' || m.role === 'assistant') &&
|
||||
typeof m.text === 'string' &&
|
||||
m.text.trim() !== '' &&
|
||||
m.keepAlive !== true
|
||||
);
|
||||
}
|
||||
|
||||
/** Identity of a drawn message: a transcript row never changes once written. */
|
||||
function chatViewMessageKey(m) {
|
||||
return `${m.role}\u0000${typeof m.turn === 'number' ? m.turn : ''}\u0000${m.queued ? 'q' : ''}\u0000${m.text}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* How to bring the drawn thread up to date. `none` when nothing changed, `append`
|
||||
* when the new list only adds messages after the drawn ones (the usual case while a
|
||||
* turn runs), else `replace` (a `/clear`, a rewritten transcript, another session).
|
||||
*/
|
||||
function chatViewRenderPlan(drawnKeys, nextKeys) {
|
||||
const drawn = Array.isArray(drawnKeys) ? drawnKeys : [];
|
||||
const next = Array.isArray(nextKeys) ? nextKeys : [];
|
||||
if (drawn.length > next.length) return { mode: 'replace' };
|
||||
for (let i = 0; i < drawn.length; i++) {
|
||||
if (drawn[i] !== next[i]) return { mode: 'replace' };
|
||||
}
|
||||
if (drawn.length === next.length) return { mode: 'none' };
|
||||
return { mode: 'append', from: drawn.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* A prompt as the user wrote it. Claude Code stores a pasted block (which every multi-line
|
||||
* prompt sent through tmux is) inside `<pasted_content id="…">…</pasted_content id="…">` (the
|
||||
* closing tag repeats the id, measured on Claude Code 2.1.331); the markdown
|
||||
* renderer reads that as a raw HTML block and runs its lines together. Only matched pairs are
|
||||
* unwrapped, so a prompt that merely mentions the tag is left alone.
|
||||
*/
|
||||
function chatViewPromptText(text) {
|
||||
return String(text ?? '').replace(
|
||||
/<pasted_content(?:\s[^>]*)?>\n?([\s\S]*?)\n?<\/pasted_content(?:\s[^>]*)?>/g,
|
||||
(_match, body) => body
|
||||
);
|
||||
}
|
||||
|
||||
/** A running turn's length as the CLI shows it: `14s`, `2m 05s`, `1h 03m`. */
|
||||
function chatViewElapsed(ms) {
|
||||
const total = Math.max(0, Math.floor((Number(ms) || 0) / 1000));
|
||||
const h = Math.floor(total / 3600);
|
||||
const m = Math.floor((total % 3600) / 60);
|
||||
const sec = total % 60;
|
||||
if (h > 0) return `${h}h ${String(m).padStart(2, '0')}m`;
|
||||
if (m > 0) return `${m}m ${String(sec).padStart(2, '0')}s`;
|
||||
return `${sec}s`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a prompt is folded, and what its folded form shows: the first lines, capped
|
||||
* in characters so one enormous pasted line folds too.
|
||||
*/
|
||||
function chatViewPromptFold(text) {
|
||||
const value = String(text ?? '');
|
||||
const lines = value.split('\n');
|
||||
if (lines.length <= CHAT_PROMPT_FOLD_LINES && value.length <= CHAT_PROMPT_FOLD_CHARS) {
|
||||
return { folded: false, head: value, totalLines: lines.length };
|
||||
}
|
||||
let head = lines.slice(0, CHAT_PROMPT_HEAD_LINES).join('\n');
|
||||
if (head.length > CHAT_PROMPT_HEAD_CHARS) head = `${head.slice(0, CHAT_PROMPT_HEAD_CHARS)}…`;
|
||||
return { folded: true, head, totalLines: lines.length };
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.WEBGL_FALLBACK = WEBGL_FALLBACK;
|
||||
window.evaluateWebGLLongTaskTrip = evaluateWebGLLongTaskTrip;
|
||||
@@ -1581,6 +1670,14 @@ if (typeof window !== 'undefined') {
|
||||
needle: tabSearchNeedle,
|
||||
filter: filterTabSearchRows,
|
||||
};
|
||||
window.CodemanChatView = {
|
||||
visibleMessages: chatViewVisibleMessages,
|
||||
messageKey: chatViewMessageKey,
|
||||
renderPlan: chatViewRenderPlan,
|
||||
promptFold: chatViewPromptFold,
|
||||
promptText: chatViewPromptText,
|
||||
elapsed: chatViewElapsed,
|
||||
};
|
||||
window.CodemanInputLimit = {
|
||||
FRAME_MAX_CHARS: INPUT_FRAME_MAX_CHARS,
|
||||
PASTE_MAX_CHARS: INPUT_PASTE_MAX_CHARS,
|
||||
@@ -1914,6 +2011,7 @@ const SSE_EVENTS = {
|
||||
TRANSCRIPT_PLAN_MODE: 'transcript:plan_mode',
|
||||
TRANSCRIPT_TOOL_START: 'transcript:tool_start',
|
||||
TRANSCRIPT_TOOL_END: 'transcript:tool_end',
|
||||
TRANSCRIPT_UPDATE: 'transcript:update',
|
||||
|
||||
// Clipboard
|
||||
CLIPBOARD_WRITE: 'clipboard:write',
|
||||
|
||||
+57
-2
@@ -225,6 +225,21 @@
|
||||
// input like Click (单击).
|
||||
Tabs: '标签页',
|
||||
'Toggle Session Sidebar': '切换会话侧边栏',
|
||||
// Chat view (chat-view.js) and its App Settings row.
|
||||
'Toggle Chat / Terminal View': '切换聊天 / 终端视图',
|
||||
Chat: '聊天',
|
||||
'Open terminal': '打开终端',
|
||||
Conversation: '对话',
|
||||
'Session view': '会话视图',
|
||||
'Show the conversation (Alt+Shift+C)': '显示对话 (Alt+Shift+C)',
|
||||
'Show the terminal (Alt+Shift+C)': '显示终端 (Alt+Shift+C)',
|
||||
'No messages yet.': '还没有消息。',
|
||||
'Open Claude sessions in Chat view': '以聊天视图打开 Claude 会话',
|
||||
"Show a session's conversation rendered as text instead of the terminal. Each session remembers its own choice, and Alt+Shift+C or the Chat / Terminal switch changes it. Not on phones.":
|
||||
'以渲染后的文本显示会话的对话,代替终端。每个会话记住自己的选择,可用 Alt+Shift+C 或聊天 / 终端开关切换。手机上不可用。',
|
||||
'Show the Chat / Terminal switch': '显示聊天 / 终端开关',
|
||||
'Show the Chat / Terminal switch at the top right of a Claude session. Alt+Shift+C switches views without it. Not on phones.':
|
||||
'在 Claude 会话右上角显示聊天 / 终端开关。没有它时,Alt+Shift+C 也能切换视图。手机上不可用。',
|
||||
'Copy Selection': '复制选中内容',
|
||||
'Copy Selection (interrupts when nothing is selected)': '复制选中内容(无选中内容时中断)',
|
||||
'Focus Tabs': '聚焦标签页',
|
||||
@@ -244,6 +259,12 @@
|
||||
'No response yet — send a message in this session first.': '暂无回复,请先在此会话中发送一条消息。',
|
||||
'No full conversation history available for this session': '此会话没有可显示的完整对话历史',
|
||||
'Last Response': '最近一次回复',
|
||||
'Response files': '回复中的文件',
|
||||
'Open Codex response files': '打开 Codex 回复中的文件',
|
||||
'Dock preview': '停靠预览',
|
||||
'No previewable files in the latest response.': '最新回复中没有可预览的文件。',
|
||||
'Unable to load response files': '无法加载回复中的文件',
|
||||
'Discard unsaved changes?': '放弃未保存的更改?',
|
||||
More: '更多',
|
||||
'Copy Markdown': '复制 Markdown',
|
||||
'Copy response as Markdown': '将回复复制为 Markdown',
|
||||
@@ -481,6 +502,9 @@
|
||||
'CPU MHz': 'CPU 频率',
|
||||
'Lifecycle Log': '生命周期日志',
|
||||
'Response Viewer': '回复查看器',
|
||||
'Codex files': 'Codex 文件',
|
||||
'Codex sessions: underlined file names and Codex sidebar file tabs open in the preview, a Response files header button, and a Dock control on file previews':
|
||||
'Codex 会话:在预览中打开带下划线的文件名和 Codex 侧边栏文件标签、标题栏的回复中的文件按钮,以及文件预览上的停靠控件',
|
||||
'Attachments Button': '附件按钮',
|
||||
'Multi-monitor Button': '多显示器按钮',
|
||||
'Session Manager Button': '会话管理器按钮',
|
||||
@@ -751,6 +775,13 @@
|
||||
'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': '自动复制:已复制选中内容',
|
||||
@@ -1159,6 +1190,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': '返回工作树',
|
||||
@@ -1702,12 +1743,22 @@
|
||||
|
||||
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} 个任务`],
|
||||
[/^(\d+) running$/, (_m, count) => `${count} 个运行中`],
|
||||
[/^(\d+) active$/, (_m, count) => `${count} 个活动`],
|
||||
[/^Show (\d+) more$/, (_m, count) => `再显示 ${count} 项`],
|
||||
// Chat view (chat-view.js).
|
||||
[/^Show all \((\d+) lines?\)$/, (_m, count) => `显示全部(${count} 行)`],
|
||||
[/^Show (\d+) more \((\d+) remaining\)$/, (_m, count, remaining) => `再显示 ${count} 项(剩余 ${remaining} 项)`],
|
||||
[/^Lifetime: (\d+) sessions created$/, (_m, count) => `累计已创建 ${count} 个会话`],
|
||||
[/^Tunnel active: (.+)$/, (_m, url) => `隧道已启用:${url}`],
|
||||
@@ -1807,8 +1858,12 @@
|
||||
(_m, name, why) => `案例“${name}”的选项已保存到本设备(同步前有效),但未保存到服务器:${ZH_CN[why] || why}`,
|
||||
],
|
||||
// A dialog read off a hook-less CLI's screen (src/web/screen-blocked.ts), as the
|
||||
// notification drawer shows it. The CLI's label passes through.
|
||||
[/^(.+) is waiting for your answer in the terminal$/, (_m, cli) => `${cli} 正在终端中等待你的回答`],
|
||||
// notification drawer shows it, and the chat view's notice, which ends in a period.
|
||||
// The agent's label passes through.
|
||||
[
|
||||
/^(.+) is waiting for your answer in the terminal(\.?)$/,
|
||||
(_m, who, dot) => `${who} 正在终端中等待你的回答${dot ? '。' : ''}`,
|
||||
],
|
||||
[/^The agent exited \(signal (\d+)\)$/, (_m, signal) => `智能体已退出(信号 ${signal})`],
|
||||
// A session header's harness logo (tile grid, split pane): "<harness> · <model>",
|
||||
// and where the model came from when the CLI did not report it. The harness
|
||||
|
||||
@@ -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 &&
|
||||
@@ -303,7 +306,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
const ext = (file.name || '').toLowerCase().match(/\.([a-z0-9]+)$/)?.[1] || '';
|
||||
if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'heic', 'heif'].includes(ext)) return 'image';
|
||||
if (['mp4', 'webm', 'mov', 'm4v', 'ogv'].includes(ext)) return 'video';
|
||||
if (['pdf', 'docx', 'pptx', 'xlsx', 'zip', 'txt', 'md', 'csv', 'tsv', 'json', 'log', 'yaml', 'yml', 'xml'].includes(ext)) {
|
||||
if (['pdf', 'docx', 'pptx', 'xlsx', 'zip', 'txt', 'md', 'csv', 'tsv', 'json', 'log', 'yaml', 'yml', 'xml', 'html', 'htm'].includes(ext)) {
|
||||
return 'document';
|
||||
}
|
||||
return null;
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
|
||||
@@ -206,6 +206,7 @@
|
||||
</div>
|
||||
<button class="btn-icon-header btn-redraw-terminal btn-redraw-terminal--hidden" onclick="app.restoreTerminalSize()" title="Redraw terminal to fit current screen (Ctrl+Shift+R)" aria-label="Redraw terminal"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="1 4 1 10 7 10"/><polyline points="23 20 23 14 17 14"/><path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"/></svg></button>
|
||||
<button class="btn-icon-header btn-response-viewer-header btn-response-viewer-header--hidden" onclick="app.toggleResponseViewer()" title="View last response" aria-label="View last response"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></button>
|
||||
<button id="responseFilesBtn" type="button" class="btn-icon-header btn-response-files btn-response-files--hidden" onclick="app.toggleResponseViewer(true)" title="Response files" aria-label="Open Codex response files" hidden><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6M8 13h8m-8 4h6"/></svg></button>
|
||||
<button class="btn-icon-header btn-away-digest btn-away-digest--hidden" onclick="app.openAwayDigest()" title="Away Digest" aria-label="Open away digest"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 6h13"/><path d="M8 12h13"/><path d="M8 18h13"/><path d="M3 6h.01"/><path d="M3 12h.01"/><path d="M3 18h.01"/></svg></button>
|
||||
<button class="btn-icon-header btn-session-manager btn-session-manager--hidden" onclick="app.openSessionManager()" title="Session Manager" aria-label="Open session manager"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></svg></button>
|
||||
<button class="btn-icon-header btn-approvals btn-approvals--hidden" id="approvalsBtn" onclick="app.toggleApprovalsInbox()" title="Approvals waiting on you" aria-label="Open approvals inbox" aria-expanded="false">
|
||||
@@ -640,7 +641,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>
|
||||
@@ -696,6 +697,7 @@
|
||||
<button class="btn-icon-sm file-preview-edit-btn" id="filePreviewEditBtn" onclick="app.enterFilePreviewEdit()" title="Edit file" aria-label="Edit file" hidden><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5z"/></svg></button>
|
||||
<button class="btn-icon-sm" onclick="app.copyFilePreviewContent()" title="Copy content">⎘</button>
|
||||
<button class="btn-icon-sm" id="filePreviewDetachBtn" onclick="app.detachFilePreview()" title="Open in new tab" aria-label="Open in new tab" hidden><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg></button>
|
||||
<button type="button" class="btn-icon-sm" id="filePreviewDockBtn" hidden onclick="app.toggleFilePreviewDock()" title="Dock preview" aria-label="Dock preview" aria-pressed="false"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M15 4v16"/></svg></button>
|
||||
<button class="btn-icon-sm" id="filePreviewExpandBtn" onclick="app.toggleFilePreviewExpanded()" title="Expand" aria-label="Expand" aria-pressed="false"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg></button>
|
||||
<button class="btn-icon-sm" onclick="app.closeFilePreview()" title="Close">×</button>
|
||||
</div>
|
||||
@@ -735,12 +737,12 @@
|
||||
<div class="response-viewer-actions">
|
||||
<button class="response-viewer-more" id="responseViewerMore" onclick="app.loadFullContext()">More</button>
|
||||
<button class="response-viewer-more response-viewer-copy-markdown" id="responseViewerCopyMarkdown" type="button" onclick="app.copyResponseViewerMarkdown()" title="Copy response as Markdown">Copy Markdown</button>
|
||||
<button class="response-viewer-close" onclick="app.toggleResponseViewer()">×</button>
|
||||
<button class="response-viewer-close" onclick="app.closeResponseViewer()">×</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="response-viewer-body" id="responseViewerBody"></div>
|
||||
</div>
|
||||
<div class="response-viewer-backdrop" id="responseViewerBackdrop" onclick="app.toggleResponseViewer()"></div>
|
||||
<div class="response-viewer-backdrop" id="responseViewerBackdrop" onclick="app.closeResponseViewer()"></div>
|
||||
|
||||
<!-- Bottom Toolbar -->
|
||||
<footer class="toolbar">
|
||||
@@ -870,7 +872,7 @@
|
||||
<path d="m21 15-5-5L5 21"/>
|
||||
</svg>
|
||||
</button>
|
||||
<input type="file" class="btn-attach-mobile-input" id="attachFileInput" accept="image/*,video/*,.pdf,.docx,.pptx,.xlsx,.zip,.txt,.md,.csv,.tsv,.json,.log,.yaml,.yml,.xml" multiple tabindex="-1" aria-hidden="true">
|
||||
<input type="file" class="btn-attach-mobile-input" id="attachFileInput" accept="image/*,video/*,.pdf,.docx,.pptx,.xlsx,.zip,.txt,.md,.csv,.tsv,.json,.log,.yaml,.yml,.xml,.html,.htm" multiple tabindex="-1" aria-hidden="true">
|
||||
</span>
|
||||
<button class="btn-voice-mobile" id="voiceInputBtnMobile" onclick="VoiceInput.toggle()"
|
||||
title="Voice input" aria-label="Start voice input" aria-pressed="false">
|
||||
@@ -2161,6 +2163,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>
|
||||
@@ -2239,13 +2248,14 @@
|
||||
<div class="set-group-head"><h4>Header buttons</h4><span class="set-scope">device</span></div>
|
||||
<p class="set-group-hint">Tap to show a control in the header. Multi-monitor is the one entry here that syncs across devices.</p>
|
||||
<div class="set-group-body">
|
||||
<div class="set-chips" data-search="header buttons plan usage font stats lifecycle response file viewer attachments monitor session away cron redraw split tiles">
|
||||
<div class="set-chips" data-search="header buttons plan usage font stats lifecycle response codex files file viewer attachments monitor session away cron redraw split tiles">
|
||||
<label class="set-chip" data-preview="header" data-preview-order="1" data-preview-text="A+"><input type="checkbox" id="appSettingsShowFontControls"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 20 10 5l6 15"/><path d="M6.5 15h7"/><path d="M18 12h4M20 10v4"/></svg><span>Font Size</span></label>
|
||||
<label class="set-chip" data-preview="header" data-preview-order="2" data-preview-text="CPU 12%"><input type="checkbox" id="appSettingsShowSystemStats" checked><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 12h4l2.5-7 4 14L16 12h5"/></svg><span>System Stats</span></label>
|
||||
<label class="set-chip" data-preview="header" data-preview-order="2" data-preview-text="GPU 8%"><input type="checkbox" id="appSettingsShowGpuStats"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="7" width="18" height="10" rx="2"/><path d="M7 21v-4M12 21v-4M17 21v-4M7 7V3M17 7V3"/></svg><span>GPU Stats</span></label>
|
||||
<label class="set-chip" data-preview="header" data-preview-order="2" data-preview-text="3400 MHz"><input type="checkbox" id="appSettingsShowCpuMhz"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg><span>CPU MHz</span></label>
|
||||
<label class="set-chip" data-preview="header" data-preview-order="3"><input type="checkbox" id="appSettingsShowRedrawButton"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="1 4 1 10 7 10"/><polyline points="23 20 23 14 17 14"/><path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"/></svg><span>Redraw Terminal</span></label>
|
||||
<label class="set-chip" data-preview="header" data-preview-order="4"><input type="checkbox" id="appSettingsShowResponseViewer"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg><span>Response Viewer</span></label>
|
||||
<label class="set-chip" data-search="codex files response files sidebar file tabs dock preview" data-preview="header" data-preview-order="4.5" title="Codex sessions: underlined file names and Codex sidebar file tabs open in the preview, a Response files header button, and a Dock control on file previews"><input type="checkbox" id="appSettingsCodexFilePreviews"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6M8 13h8m-8 4h6"/></svg><span>Codex files</span></label>
|
||||
<label class="set-chip" data-preview="header" data-preview-order="5"><input type="checkbox" id="appSettingsShowAwayDigestButton"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 6h13"/><path d="M8 12h13"/><path d="M8 18h13"/><path d="M3 6h.01"/><path d="M3 12h.01"/><path d="M3 18h.01"/></svg><span>Away Digest</span></label>
|
||||
<label class="set-chip" data-preview="header" data-preview-order="6"><input type="checkbox" id="appSettingsShowSessionButton"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></svg><span>Session Manager</span></label>
|
||||
<label class="set-chip" data-preview="header" data-preview-order="9"><input type="checkbox" id="appSettingsShowAttachmentsButton"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg><span>Attachments</span></label>
|
||||
@@ -2280,6 +2290,20 @@
|
||||
<label class="set-chip" data-preview="panel" data-preview-order="3"><input type="checkbox" id="appSettingsShowFileBrowser"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg><span>File Browser</span></label>
|
||||
<label class="set-chip" data-preview="panel" data-preview-order="4"><input type="checkbox" id="appSettingsShowSubagents"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/><circle cx="18" cy="12" r="2.5"/><path d="M8.2 7.2 15.6 11M8.2 16.8 15.6 13"/></svg><span>Subagents</span></label>
|
||||
</div>
|
||||
<div class="set-row" data-search="chat view conversation rendered markdown terminal default claude sessions readable">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">Open Claude sessions in Chat view</span>
|
||||
<span class="set-row-desc">Show a session's conversation rendered as text instead of the terminal. Each session remembers its own choice, and Alt+Shift+C or the Chat / Terminal switch changes it. Not on phones.</span>
|
||||
</div>
|
||||
<label class="switch switch-sm"><input type="checkbox" id="appSettingsChatViewDefault"><span class="slider"></span></label>
|
||||
</div>
|
||||
<div class="set-row" data-search="chat view terminal switch toggle button show hide claude sessions">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">Show the Chat / Terminal switch</span>
|
||||
<span class="set-row-desc">Show the Chat / Terminal switch at the top right of a Claude session. Alt+Shift+C switches views without it. Not on phones.</span>
|
||||
</div>
|
||||
<label class="switch switch-sm"><input type="checkbox" id="appSettingsShowChatViewSwitch"><span class="slider"></span></label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -4547,6 +4571,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. -->
|
||||
@@ -4578,6 +4603,7 @@
|
||||
<script defer src="git-status-ui.js"></script>
|
||||
<script defer src="edit-history-ui.js"></script>
|
||||
<script defer src="local-model-ui.js"></script>
|
||||
<script defer src="chat-view.js"></script>
|
||||
<script defer src="entrance-animations.js"></script>
|
||||
<script defer src="api-client.js"></script>
|
||||
<script defer src="subagent-windows.js"></script>
|
||||
|
||||
+76
-29
@@ -17,10 +17,10 @@
|
||||
* 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 (_owner): clear() stashes it under that session and
|
||||
* restoreDraft() brings it back when the session is shown again, except a
|
||||
* clear({ discard: true }) (the keyboard bar's clear-line key), which throws
|
||||
* it away.
|
||||
* 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
|
||||
*
|
||||
@@ -65,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;
|
||||
@@ -88,10 +91,10 @@ const CjkInput = (() => {
|
||||
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 the field's text belongs to (the one last shown,
|
||||
// set by restoreDraft). clear() stashes a held draft under it, so every path
|
||||
// that drops the active session before the next cleanup (goHome, the tile
|
||||
// grid's _replaceTileGrid and _onTileAdoptedElsewhere) keeps the answer.
|
||||
// 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 = {};
|
||||
|
||||
@@ -195,8 +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.
|
||||
@@ -236,7 +252,7 @@ const CjkInput = (() => {
|
||||
const val = _strip(_textarea.value);
|
||||
_t(`flush ${val ? 'send len=' + val.length : 'empty'}`);
|
||||
if (val) {
|
||||
_send(val);
|
||||
_send(val, _targetForSend());
|
||||
}
|
||||
_resetToPhantom();
|
||||
}
|
||||
@@ -273,14 +289,15 @@ const CjkInput = (() => {
|
||||
* (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 was refused
|
||||
* (too long, no session), so the field keeps it. */
|
||||
function _sendHeld(val) {
|
||||
* 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) !== false;
|
||||
return _sendPrompt(val, sessionId) !== false;
|
||||
}
|
||||
|
||||
/** Enter: send what the field holds (or a bare Enter when it is empty) and
|
||||
@@ -296,11 +313,11 @@ const CjkInput = (() => {
|
||||
if (_hold && !val.trim()) val = '';
|
||||
if (_hold && val) {
|
||||
// Refused (too long, no session): keep the text so nothing is lost.
|
||||
if (!_sendHeld(val)) return false;
|
||||
if (!_sendHeld(val, _targetForSend())) return false;
|
||||
} else if (val) {
|
||||
_send(val + '\r');
|
||||
_send(val + '\r', _targetForSend());
|
||||
} else {
|
||||
_send('\r');
|
||||
_send('\r', _targetForSend());
|
||||
}
|
||||
_resetToPhantom();
|
||||
if (_hold) _autoGrow();
|
||||
@@ -336,10 +353,17 @@ const CjkInput = (() => {
|
||||
return;
|
||||
}
|
||||
_t('hold ctrl key');
|
||||
_textarea.value = PHANTOM + before;
|
||||
_textarea.setSelectionRange(1 + at, 1 + at);
|
||||
_heldBase = before;
|
||||
_send(now[at]);
|
||||
// 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.
|
||||
@@ -353,7 +377,7 @@ const CjkInput = (() => {
|
||||
const wasEmpty = !_heldBase;
|
||||
_heldBase = _strip(_textarea.value);
|
||||
if (!_heldBase) {
|
||||
if (wasEmpty) _send('\x7f');
|
||||
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
|
||||
@@ -397,11 +421,12 @@ const CjkInput = (() => {
|
||||
}
|
||||
|
||||
return {
|
||||
init({ send, sendPrompt = null }) {
|
||||
init({ send, sendPrompt = null, captureTarget }) {
|
||||
if (_initialized) this.destroy();
|
||||
|
||||
_send = send;
|
||||
_sendPrompt = sendPrompt;
|
||||
_captureTarget = captureTarget;
|
||||
_composing = false;
|
||||
_printableKeydownAt = null;
|
||||
_flushTimer = null;
|
||||
@@ -461,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();
|
||||
@@ -515,7 +541,7 @@ const CjkInput = (() => {
|
||||
// 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;
|
||||
}
|
||||
|
||||
@@ -527,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;
|
||||
}
|
||||
@@ -539,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;
|
||||
}
|
||||
|
||||
@@ -554,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;
|
||||
}
|
||||
@@ -565,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
|
||||
@@ -591,7 +619,7 @@ const CjkInput = (() => {
|
||||
if (_composing) return;
|
||||
if (_isEffectivelyEmpty()) {
|
||||
_cancelDebouncedFlush();
|
||||
_send('\x7f');
|
||||
_send('\x7f', _targetForSend());
|
||||
_resetToPhantom();
|
||||
return;
|
||||
}
|
||||
@@ -640,6 +668,15 @@ 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
|
||||
@@ -653,13 +690,15 @@ const CjkInput = (() => {
|
||||
// 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.
|
||||
if (_hold && _owner) {
|
||||
const sessionId = _hasTarget && _target ? _target : _owner;
|
||||
if (_hold && sessionId) {
|
||||
const draft = _strip(_textarea.value);
|
||||
if (draft.trim()) _drafts.set(_owner, draft);
|
||||
if (draft.trim()) _drafts.set(sessionId, draft);
|
||||
}
|
||||
_owner = null;
|
||||
}
|
||||
@@ -748,6 +787,7 @@ const CjkInput = (() => {
|
||||
* 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
|
||||
@@ -771,6 +811,10 @@ const CjkInput = (() => {
|
||||
_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();
|
||||
},
|
||||
|
||||
@@ -802,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;
|
||||
},
|
||||
|
||||
@@ -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
|
||||
@@ -1535,7 +1564,7 @@ const KeyboardAccessoryBar = {
|
||||
<button type="button" class="paste-cancel">Cancel</button>
|
||||
<button type="button" class="paste-send">Send</button>
|
||||
</div>
|
||||
<input type="file" class="paste-file-input" accept="image/*,video/*,.pdf,.docx,.pptx,.xlsx,.zip,.txt,.md,.csv,.tsv,.json,.log,.yaml,.yml,.xml" multiple hidden>
|
||||
<input type="file" class="paste-file-input" accept="image/*,video/*,.pdf,.docx,.pptx,.xlsx,.zip,.txt,.md,.csv,.tsv,.json,.log,.yaml,.yml,.xml,.html,.htm" multiple hidden>
|
||||
</div>
|
||||
`;
|
||||
|
||||
@@ -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');
|
||||
@@ -1753,7 +1786,7 @@ const KeyboardAccessoryBar = {
|
||||
<button class="paste-cancel">Cancel</button>
|
||||
<button class="paste-send">Send</button>
|
||||
</div>
|
||||
<input type="file" class="paste-file-input" accept="image/*,video/*,.pdf,.docx,.pptx,.xlsx,.zip,.txt,.md,.csv,.tsv,.json,.log,.yaml,.yml,.xml" multiple hidden>
|
||||
<input type="file" class="paste-file-input" accept="image/*,video/*,.pdf,.docx,.pptx,.xlsx,.zip,.txt,.md,.csv,.tsv,.json,.log,.yaml,.yml,.xml,.html,.htm" multiple hidden>
|
||||
</div>
|
||||
`;
|
||||
|
||||
@@ -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();
|
||||
@@ -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,
|
||||
|
||||
@@ -593,6 +593,9 @@ html.mobile-init .file-browser-panel {
|
||||
.btn-icon-header.btn-session-manager,
|
||||
/* Edit history: a desktop panel; phones never show the button (opt-in, default OFF anyway). */
|
||||
.btn-icon-header.btn-edit-history,
|
||||
/* Response files: the phone header keeps one opt-in button (File Viewer), so
|
||||
this stays off phones even with the Codex files setting on. */
|
||||
.btn-icon-header.btn-response-files,
|
||||
/* Approvals bell: phones answer from the overview's NEEDS YOU rows instead
|
||||
(inline approve/deny in mobile-overview.js); the bell would only crowd the
|
||||
header it was designed to stay out of. */
|
||||
@@ -1039,15 +1042,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 */
|
||||
|
||||
+331
-15
@@ -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();
|
||||
@@ -3760,6 +4021,56 @@ Object.assign(CodemanApp.prototype, {
|
||||
if (headerBtn) headerBtn.setAttribute('aria-expanded', 'false');
|
||||
},
|
||||
|
||||
_setFilePreviewDocked(dock) {
|
||||
const overlay = this.$('filePreviewOverlay');
|
||||
if (!overlay) return;
|
||||
const terminalWrap = this.$('terminalContainer')?.closest('.terminal-wrap');
|
||||
// Docking is one of the Codex files extras (_codexFilePreviewsEnabled, app.js): with the
|
||||
// setting off a preview only ever floats. Undocking is always allowed.
|
||||
dock = Boolean(
|
||||
dock &&
|
||||
this._codexFilePreviewsEnabled?.() &&
|
||||
terminalWrap?.parentElement?.matches('.main:not(.tiles-active, .webview-active)') &&
|
||||
window.matchMedia?.('(min-width: 1180px)').matches
|
||||
);
|
||||
if (dock === overlay.classList.contains('is-docked')) return;
|
||||
if (dock) {
|
||||
if (!overlay.parentElement) return;
|
||||
this._filePreviewOverlayHome = overlay.parentElement;
|
||||
terminalWrap.after(overlay);
|
||||
} else {
|
||||
this._filePreviewOverlayHome?.append(overlay);
|
||||
this._filePreviewOverlayHome = null;
|
||||
}
|
||||
overlay.classList.toggle('is-docked', dock);
|
||||
this.$('filePreviewDockBtn')?.setAttribute('aria-pressed', String(dock));
|
||||
},
|
||||
|
||||
_isFilePreviewDocked() {
|
||||
const overlay = this.$('filePreviewOverlay');
|
||||
return (
|
||||
overlay?.classList.contains('is-docked') &&
|
||||
overlay.parentElement?.matches('.main:not(.tiles-active, .webview-active)') &&
|
||||
window.matchMedia?.('(min-width: 1180px)').matches
|
||||
);
|
||||
},
|
||||
|
||||
toggleFilePreviewDock() {
|
||||
const overlay = this.$('filePreviewOverlay');
|
||||
if (!overlay?.classList.contains('visible')) return;
|
||||
this._setFilePreviewDocked(!overlay.classList.contains('is-docked'));
|
||||
},
|
||||
|
||||
_maybeCloseDockedFilePreviewOnEscape(event) {
|
||||
const overlay = this.$('filePreviewOverlay');
|
||||
if (!this._isFilePreviewDocked() || !overlay?.classList.contains('visible') || !overlay.contains(event.target)) return false;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
this.closeFilePreview();
|
||||
if (!overlay.classList.contains('visible')) this.terminal?.focus();
|
||||
return true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Whether a path is absolute and provably OUTSIDE this session's workspace.
|
||||
*
|
||||
@@ -3866,6 +4177,9 @@ Object.assign(CodemanApp.prototype, {
|
||||
|
||||
if (!overlay || !bodyEl) return;
|
||||
|
||||
const dockBtn = this.$('filePreviewDockBtn');
|
||||
if (dockBtn) dockBtn.hidden = !this._codexFilePreviewsEnabled?.();
|
||||
if (options.dock) this._setFilePreviewDocked?.(true);
|
||||
this._recordFilePreviewHistory(filePath, sessionId, attachmentId, options);
|
||||
this._bindFilePreviewChrome();
|
||||
|
||||
@@ -4396,6 +4710,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
if (ev.key !== 'ArrowLeft' && ev.key !== 'ArrowRight') return;
|
||||
if (!this.$('filePreviewOverlay')?.classList.contains('visible')) return;
|
||||
const t = ev.target;
|
||||
if (this._isFilePreviewDocked?.() && !this.$('filePreviewOverlay')?.contains(t)) return;
|
||||
if (t && (t.isContentEditable || (/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName) && !t.classList?.contains('xterm-helper-textarea')))) return;
|
||||
// Swallowed even at the ends of the list: otherwise the terminal behind the overlay
|
||||
// types it as word-left/right, and on a header button the browser's own Alt+← goes Back.
|
||||
@@ -4526,6 +4841,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
const overlay = this.$('filePreviewOverlay');
|
||||
if (overlay) {
|
||||
overlay.classList.remove('visible');
|
||||
this._setFilePreviewDocked?.(false);
|
||||
}
|
||||
// The overlay is hidden with display:none, which stops it being PAINTED and
|
||||
// nothing else: a <video>/<audio> inside it keeps playing, keeps its audio
|
||||
|
||||
@@ -2070,18 +2070,8 @@ 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;
|
||||
// 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.
|
||||
@@ -2092,14 +2082,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
CjkInput.submit?.();
|
||||
return;
|
||||
}
|
||||
const coreService = this.terminal?._core?.coreService;
|
||||
if (coreService && typeof coreService.triggerDataEvent === 'function') {
|
||||
coreService.triggerDataEvent('\r', true);
|
||||
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() {
|
||||
|
||||
@@ -605,6 +605,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
// in the template, so an unchecked box and a hidden button stay consistent).
|
||||
document.getElementById('appSettingsShowSessionButton').checked = settings.showSessionButton ?? defaults.showSessionButton ?? false;
|
||||
document.getElementById('appSettingsShowAwayDigestButton').checked = settings.showAwayDigestButton ?? defaults.showAwayDigestButton ?? false;
|
||||
// Codex files (Response files button, sidebar file tabs, Dock): per-device, default OFF.
|
||||
document.getElementById('appSettingsCodexFilePreviews').checked = settings.codexFilePreviewsEnabled ?? defaults.codexFilePreviewsEnabled ?? false;
|
||||
document.getElementById('appSettingsShowCronButton').checked = settings.showCronButton ?? defaults.showCronButton ?? false;
|
||||
document.getElementById('appSettingsShowGitStatus').checked = settings.showGitStatus ?? defaults.showGitStatus ?? false;
|
||||
document.getElementById('appSettingsGitStatusTree').checked = settings.gitStatusTree ?? defaults.gitStatusTree ?? true;
|
||||
@@ -616,6 +618,9 @@ Object.assign(CodemanApp.prototype, {
|
||||
document.getElementById('appSettingsGitFetchEnabled').checked = settings.gitFetchEnabled === true;
|
||||
document.getElementById('appSettingsGitFetchIntervalSeconds').value = settings.gitFetchIntervalSeconds ?? 300;
|
||||
document.getElementById('appSettingsShowEditHistory').checked = settings.showEditHistory ?? defaults.showEditHistory ?? false;
|
||||
document.getElementById('appSettingsChatViewDefault').checked = settings.chatViewDefault === true;
|
||||
// Absent means ON: the switch shows until this device turns it off.
|
||||
document.getElementById('appSettingsShowChatViewSwitch').checked = settings.showChatViewSwitch === true;
|
||||
// Gesture control lives in the Input section (alongside Local Echo / CJK Input)
|
||||
// but is only available when the instance runs with CODEMAN_GESTURE=1 (server sets
|
||||
// window.__codemanGestureAvailable). Hide just this item otherwise so the toggle
|
||||
@@ -648,6 +653,8 @@ 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;
|
||||
@@ -3163,6 +3170,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
spawnedTabsFollowParent: document.getElementById('appSettingsSpawnedTabsFollowParent').checked,
|
||||
showSessionButton: document.getElementById('appSettingsShowSessionButton').checked,
|
||||
showAwayDigestButton: document.getElementById('appSettingsShowAwayDigestButton').checked,
|
||||
codexFilePreviewsEnabled: document.getElementById('appSettingsCodexFilePreviews').checked,
|
||||
showCronButton: document.getElementById('appSettingsShowCronButton').checked,
|
||||
showGitStatus: document.getElementById('appSettingsShowGitStatus').checked,
|
||||
gitStatusTree: document.getElementById('appSettingsGitStatusTree').checked,
|
||||
@@ -3177,6 +3185,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
Math.max(30, parseInt(document.getElementById('appSettingsGitFetchIntervalSeconds').value, 10) || 300)
|
||||
),
|
||||
showEditHistory: document.getElementById('appSettingsShowEditHistory').checked,
|
||||
chatViewDefault: document.getElementById('appSettingsChatViewDefault').checked,
|
||||
showChatViewSwitch: document.getElementById('appSettingsShowChatViewSwitch').checked,
|
||||
gestureControlEnabled: document.getElementById('appSettingsGestureControl').checked,
|
||||
subagentTrackingEnabled: document.getElementById('appSettingsSubagentTracking').checked,
|
||||
subagentActiveTabOnly: document.getElementById('appSettingsSubagentActiveTabOnly').checked,
|
||||
@@ -3196,6 +3206,7 @@ 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,
|
||||
@@ -3285,6 +3296,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);
|
||||
|
||||
@@ -3405,6 +3417,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
this._updateTokensImmediate(); // Re-render token display (picks up showCost change)
|
||||
this.applyMonitorVisibility();
|
||||
this.renderApprovals?.(); // Approvals Inbox toggle (hide/show bell + drawer)
|
||||
this._chatViewSync?.(); // Chat view default and the Chat / Terminal switch's visibility
|
||||
this.renderProjectInsightsPanel(); // Re-render to apply visibility setting
|
||||
this.updateSubagentWindowVisibility(); // Apply subagent window visibility setting
|
||||
|
||||
@@ -3459,6 +3472,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
|
||||
@@ -3480,6 +3494,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
// SettingsUpdateSchema (.strict()), so sending them would 400 the PUT.
|
||||
showSessionButton: _ssb,
|
||||
showAwayDigestButton: _adb,
|
||||
// Codex files extras (app.js _codexFilePreviewsEnabled): per-device, absent from the .strict() schema.
|
||||
codexFilePreviewsEnabled: _cfp,
|
||||
showCronButton: _crb,
|
||||
// Per-device bottom-bar indicator, absent from SettingsUpdateSchema (.strict()): it must not reach the PUT.
|
||||
showGitStatus: _sgs,
|
||||
@@ -3491,6 +3507,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
gitStatusTimeoutSeconds: _gst2,
|
||||
// Per-device header button (edit-history-ui.js), likewise absent from the .strict() schema.
|
||||
showEditHistory: _seh,
|
||||
// Which view a session opens in (chat-view.js): per-device, absent from the .strict() schema.
|
||||
chatViewDefault: _cvd,
|
||||
// Whether the Chat / Terminal switch shows (chat-view.js): per-device, absent from the .strict() schema.
|
||||
showChatViewSwitch: _scvs,
|
||||
showTabDetachButton: _tdb,
|
||||
showTabNewButton: _tnb,
|
||||
// Detach Tiles: what a tile drag does is a property of this device's
|
||||
@@ -4179,8 +4199,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
/** Keep the launch surfaces in sync with Settings mutations without a reload. */
|
||||
_syncCliLaunchCatalog() {
|
||||
if (!Array.isArray(this._cliList) || this._cliList.length === 0) return;
|
||||
// /api/clis rows carry no capabilities, so keep the served catalog's `external`
|
||||
// (isExternalCliSession() reads it). A new custom CLI has none and falls back to `kind`.
|
||||
// /api/clis rows carry no capabilities, so retain them from the served catalog.
|
||||
const previous = new Map(
|
||||
(Array.isArray(window.__codemanCliCatalog) ? window.__codemanCliCatalog : []).map((cli) => [cli.id, cli])
|
||||
);
|
||||
@@ -4191,6 +4210,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
order: cli.order,
|
||||
kind: cli.kind,
|
||||
external: previous.get(cli.id)?.external,
|
||||
transcript: previous.get(cli.id)?.transcript,
|
||||
enabled: cli.enabled,
|
||||
available: cli.kind === 'shell' || (cli.enabled && cli.installed),
|
||||
}));
|
||||
@@ -4484,6 +4504,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
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',
|
||||
};
|
||||
@@ -4842,6 +4863,15 @@ Object.assign(CodemanApp.prototype, {
|
||||
awayDigestBtn.classList.toggle('btn-away-digest--hidden', !showAwayDigestButton);
|
||||
}
|
||||
|
||||
// Codex files (Response files button, sidebar file tabs, Dock) — opt-in, hidden by default.
|
||||
// Switching it off takes a docked preview back to floating. The Dock button follows the
|
||||
// setting here too, not only when a preview opens: with a preview open, switching the setting
|
||||
// off would otherwise leave a Dock button that does nothing, and on would show none.
|
||||
this._syncResponseFilesButton?.();
|
||||
const filePreviewDockBtn = document.getElementById('filePreviewDockBtn');
|
||||
if (filePreviewDockBtn) filePreviewDockBtn.hidden = !this._codexFilePreviewsEnabled?.();
|
||||
if (!this._codexFilePreviewsEnabled?.()) this._setFilePreviewDocked?.(false);
|
||||
|
||||
// Cron button (footer toolbar) — opt-in, hidden by default. Same marker pattern.
|
||||
const showCronButton = settings.showCronButton ?? defaults.showCronButton ?? false;
|
||||
const cronBtn = document.querySelector('.btn-cron');
|
||||
@@ -5216,8 +5246,9 @@ Object.assign(CodemanApp.prototype, {
|
||||
'terminalFontFamily', 'terminalFontWeight', 'terminalFontWeightBold',
|
||||
'language',
|
||||
'terminalWheelLocalScrollback',
|
||||
'historyReloadAction',
|
||||
'autoCopySelection', 'copyStripMargin',
|
||||
'showSessionButton', 'showAwayDigestButton', 'showCronButton', 'showGitStatus', 'gitStatusTree', 'gitStatusMaxRepos', 'gitStatusTimeoutSeconds', 'showEditHistory',
|
||||
'showSessionButton', 'showAwayDigestButton', 'codexFilePreviewsEnabled', 'showCronButton', 'showGitStatus', 'gitStatusTree', 'gitStatusMaxRepos', 'gitStatusTimeoutSeconds', 'showEditHistory', 'chatViewDefault', 'showChatViewSwitch',
|
||||
'showTabDetachButton',
|
||||
'showTabNewButton',
|
||||
'mobileOverviewEnabled',
|
||||
|
||||
+364
-1
@@ -4399,6 +4399,9 @@ html[data-tab-logos='off'] .home-sessions-harness {
|
||||
overflow: hidden;
|
||||
/* Anchor for the partial-history banner, which overlays rather than stacks. */
|
||||
position: relative;
|
||||
/* Keeps the chat view's layers (20 and 21) inside the terminal area, so the
|
||||
narrow-width session sidebar drawer (z-index 12, mobile.css) stays above them. */
|
||||
isolation: isolate;
|
||||
}
|
||||
|
||||
/* Partial-history banner (#258).
|
||||
@@ -11803,6 +11806,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;
|
||||
@@ -11923,6 +11956,63 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
|
||||
display: flex;
|
||||
}
|
||||
|
||||
#filePreviewDockBtn {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Hidden while the Codex files setting is off (panels-ui.js openFilePreview). */
|
||||
#filePreviewDockBtn[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
@media (min-width: 1180px) {
|
||||
html {
|
||||
--file-preview-dock-width: clamp(400px, 35vw, 620px);
|
||||
}
|
||||
|
||||
body:has(.main:not(.tiles-active, .webview-active) > .terminal-wrap) #filePreviewDockBtn {
|
||||
display: inline-flex;
|
||||
}
|
||||
|
||||
.main:not(.tiles-active, .webview-active) > .file-preview-overlay.is-docked {
|
||||
position: relative;
|
||||
/* The floating overlay's 5100 would, with nothing above it making a stacking
|
||||
context, put a docked pane over every modal (1000+) and the response viewer
|
||||
(5000). Docked, it is page content beside the terminal. */
|
||||
z-index: auto;
|
||||
inset: auto;
|
||||
flex: 0 0 var(--file-preview-dock-width);
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
align-items: stretch;
|
||||
background: transparent;
|
||||
backdrop-filter: none;
|
||||
-webkit-backdrop-filter: none;
|
||||
}
|
||||
|
||||
.main:not(.tiles-active, .webview-active) > .file-preview-overlay.is-docked .file-preview-window {
|
||||
width: 100% !important;
|
||||
height: 100% !important;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
max-height: none;
|
||||
border-radius: 0;
|
||||
resize: none;
|
||||
}
|
||||
|
||||
.main:not(.tiles-active, .webview-active) > .file-preview-overlay.is-docked :is(#filePreviewExpandBtn, #filePreviewResize) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#filePreviewDockBtn[aria-pressed='true'] {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
body:has(.main:not(.tiles-active, .webview-active) > .file-preview-overlay.is-docked.visible) .attachment-card-stack {
|
||||
right: calc(var(--file-preview-dock-width) + 18px);
|
||||
}
|
||||
}
|
||||
|
||||
/* Folder grid (panels-ui.js openFolderGrid): one step BELOW the file preview, so a
|
||||
tile opens its preview on top and closing that preview lands back on the grid. */
|
||||
.folder-grid-overlay {
|
||||
@@ -13598,6 +13688,24 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
#responseFilesBtn[hidden],
|
||||
.btn-icon-header.btn-response-files--hidden,
|
||||
.response-viewer[data-files-only='true'] :is(#responseViewerMore, #responseViewerCopyMarkdown) {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* Response files rows: buttons (no href for a middle-click to open), drawn as links. */
|
||||
.response-files-list .response-files-item {
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--accent);
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.response-viewer-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -14089,6 +14197,28 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
|
||||
text-align: start;
|
||||
vertical-align: top;
|
||||
white-space: normal;
|
||||
/* A cell wraps between words, so its column is never narrower than its longest word.
|
||||
With the `anywhere` that cells inherit from .rv-text, the table counted every letter
|
||||
as a break point when it sized its columns, and a column beside wide headers shrank
|
||||
to one letter per line. */
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
/* Inline code and links hold long tokens such as URLs, identifiers and hashes. Chromium
|
||||
finds no break point inside one, since it never breaks after `/`. Under `break-word`
|
||||
the longest token set its column's width and the whole table scrolled sideways, so
|
||||
these tokens break anywhere. A linked path already does, through the `break-all` of
|
||||
the a.rv-path rule above. CSS cannot tell an autolink from a link with a prose label,
|
||||
so a label breaks anywhere too. The one exception is a path link's label
|
||||
(.rv-path-link), which keeps breaking between words. */
|
||||
.rv-table-wrap td :is(code, a:not(.rv-path-link)) {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* Breaking anywhere lets a column shrink to one letter per line, so a cell holding such
|
||||
a token gets a floor of about ten characters. */
|
||||
.rv-table-wrap td:has(code, a:not(.rv-path-link)) {
|
||||
min-width: 6em;
|
||||
}
|
||||
|
||||
.rv-text th:last-child, .rv-text td:last-child,
|
||||
@@ -19618,6 +19748,15 @@ html[data-session-list="sidebar"][data-sidebar="collapsed"] .btn-sidebar-toggle
|
||||
top: 28px;
|
||||
}
|
||||
|
||||
/* Pane A's split header is the first child of .terminal-wrap, so the chat layer and its switch start below it. */
|
||||
.terminal-pane-a-header ~ .chat-view {
|
||||
top: 28px;
|
||||
}
|
||||
|
||||
.terminal-pane-a-header ~ .chat-view-toggle {
|
||||
top: 36px;
|
||||
}
|
||||
|
||||
.split-harness.run-mode-dot {
|
||||
font-size: 13px;
|
||||
}
|
||||
@@ -23615,7 +23754,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;
|
||||
}
|
||||
|
||||
@@ -24025,3 +24170,221 @@ html[data-header-stats='tiles'] .header-plan-usage:not(:has(.pu-row)) {
|
||||
body.keyboard-visible .terminal-container .xterm-screen {
|
||||
transform: translateY(calc(-1 * var(--kb-clip, 0px)));
|
||||
}
|
||||
|
||||
/* ═══ Chat view (chat-view.js) ═══════════════════════════════════════════════
|
||||
A session's conversation as its main view. It covers the terminal inside
|
||||
.terminal-wrap; the terminal stays mounted and sized underneath, so switching
|
||||
views never resizes the PTY. The message list carries .response-viewer-body,
|
||||
so it renders exactly as the Response Viewer does. Theme tokens only. */
|
||||
.chat-view {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 20;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--bg-dark);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.chat-view[hidden],
|
||||
.chat-view-toggle[hidden],
|
||||
.chat-view-dialog[hidden],
|
||||
.chat-view-status[hidden],
|
||||
.chat-view-empty[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.chat-view-scroll {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
padding-top: 48px;
|
||||
}
|
||||
|
||||
.chat-view-thread,
|
||||
.chat-view-empty {
|
||||
max-width: 820px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.chat-view-empty {
|
||||
color: var(--text-muted);
|
||||
text-align: center;
|
||||
padding-top: 15vh;
|
||||
}
|
||||
|
||||
/* The notice is a paragraph directly inside the scroller, which carries the Response Viewer's
|
||||
`.response-viewer-body > p` margin rule; this one outranks it so the notice stays centred. */
|
||||
.chat-view-scroll > .chat-view-empty {
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
.chat-view-show-all {
|
||||
margin-top: 8px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--accent);
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.chat-view-show-all:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.chat-view-dialog {
|
||||
width: calc(100% - 32px);
|
||||
max-width: 820px;
|
||||
margin-inline: auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-bottom: 8px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-inline-start: 3px solid var(--yellow);
|
||||
border-radius: 10px;
|
||||
background: var(--bg-card);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.chat-view-dialog-text {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* Sits in the message list, right under the last message. */
|
||||
.chat-view-status {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
max-width: 820px;
|
||||
margin: 4px auto 0;
|
||||
padding-inline-start: 4px;
|
||||
color: var(--text-muted);
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.chat-view-status-body {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.chat-view-status-dot {
|
||||
flex: none;
|
||||
margin-top: 6px;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--accent);
|
||||
animation: chat-view-pulse 1.4s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes chat-view-pulse {
|
||||
0%, 100% { opacity: 0.35; }
|
||||
50% { opacity: 1; }
|
||||
}
|
||||
|
||||
.chat-view-btn {
|
||||
height: 32px;
|
||||
padding: 0 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--bg-input);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.chat-view-btn:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.chat-view-btn-primary {
|
||||
border-color: var(--accent);
|
||||
background: var(--accent);
|
||||
color: var(--bg-card);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.chat-view-btn-primary:hover {
|
||||
background: var(--accent);
|
||||
filter: brightness(1.08);
|
||||
}
|
||||
|
||||
.chat-view-btn:focus-visible,
|
||||
.chat-view-toggle-btn:focus-visible,
|
||||
.chat-view-show-all:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* Chat / Terminal switch: top right of the session area, above both views. */
|
||||
.chat-view-toggle {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
inset-inline-end: 18px;
|
||||
z-index: 21;
|
||||
display: flex;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--floating-bg);
|
||||
overflow: hidden;
|
||||
opacity: 0.8;
|
||||
transition: opacity 0.15s ease;
|
||||
}
|
||||
|
||||
.chat-view-toggle:hover,
|
||||
.chat-view-toggle:focus-within,
|
||||
.chat-view-toggle--over-chat {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.chat-view-toggle-btn {
|
||||
padding: 4px 10px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--text-muted);
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.chat-view-toggle-btn[aria-pressed="true"] {
|
||||
background: rgba(var(--accent-rgb), 0.16);
|
||||
color: var(--text);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* The partial-history banner draws its Load full history and dismiss buttons at
|
||||
the right end of the top row, where the Chat / Terminal switch sits. */
|
||||
.terminal-wrap:has(> .chat-view-toggle:not([hidden])) .history-trunc-bar {
|
||||
padding-inline-end: 170px;
|
||||
}
|
||||
|
||||
/* The keyboard accessory bar's keys write straight into the pane, which the chat
|
||||
view hides, so the bar stays hidden while the chat view shows. */
|
||||
body.chat-view-showing .keyboard-accessory-bar.visible {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* On touch devices the CJK input field is fixed over the bottom of the chat view, and its text
|
||||
goes into the pane, so it stays hidden while the chat view shows. !important beats the inline
|
||||
display that app.js _updateCjkInputState sets. */
|
||||
body.chat-view-showing.touch-device #cjkInput.cjk-input-visible {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.chat-view-status-dot { animation: none; }
|
||||
.chat-view-toggle { transition: none; }
|
||||
}
|
||||
|
||||
/* The conversation takes focus only so keys never reach the hidden terminal; it draws no ring. */
|
||||
.chat-view-scroll:focus {
|
||||
outline: none;
|
||||
}
|
||||
@@ -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);
|
||||
@@ -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;
|
||||
|
||||
@@ -207,6 +207,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
headerA.el.classList.add('terminal-pane-a-header');
|
||||
this._splitHeaders = { a: headerA, b: headerB };
|
||||
|
||||
this._setFilePreviewDocked?.(false);
|
||||
parent.insertBefore(container, wrap);
|
||||
wrap.insertBefore(headerA.el, wrap.firstChild);
|
||||
container.appendChild(wrap);
|
||||
|
||||
@@ -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
|
||||
@@ -338,6 +342,8 @@
|
||||
if (ev.type === 'keydown' && global.app?.shouldToggleSessionSidebarFromShortcut?.(ev)) {
|
||||
return false;
|
||||
}
|
||||
// Alt+Shift+C flips the main view's chat view, so it must never type into this pane.
|
||||
if (ev.type === 'keydown' && global.app?.shouldToggleChatViewFromShortcut?.(ev)) return false;
|
||||
// Tile grid chords (focus, toggle): acted on by the capture handler, so
|
||||
// they must never reach this tile's PTY. Every event type, and before
|
||||
// the Shift+Enter branch below.
|
||||
@@ -639,6 +645,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 +1622,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-
|
||||
|
||||
Loaded 100 of 196 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user