mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-28 08:29:32 +01:00
Compare commits
166
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c51a7134eb | ||
|
|
d9fce03444 | ||
|
|
6db166f3f8 | ||
|
|
b3e781696a | ||
|
|
854f316809 | ||
|
|
00552ac04a | ||
|
|
4936e07ca2 | ||
|
|
51852dbdbc | ||
|
|
fcccdd07c5 | ||
|
|
f2c03e6bf3 | ||
|
|
d5fe0adfe7 | ||
|
|
a4201b34a8 | ||
|
|
70ee1312d4 | ||
|
|
9309500d40 | ||
|
|
95918b80b4 | ||
|
|
64c8d1c8a5 | ||
|
|
b957eb8dea | ||
|
|
6824fe666c | ||
|
|
5672e47a2d | ||
|
|
03916d75a1 | ||
|
|
38c98529c4 | ||
|
|
063476ec55 | ||
|
|
7a3bbce7d5 | ||
|
|
eb40f4aaa5 | ||
|
|
dfd661f9d1 | ||
|
|
fc41bb5b13 | ||
|
|
76c5f1a99b | ||
|
|
f109bdc23a | ||
|
|
d466e5c3bf | ||
|
|
1d889468df | ||
|
|
0be4c154cc | ||
|
|
b7bb332338 | ||
|
|
babb55e4d9 | ||
|
|
891f3a19e9 | ||
|
|
ccf502b7a8 | ||
|
|
79f85415d8 | ||
|
|
9753ca9d70 | ||
|
|
dbf545ce8f | ||
|
|
d387cf8cdb | ||
|
|
ba61cfe4e6 | ||
|
|
d7c141e25f | ||
|
|
67aa28ac4f | ||
|
|
df494b21ce | ||
|
|
79f444a2fc | ||
|
|
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 | ||
|
|
5548c17c4a | ||
|
|
1d33220493 | ||
|
|
baf9d6a6a4 | ||
|
|
d00a8d6cbf | ||
|
|
a9ed3f55c3 | ||
|
|
acd90efe73 | ||
|
|
9d0f29fb22 | ||
|
|
6a5b818f65 | ||
|
|
507116f019 | ||
|
|
8202e07286 | ||
|
|
6222444e82 | ||
|
|
1207c316c0 | ||
|
|
923db64a10 | ||
|
|
756d8d875e | ||
|
|
f25e94141f | ||
|
|
c31e4fc716 | ||
|
|
99a69a87cf | ||
|
|
5df5628518 | ||
|
|
4344ce8c11 | ||
|
|
b732cec36d | ||
|
|
bee4948e1a | ||
|
|
c7b6e1cb4e | ||
|
|
b5a356dadf | ||
|
|
363de086fc | ||
|
|
d7b195a783 | ||
|
|
d9ded95b95 | ||
|
|
8b809da466 | ||
|
|
ce899f59cc | ||
|
|
44459a12dd | ||
|
|
974b85493c | ||
|
|
a36b875363 | ||
|
|
7343274d5f | ||
|
|
ba4a1c16e2 | ||
|
|
c639b38c1a | ||
|
|
e85bb83353 | ||
|
|
3ef4900e60 | ||
|
|
3c5b7e2199 | ||
|
|
57fdb52f7c | ||
|
|
387cb830f4 | ||
|
|
673a656538 | ||
|
|
b5ad7afebe | ||
|
|
80d719df5f | ||
|
|
64ee504247 | ||
|
|
95fb147e9c | ||
|
|
14dccd462f | ||
|
|
677e393fc3 | ||
|
|
2a3496b7b3 | ||
|
|
44a10cff39 | ||
|
|
06100a5506 | ||
|
|
cc413afdd1 | ||
|
|
238853f96a | ||
|
|
7f729ee87b | ||
|
|
b1bcd1e3af | ||
|
|
4ce9abde7d | ||
|
|
6e3d6ebad9 | ||
|
|
28ed4016bd | ||
|
|
0ea97d62ec | ||
|
|
0b3087918f | ||
|
|
9304f98efb | ||
|
|
0e913eedf2 | ||
|
|
c497869ee5 | ||
|
|
b8a4466643 | ||
|
|
e0e2f689cf | ||
|
|
e4a85fabcd | ||
|
|
10e443a309 | ||
|
|
ab9c574ca4 | ||
|
|
4cedeec529 | ||
|
|
e99b42c387 | ||
|
|
574eae72f3 | ||
|
|
75ea908f29 | ||
|
|
d44b049c51 | ||
|
|
259cabd738 | ||
|
|
f1b2a2ab75 | ||
|
|
03cb6a68b4 | ||
|
|
6fb8b27768 | ||
|
|
f604deba3e | ||
|
|
60f1900081 | ||
|
|
fa4815b465 | ||
|
|
a26be7c98f | ||
|
|
4423949923 | ||
|
|
5396e33b48 |
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"aicodeman": patch
|
||||
---
|
||||
|
||||
Claude sessions now start when Codeman itself runs as root (a VPS, an LXC container): Claude Code refuses `--dangerously-skip-permissions` under root and every local Claude tab showed a dead pane, so a root server now starts Claude without the bypass (it asks for permission instead) and says so in the server log.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"aicodeman": patch
|
||||
---
|
||||
|
||||
The installer no longer stops on "Failed to obtain sudo privileges" in a headless run with a working passwordless sudo (`su - user -c`, cron, a CI runner, cloud-init): it now checks whether `/dev/tty` can be opened before taking sudo's input from it, where it used to test only that the node exists.
|
||||
@@ -10,7 +10,7 @@
|
||||
"name": "codeman",
|
||||
"source": "./plugins/codeman",
|
||||
"description": "Drive Codeman from inside a Claude Code session: spawn worker sessions, prompt them, wait for them, read their answers, clean up. Acts inside a Codeman-managed session; outside one it only reads saved Codex conversations offline.",
|
||||
"version": "1.51.0",
|
||||
"version": "1.52.0",
|
||||
"author": {
|
||||
"name": "Ark0N",
|
||||
"url": "https://github.com/Ark0N"
|
||||
|
||||
@@ -1,5 +1,77 @@
|
||||
# aicodeman
|
||||
|
||||
## 1.52.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 7a3bbce: ### Thanks
|
||||
- @HadrienKerlero for two big ones: the iPhone keyboard fix (#839, nine review rounds) and the Reload history action (#815, eighteen rounds), and for the reports that started both (#830, #814).
|
||||
- @DodgyBadger for the Files panel that loads one folder at a time (#848), built on the design from #759.
|
||||
- @kkalisz for three fixes: the login lockout after a restart (#838), exited agents on tmux 3.8 (#840, five review rounds), and the terminal dashboard's window size (#853).
|
||||
- @bearyjd for the installer's multi-user guidance (#847) and the wiki section on keeping reverse-proxy hostnames across restarts (#845), a first contribution.
|
||||
|
||||
**Closing a tab can no longer signal every process of your account.** tmux reports pid 0 for a pane that has no process, such as an empty split beside the agent. A server restart could record that 0 for the tab, and closing the tab while that pane was the active one then signalled the children of pid 0, which is every process of the account: all sessions, tmux and the systemd user manager. A kill now never takes pid 0 or 1. Such a tab is closed by tmux alone and nothing else is signalled.
|
||||
|
||||
**The Files panel loads one folder at a time (#848).** Opening the panel reads only the top folder, and a folder is read when you open it, 500 entries a page with Load more. Large workspaces no longer stop at a scan limit, and Refresh keeps the folders you had open. Behaviour change: typing in the search box filters the folders already loaded, and Enter searches the whole workspace.
|
||||
|
||||
**iPhone keyboard suggestions, dictation and hold-delete work in the terminal (#839, fixes #830).** Tapping a suggestion used to send only its first letter, and holding delete never went word by word. Suggestions, text replacement, dictation and held delete now reach the agent as one ordered edit, in the main terminal, the split pane and every tile. A delayed Enter or paste stays with the session it was typed for when you switch tabs, and backspace deletes a whole emoji.
|
||||
|
||||
**Mac app: server tabs (#816).** The Mac app keeps several Codeman servers open in one window, one tab each in the title bar, and switches between them with a click or ⌘1 to ⌘8. Every tab shows whether its server needs you, is waiting, is working or is offline, and ⌘0 shows all servers at once with the ones that need you first. ⌘T opens another server, a tab can be renamed, coloured and dragged, ⇧⌘T reopens a closed one, and your tabs come back at the next launch. On macOS 14 and later every server keeps its own login and cookies; before macOS 14 a second tab on the same machine is refused. Behaviour change: only the server you used last keeps its per-device settings (font size, skin); every other server starts those fresh once.
|
||||
|
||||
**Fixes.**
|
||||
- **An open tab after a restart no longer locks everyone out (#838).** A request with no `Authorization` header always gets the login prompt and is no longer counted as a failed login. Before, an open tab's background requests filled the per-IP limit within seconds of a restart, and everyone behind the same tunnel address was locked out for 15 minutes. Wrong passwords and malformed headers are counted as before.
|
||||
- **Missing lines above the live screen can be fetched again (#815, fixes #814).** In some agent sessions (seen with OMP) a few lines were missing right above the live output until you scrolled to the very top. The history banner now has a Reload history action, on desktop and on phones, that fetches the whole history again and keeps the text you are reading in place. It can be switched off per device in Settings > Terminal & Input > Scrolling & rendering. Also, while you are scrolled up, new output no longer moves the text you are reading once the scrollback is full.
|
||||
- **An agent that exited is seen again on tmux 3.8 (#840).** tmux 3.8 prints no process number for a finished pane, so a session whose agent had exited stayed on the board as idle, and a restart of Codeman dropped its record while its tmux session stayed behind. Such a session is now seen as exited and closed, as on older tmux. Finished sessions that piled up on tmux 3.8 are relaunched once, at the first start after this update. A dead `codeman-*` tmux session that was orphaned before this fix is not found again: remove it with `tmux -L codeman kill-session -t codeman-<id>`.
|
||||
- **`codeman tui` takes its window size back (#853).** While a terminal is attached, the window follows whichever client was used last, as plain tmux does. Before, a browser tab that opened or resized the same session pinned the window to the tab's size until you detached and attached again. Now typing, pasting or resizing the terminal fills it again, and typing in the tab, or its Redraw, gives the tab the size. Needs tmux 3.3 or newer.
|
||||
- **Closing a dialog you opened with the mouse puts the keyboard back in the terminal (#857).** After App Settings or Session Options was opened with a click and closed again, nothing you typed reached the terminal until you clicked it. A dialog now returns the keyboard to the field you were typing in when you clicked, which with the tile grid or the split open is the pane you were in. The Session Manager and the command palette follow the same rule, and a dialog opened with the keyboard still returns to the control it was opened from.
|
||||
- **The Ledger tab layout shows the working spinner again (#851).** The ledger hid the status dot and the spinner with it, so a busy session looked like an idle one. A working cell now keeps the ring.
|
||||
- **The phone toolbar sits directly on the keyboard (#819).** With the keyboard open on an iPhone, an empty band sat between the toolbar and the keyboard, and the last line of the prompt you were typing was hidden under the bar above it. Both are gone.
|
||||
- **Mac app: pasting an image works (#817).** ⌘V with a copied picture did nothing in the Mac app, while the same server worked in a browser. Screenshots, images copied from an app, files copied in Finder and plain text now paste with one ⌘V, also from servers on older Codeman versions.
|
||||
- **The installer explains multi-user mode and keeps it across re-runs (#847).** The done screen says how to create the first admin and switch multi-user sign-in on for a systemd unit or a LaunchAgent, and a re-run keeps an existing `CODEMAN_MULTIUSER` setting.
|
||||
- **A hand-written quoted value in the systemd unit survives an installer re-run.** `Environment=CODEMAN_PASSWORD="my pass"` used to be dropped when the installer rewrote the unit, which left a server bound to the LAN without its password. It is now read the way systemd reads it.
|
||||
|
||||
**Fixes applied while landing.** The installer prints the manual multi-user start line only where no service runs, since next to a running service it would start a second server on the same data (#847). The Files panel no longer pages through a whole large folder looking for an open folder that was deleted, shows a folder that is still waiting to load as loading instead of empty, and its error line and single-match count read correctly in Chinese and English (#848). The resize nudge that lets a browser's Redraw win back the window runs only for sessions that have tmux behind them (#853), and the test for closing a live pane no longer reads the machine's real process list (#840).
|
||||
|
||||
**Docs and tests.** The Remote Access wiki page shows how to keep `CODEMAN_ALLOWED_HOSTS` across restarts with a systemd drop-in (#845), and the kill guard, the installer's unit reader and the Files panel restore have tests that fail without them.
|
||||
|
||||
## 1.51.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 1d33220: ### Thanks
|
||||
- @kkalisz for Send on Enter in the phone's input field (#820), `codeman tui <name>` (#834), and a password-protected Codeman that installs as an app (#826).
|
||||
- @ArizeSky for web tabs that render the DeepSeek Harness web UI and Vite dashboards (#825), and for closing a session-cookie leak on the web tab's WebSocket leg (#827).
|
||||
- @JDProfresh for tracking a 174 GiB log flood down to a chokidar retry loop and fixing it (#818), and for wheel forwarding that any CLI entry can ask for (#831).
|
||||
- @aakhter for the tmux 3.7 key-table fix (#821) and for Start-Codeman.sh on WSL (#822).
|
||||
- @ludovicfourrage for the report and the fix that makes the header's CPU reading real CPU use (#823, #824).
|
||||
- @johoja12 for Discord replies that are typed once, however often the gateway replays them (#832).
|
||||
- @shenlvkang-collab for the report in #701 that led to answers on a relocated Claude config folder (#812).
|
||||
|
||||
**Phone: Send on Enter for the input field (#820).** A new per-device setting next to CJK Input, Input Field: Send on Enter. With both on, the field above the keyboard works like a chat box: your text stays there while you scroll the terminal to reread a question, Enter sends it, Shift+Enter adds a line and Esc clears it. The phone keyboard layout is sturdier for everyone too: a swipe on the live screen no longer closes the field's keyboard, and on iOS the bars sit on the keyboard the first time it opens.
|
||||
|
||||
**The terminal dashboard attaches by session name (#834).** `codeman tui <name>` attaches to a live session by its exact name as well as by its list number, so getting back into the same session over SSH no longer depends on where it sits in the list.
|
||||
|
||||
**Web tabs render the DeepSeek Harness web UI and Vite dashboards (#825).** The DeepSeek Harness web tab opened on a blank 401 page since `dsh web` started asking for a one-time launch token. Codeman now trades that token for dsh's session cookie and presents it only to that tab. Dashboards that ship a relative `<base href>` (what Vite and SvelteKit builds emit) and ones that load modules with `import("/...")` render through the web tab proxy too.
|
||||
|
||||
**Local model: Muse Glimmer 30B as its MLX build (#803).** On a Mac with 48 GB or more, Run a model on this Mac offers the MLX build of Muse Glimmer 30B. On an M5 Pro with 48 GB it wrote twice as many tokens a second as the GGUF build on the same request, and finished an OpenCode turn the GGUF build never answered. Macs with 32 or 36 GB keep the GGUF row as it was.
|
||||
|
||||
**Fixes.**
|
||||
- **A failing file watcher no longer floods the log (#818).** When Linux ran out of inotify instances, a watcher whose `fs.watch` failed retried on each parent folder up to `/` and then forever, writing about 112,000 log lines a second until the disk filled. It now logs one warning and keeps working by polling, and the agent-teams watcher switches its live watcher back on once watching works again.
|
||||
- **A password-protected Codeman installs as an app (#826).** The browser fetched the app manifest without the login cookie and got a 401, so Chrome's Install app refused. The manifest request now carries the cookie.
|
||||
- **A trusted web tab's WebSocket no longer sends Codeman's session cookie to the dashboard (#827).** The HTTP leg already stripped it.
|
||||
- **Answers come back for a session on its own Claude config folder (#701, #812).** A session started with `CLAUDE_CONFIG_DIR` (a second Claude account) showed "No response yet" in the response viewer, and `codeman agent read` and the Discord bridge's last message came back empty. They now read the transcript from that session's own folder.
|
||||
- **tmux 3.7 to 3.7c: the prefix table and `codeman tui` keys read right (#821).** Those releases print nothing for a key table with exactly one binding, so Codeman reset its already reduced prefix table on every new session and `codeman tui` took a bound key for a free one.
|
||||
- **`docker/Start-Codeman.sh` no longer hangs on WSL (#822).** Each free-port check gives up after about a second instead of waiting out the kernel's connect timeout.
|
||||
- **The header CPU reading is CPU use (#823, #824).** It showed the load average per core, which read 100% on a host whose cores were mostly idle. Behaviour change: on such a host the figure is now much lower.
|
||||
- **Discord: a replayed reply is typed once (#832).** A gateway replay, also after a restart, could type the same reply into a session twice. If the small store that prevents it fails, the reply is still typed.
|
||||
- **A custom full-screen CLI can get the mouse wheel (#831).** The wheel went only to a fixed list of CLIs. It now follows each entry's `wheelForward` rule, so a `clis.json` entry can ask for it; stock CLIs behave as before.
|
||||
|
||||
**Fixes applied while landing.** The web tab proxy filters Codeman's session cookie off the WebSocket leg whether or not the dsh cookie is added, and a dsh tab created in multi-user mode still gets its cookie after a switch back to single-user mode (#825, #827). The CPU fallback no longer divides by a core count of 0 (#824). A watcher that a restart finds still failing warns again, and the watcher tests skip on macOS, where chokidar never calls `fs.watch` (#818). The Discord reply store has a test for a planted symlink at its path (#832).
|
||||
|
||||
**Docs and tests.** The docs name the tmux releases with the blank key-table answer, the DeepSeek web cookie rules and how a custom full-screen CLI asks for the wheel.
|
||||
|
||||
About 8,900 lines of code nothing reached are gone, among them the Ralph plan wizard that no button opened any more and the Agent Teams terminal windows; no route, setting or SSE event was removed. `npm run check:frontend-dead` lists frontend code nothing references.
|
||||
|
||||
## 1.51.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
@@ -52,7 +52,7 @@ Uses [Semantic Versioning](https://semver.org/) (`MAJOR.MINOR.PATCH`) via `@chan
|
||||
|
||||
When the user says **COM** (`COM` = patch, `COM minor`, `COM major`): **Read [`docs/releasing.md`](docs/releasing.md) and follow every step in order**; never improvise a release from memory. It covers the changeset, `npm run version-packages`, the `**Version**` line below, the branch check and explicit-path commit, deploy, the getcodeman.com badge, watching BOTH CI workflows, the MCP registry publish, and the Discussions announcement.
|
||||
|
||||
**Version**: 1.51.0 (must match `package.json`)
|
||||
**Version**: 1.52.0 (must match `package.json`)
|
||||
|
||||
## Project Overview
|
||||
|
||||
@@ -64,7 +64,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
|
||||
**Requirements**: Node.js 22+, Claude CLI, tmux
|
||||
|
||||
**Git**: Main branch is `master`. Terminal session dashboard: `codeman tui` (`--list` to list, `codeman tui <n>` to attach).
|
||||
**Git**: Main branch is `master`. Terminal session dashboard: `codeman tui` (`--list` to list, `codeman tui <n>` or `codeman tui <name>` to attach).
|
||||
|
||||
## Additional Commands
|
||||
|
||||
@@ -76,6 +76,8 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
| Regenerate the CLI catalogue | `npm run generate:cli-catalog` (`--check` to fail on drift). Rewrites `config/clis.stock.json` **and** the marked block in `install.sh` from `stock.ts`. ⚠ **Commit both.** They are what `install.sh` and the Docker agent image read, since neither can import TypeScript; `test/cli-catalog-sync.test.ts` and a CI `--check` step fail if either goes stale. See `docs/cli-registry.md` |
|
||||
| Build the docker agent image | `node scripts/build-agent-image.mjs --no-cache` (builds `codeman/agent:base` from `docker/agent.Dockerfile`; prerequisite for Docker cases; `--engine`/`--image`). ⚠ **Always `--no-cache`** — a plain rebuild re-uses the cached `npm install -g` layer and silently keeps the CLIs frozen at their original versions, which once shipped a BROKEN codex while reporting success. See `docs/docker-cases.md` |
|
||||
| Browser-test exclusion check | `npm run check:browser-excludes` (`scripts/check-browser-test-excludes.mjs`; runs in CI, <1s). Fails if a test importing playwright/puppeteer is still collected by `config/vitest.ci.config.ts`; add it to `BROWSER_TEST_GLOBS` in `config/test-suites.ts` |
|
||||
| Dead-code report | `npm run knip` (`config/knip.json`; fetched with `npx`, so it needs the network and is not a CI step). It reports nothing on a clean tree: an export, file or dependency it lists is new dead code, or a manual script that needs an `entry`. Tests count as users, and `src/web/public/` is outside it (plain scripts with no imports). A deliberate keep carries `@knipignore` in its JSDoc |
|
||||
| Frontend dead-code check | `npm run check:frontend-dead` (`scripts/check-frontend-dead-code.mjs`, a few seconds, not a CI step). `src/web/public/` is plain scripts that knip cannot follow, so this is its counterpart there: it fails on a function, method or top-level binding that nothing references (identifiers, strings, `index.html`, the gesture overlay's source, tests) and on a CSS class or id that no markup or script can produce. `--production` also lists what only tests reference. A deliberate keep goes in the script's `ALLOW` map with its reason |
|
||||
| Pre-push hook | Installed by `npm install` (`scripts/git-hooks.mjs`, via postinstall): runs the static CI checks (~10-40s) before `git push`. Skip once: `CODEMAN_SKIP_PREPUSH=1 git push`. Skips itself with a notice when HEAD is not the pushed commit or the tree has uncommitted changes the checks would read. Marker-owned, so a hand-written `pre-push` is never overwritten; installs ONLY into the repo's own `<git-common-dir>/hooks` (worktree-safe; a `core.hooksPath` elsewhere, e.g. a global one, is left alone) |
|
||||
| Production logs | `journalctl --user -u codeman-web -f` |
|
||||
| Detached server | `codeman web -d` (`--status`, `--stop`; pidfile+log at `dataPath('web.pid'/'web.log')`). ⚠ Refuses to start a 2nd server on one data dir — see Instance isolation |
|
||||
@@ -92,7 +94,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
- **ESM only** — Never `require()`, use `await import()`. `tsx` masks CJS/ESM issues in dev but production breaks
|
||||
- **Package ≠ product name** — npm: `aicodeman`, product: **Codeman**. Release renames tags accordingly. Both `aicodeman` and `codeman` bin aliases are installed (`package.json` `bin`)
|
||||
- **Global regex `lastIndex`** — Shared `g`-flag patterns in loops must reset `lastIndex = 0` first, or use the `execPattern()` helper in `utils/regex-patterns.ts` (resets automatically)
|
||||
- **`envOverrides` flow `CLAUDE_CODE_*` / `OPENCODE_*` / `CODEX_*` / `GEMINI_*` / `GOOGLE_*` / `ANTIGRAVITY_*` / `PI_*` / `GROK_*` / `XAI_*` / `DSH_*` / `DEEPSEEK_*` / `COPILOT_*` env vars, plus exact-key `CLAUDE_CONFIG_DIR`** — Set via `POST /api/sessions { envOverrides }`, stored on `Session._envOverrides`, exported by `tmux-manager.buildEnvExports()` at spawn time, persisted in `SessionState.envOverrides`. **Do NOT** write these to `<case>/.claude/settings.local.json` — that's the old path and creates UI/disk drift. (`GOOGLE_*` is the deliberately-broad Vertex-AI namespace for Gemini — see Multi-CLI prefix discipline.) `CLAUDE_CONFIG_DIR` (#255, exact match via `ALLOWED_ENV_KEYS` in `schemas.ts`) points a session at a separate Claude account/config dir for per-client subscriptions; it persists to state.json (a path, not a secret; losing it on restart would silently switch accounts). ⚠️ A relocated config dir writes transcripts outside `~/.claude/projects`, so the response viewer, subagent windows, ultracode panel and Read My Mind capture go blind for that session unless the user symlinks `projects` back into the shared tree (`ln -s ~/.claude/projects <configDir>/projects`). ⚠️ It is also one of claude's `privilegedEnvKeys` (Custom Model Endpoint Profiles, since it can redirect a session's traffic same as any other injected var), so in multi-user mode setting it via `envOverrides` is admin-only, and a non-granted owner's already-persisted `CLAUDE_CONFIG_DIR` is stripped on reboot-restore — silently returning that session to the default Claude account rather than the one it was pointed at (see `session-env-clamp.ts`). → [architecture-invariants#per-session-env-overrides-exact-key-allowlist-and-claude_config_dir](docs/architecture-invariants.md#per-session-env-overrides-exact-key-allowlist-and-claude_config_dir)
|
||||
- **`envOverrides` flow `CLAUDE_CODE_*` / `OPENCODE_*` / `CODEX_*` / `GEMINI_*` / `GOOGLE_*` / `ANTIGRAVITY_*` / `PI_*` / `GROK_*` / `XAI_*` / `DSH_*` / `DEEPSEEK_*` / `COPILOT_*` env vars, plus exact-key `CLAUDE_CONFIG_DIR`** — Set via `POST /api/sessions { envOverrides }`, stored on `Session._envOverrides`, exported by `tmux-manager.buildEnvExports()` at spawn time, persisted in `SessionState.envOverrides`. **Do NOT** write these to `<case>/.claude/settings.local.json` — that's the old path and creates UI/disk drift. (`GOOGLE_*` is the deliberately-broad Vertex-AI namespace for Gemini — see Multi-CLI prefix discipline.) `CLAUDE_CONFIG_DIR` (#255, exact match via `ALLOWED_ENV_KEYS` in `schemas.ts`) points a session at a separate Claude account/config dir for per-client subscriptions; it persists to state.json (a path, not a secret; losing it on restart would silently switch accounts). ⚠️ A relocated config dir writes transcripts outside `~/.claude/projects`, so subagent windows, the ultracode panel and Read My Mind capture go blind for that session unless the user symlinks `projects` back into the shared tree (`ln -s ~/.claude/projects <configDir>/projects`). The response viewer and the rename's `/resume` title read a LOCAL session's own folder, then the server's `CLAUDE_CONFIG_DIR`, then `~/.claude` (`claudeConversationDirs()` in session-routes.ts over `claudeProjectsDir()`, as the Edit history panel and the relaunch pin do, #701): a relocated folder is probed bounded first, and a missing one reads as no transcript, never as a reason to look under `~/.claude`. ⚠️ It is also one of claude's `privilegedEnvKeys` (Custom Model Endpoint Profiles, since it can redirect a session's traffic same as any other injected var), so in multi-user mode setting it via `envOverrides` is admin-only, and a non-granted owner's already-persisted `CLAUDE_CONFIG_DIR` is stripped on reboot-restore — silently returning that session to the default Claude account rather than the one it was pointed at (see `session-env-clamp.ts`). → [architecture-invariants#per-session-env-overrides-exact-key-allowlist-and-claude_config_dir](docs/architecture-invariants.md#per-session-env-overrides-exact-key-allowlist-and-claude_config_dir)
|
||||
- **Effort is NOT an env var** — never carry effort as `CLAUDE_CODE_EFFORT_LEVEL`: the env var hard-locks effort and blocks in-session `/effort` switching (incl. ultracode). It flows as the dedicated `effort` payload field → `Session._effort` → `claude --effort <level>` for regular levels incl. `max` (the settings `effortLevel` key is `enum(["low","medium","high","xhigh"]).catch(undefined)` — `max` gets SILENTLY dropped there), or `claude --settings '{"ultracode":true}'` for ultracode (rejected by `--effort`). Both are soft defaults the user can override anytime. Legacy env-var entries are auto-migrated by the Session constructor and unset from tmux sessions in `applyEnvOverrides()`. See `buildEffortCliArgs()` in `session-cli-builder.ts`, tests in `test/effort-injection.test.ts`
|
||||
- **The advisor rides `--settings`, NEVER the `--advisor` flag**: Claude Code's advisor tool (a stronger model consulted at decision points, code.claude.com/docs/en/advisor) flows as the `advisorModel` payload field → `Session._advisorModel` (persisted, so respawn and reboot restore keep it) → the `advisorModel` key in the launch's ONE `--settings` JSON, merged with ultracode and the statusLine exporter by `buildAdvisorSettings()` (`session-cli-builder.ts`). ⚠️ The flag EXITS at launch on any pairing the CLI refuses (`claude --advisor haiku` exits 1, so does Fable before its usage-credit consent), which would leave a dead pane on every respawn; the settings key degrades to "no advisor" instead. ⚠️ `isAdvisorModel()` (fable/opus/sonnet aliases or full ids, no haiku) is also the injection guard for the single-quoted argument. Soft default: `/advisor` still switches it in-session. App Settings key `claudeAdvisorModel` (SYNCED, `''` = leave it to the CLI). Remote/docker quick-start refuses it, like `effort`, and so does a remote attach on `POST /api/sessions`. Tests: `test/advisor-model.test.ts`
|
||||
- **Model choice: a persistent default in `settings.local.json`, a per-session `--model`, never env** — the App Settings **Claude Model** picker (`claudeModel` in `settings.json`) is read by `session-ui.js` at session create (wins over the legacy 1M-Opus toggles `opusContext1m`/`opusContext1mEnabled`), sent as the `modelOverride` payload field, and `updateCaseModel()` (`hooks-config.ts`) writes/deletes the `model` key in `<case>/.claude/settings.local.json`. This is the intended exception to the envOverrides rule above: model legitimately lives in `settings.local.json` (a soft default — in-session `/model` still works); env vars do not. A caller that wants one session on a model without touching the case sends `model` on `POST /api/sessions` instead: it goes out as `claude --model <id>`, writes nothing, wins over the app-wide default, and is persisted as `SessionState.model` so both recovery paths relaunch on it (`test/routes/session-routes-claude-model.test.ts`, `test/session-model-recovery.test.ts`). ⚠️ Claude only, via the `model.source` capability (`cliTakesSessionModel()`), never a mode check: refused for other CLIs and on a remote attach, and published by `toState()` for claude alone (cron hands its Claude default to every CLI with a model).
|
||||
@@ -132,7 +134,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
|
||||
**Agent CLI (`codeman agent …`, `src/cli-agent.ts`)**: the command-line client for the wait primitives and the session verbs, for agents the skill does not reach (pi, shell, no `jq`; `seedAgentSessionPreamble` covers every local session whose CLI takes the skill, `capabilities.agentSkillDir`; every pane still exports `CODEMAN_MUX`/`CODEMAN_SESSION_ID`/`CODEMAN_API_URL`). It is an HTTP CLIENT: inspection and guarded stage/submit use the ownership-checked `agent-session-routes.ts` module (experimental, behind `agentCoordinationEnabled`, SYNCED, default OFF: all three routes answer `403 FORBIDDEN` naming it while off, and the CLI shows that verbatim); the other verbs reuse existing routes, with no second transport (the plan's "Socket API" non-goal stands), every call carries `X-Codeman-Parent-Session`, only `spawn`'s quick-start carries `X-Codeman-Agent-Origin` (pinned in test/cli-agent.test.ts), while `spawn` without a case (cwd or `--working-dir`) is `POST /api/v1/sessions` plus `/interactive` or `/shell` without that header, so no agent-case marker, and refuses (exit 4, before any request) an empty `--working-dir` and a bare spawn from a HOME cwd, since it always sends an explicit `workingDir` and the server's no-`workingDir` hooks skip cannot apply (test/cli-agent-project-spawn.test.ts), auth (`src/codeman-credentials.ts`, shared with `codeman attach` and the TUI) from `CODEMAN_PASSWORD` or the data dir's `.env` (the same reader `codeman attach` uses — `readCodemanEnvFile`). Verbs return exit codes (`0` ok / `1` error / `2` timeout / `3` exited / `4` refused) instead of calling `process.exit`, so `test/cli-agent.test.ts` drives every verb against a recording fake transport plus the real `httpRequest` against a local server. ⚠️ Three guards live in code, not prose, and the tests pin them: refuse without `CODEMAN_MUX=1`+`CODEMAN_API_URL` (never guess a URL); `send` transmits printable text + `\r` only (`inputRefusal`: any byte < 0x20 or DEL refuses BEFORE the transport — opencode's `Ctrl+C` is `app_exit`), ESC exists solely as `interrupt` with no `\r`; `rm` fails closed (`deleteRefusal`: empty id, self shorter than 8, prefix match in EITHER direction, re-checked on the resolved id). ⚠️ The routes accept FULL ids only — an 8-char prefix is a 404 (measured live) — while `ls` prints prefixes, so `resolveSessionId` maps a short id through `GET /api/v1/sessions` and refuses an ambiguous one. It also refuses any id under 8 characters (exit 4, on every verb, before any request), the same floor as the server's `PARENT_SESSION_ID_MIN_PREFIX`, so `rm 9` can never pick an arbitrary session. ⚠️ A 400 for `--until stop` on a hook-less mode is passed through verbatim, never papered over: the marker path is the answer there. `spawn` on a readiness timeout exits 2 and LEAVES the session for inspection (the skill's `spawn_worker` deletes it; the CLI's caller is often a human); its stdout is the id ALONE (prose on stderr) so `SID=$(…)` works. ⚠️ Two server answers that look like success and are not: `delivered:false` without `duplicate` (the bytes went into a dead pane — the field exists so a client says "restart" instead of "wait longer") and `wait.ended:true, signal:null` (the worker died during a `stop`/`idle` wait: the registry satisfies only waiters that listed `exit`, then cancels the rest) — both exit 3, checked BEFORE the happy paths in `waitExitCode`. → README "`codeman agent`", `docs/api-reference.md`
|
||||
|
||||
**Discord bridge (`src/discord-bridge.ts`, `src/web/routes/discord-routes.ts`, `src/cli-notify.ts`)**: opt-in two-way Discord (a bot, not the one-way webhook), one thread per tab. Split like `webhook-notify.ts`: pure helpers, a 0600 store (`discord.json` holds the bot token, is never returned by these routes and is on the sensitive-path list; `discord-bridge.json` maps sessionId to thread id), then IO (`DiscordApi` REST with injected fetch, `DiscordGateway` inbound WebSocket with injected socket, `DiscordBridge` rules). Outbound hangs off `WebServer.sendPushNotifications` beside the webhook (so it works with zero push subscriptions) and tab events off `WebServer.broadcast` (`bridgeSessionEvent`); a finished turn (Claude's idle and stop hooks, DeepSeek's stop; the other CLIs raise no turn end, so theirs arrive with an error, a blocked respawn, a crash loop or `codeman notify`) or an error posts the CLI's WHOLE last message as markdown, read from its transcript through the response viewer's reader (`WebServer.lastResponseFor`, set by the session routes: the CLI's own transcript, or the pane segmented into turns for the CLIs that keep none; never for a shell), split over posts of at most 1900 characters and not posted twice (keyed on the text plus its turn, recorded only after the first post succeeds), while a dialog and every CLI without a transcript post the RENDERED tmux screen (`screenTail`, with the composer row and the status lines under it cut), never the raw stream, which a full-screen UI repaints in place; `staleThreads` (default `keep`) archives or deletes threads the bot owns that no tab maps to, after boot and then daily, never one under an hour old, never with an empty map and at most 25 per run. Inbound replies are typed through `session.writeViaMux`. ⚠️ Guards that live in code and tests pin: only `allowedUserIds`, in `guildId`, inside a thread the bridge created, are acted on, everything else is dropped unread; a reply is one printable line plus Enter (a lone digit while a permission or question is pending goes as the key alone, since the dialog acts on it), capped and rate limited, and `discord-notify` is a per-session token bucket (6 a minute, 429 `RATE_LIMITED`; `fileProblem` probes the folder with the bounded probe first); posts send `allowed_mentions` limited to the allowlisted ids; received files go only from Discord's own HTTPS hosts (max 5 x 8 MB, names reduced to `[A-Za-z0-9._-]`) into `<tab folder>/.codeman-discord/`, and a sent file's REAL path must lie inside the tab's folder (`fileProblem`, symlinks followed); a Discord failure never reaches a session; the alert tail is a function the bridge calls only once it will post (no tmux exec per event while off); a delete reaches the bridge from the cleanup path with `killMux` true, never from `session:deleted`, which a detach also fires; `.codeman-discord/` is probed with the bounded probe, refused if a symlink, and ignores itself with a `.gitignore` of `*`; a config restore of `discord.json` reloads the running bridge (`afterRestore`). The startup hint ("how to reach the user") rides the CLI registry as the engine value `appendSystemPrompt` (Claude's `--append-system-prompt`, undefined unless the bridge and `startupHint` are on, so every other launch is byte-identical) No other CLI is told. `codeman notify "<message>" [--urgent] [--file <path>]` wraps `POST /api/sessions/:id/discord-notify`, which accepts a unique 8-character id prefix (a Docker case exports it cut). → `docs/discord-bridge.md`, `docs/wiki/Discord-Bridge.md`, `docs/api-reference.md`
|
||||
**Discord bridge (`src/discord-bridge.ts`, `src/web/routes/discord-routes.ts`, `src/cli-notify.ts`)**: opt-in two-way Discord (a bot, not the one-way webhook), one thread per tab. Split like `webhook-notify.ts`: pure helpers, a 0600 store (`discord.json` holds the bot token, is never returned by these routes and is on the sensitive-path list; `discord-bridge.json` maps sessionId to thread id), then IO (`DiscordApi` REST with injected fetch, `DiscordGateway` inbound WebSocket with injected socket, `DiscordBridge` rules). Outbound hangs off `WebServer.sendPushNotifications` beside the webhook (so it works with zero push subscriptions) and tab events off `WebServer.broadcast` (`bridgeSessionEvent`); a finished turn (Claude's idle and stop hooks, DeepSeek's stop; the other CLIs raise no turn end, so theirs arrive with an error, a blocked respawn, a crash loop or `codeman notify`) or an error posts the CLI's WHOLE last message as markdown, read from its transcript through the response viewer's reader (`WebServer.lastResponseFor`, set by the session routes: the CLI's own transcript, or the pane segmented into turns for the CLIs that keep none; never for a shell), split over posts of at most 1900 characters and not posted twice (keyed on the text plus its turn, recorded only after the first post succeeds), while a dialog and every CLI without a transcript post the RENDERED tmux screen (`screenTail`, with the composer row and the status lines under it cut), never the raw stream, which a full-screen UI repaints in place; `staleThreads` (default `keep`) archives or deletes threads the bot owns that no tab maps to, after boot and then daily, never one under an hour old, never with an empty map and at most 25 per run. Inbound replies are typed through `session.writeViaMux`. An allowed reply is claimed by message ID before rate-limit or exited-agent checks, attachments or typing; a store failure never costs a reply. A file that could not be read is never overwritten. ⚠️ Guards that live in code and tests pin: only `allowedUserIds`, in `guildId`, inside a thread the bridge created, are acted on, everything else is dropped unread; a reply is one printable line plus Enter (a lone digit while a permission or question is pending goes as the key alone, since the dialog acts on it), capped and rate limited, and `discord-notify` is a per-session token bucket (6 a minute, 429 `RATE_LIMITED`; `fileProblem` probes the folder with the bounded probe first); posts send `allowed_mentions` limited to the allowlisted ids; received files go only from Discord's own HTTPS hosts (max 5 x 8 MB, names reduced to `[A-Za-z0-9._-]`) into `<tab folder>/.codeman-discord/`, and a sent file's REAL path must lie inside the tab's folder (`fileProblem`, symlinks followed); a Discord failure never reaches a session; the alert tail is a function the bridge calls only once it will post (no tmux exec per event while off); a delete reaches the bridge from the cleanup path with `killMux` true, never from `session:deleted`, which a detach also fires; `.codeman-discord/` is probed with the bounded probe, refused if a symlink, and ignores itself with a `.gitignore` of `*`; a config restore of `discord.json` reloads the running bridge (`afterRestore`). The startup hint ("how to reach the user") rides the CLI registry as the engine value `appendSystemPrompt` (Claude's `--append-system-prompt`, undefined unless the bridge and `startupHint` are on, so every other launch is byte-identical) No other CLI is told. `codeman notify "<message>" [--urgent] [--file <path>]` wraps `POST /api/sessions/:id/discord-notify`, which accepts a unique 8-character id prefix (a Docker case exports it cut). → `docs/discord-bridge.md`, `docs/wiki/Discord-Bridge.md`, `docs/api-reference.md`
|
||||
|
||||
**MCP server (`codeman mcp`, `src/mcp-server.ts`)**: a Model Context Protocol server on stdio for any MCP client, a CLIENT of the HTTP API like `codeman agent` (reuses its `httpRequest`, `inputRefusal`, `buildSendBody`; the MCP server adds no routes). Seven tools: `list_sessions`, `start_session`, `send_prompt`, `wait_for_session`, `read_output`, `interrupt_session`, `delete_session`. ⚠️ Dual-era: answers the legacy `initialize` handshake (2024-11-05 to 2025-11-25) AND the 2026-07-28 revision (per-request `_meta` with `protocolVersion` + `clientCapabilities`, `server/discover`, `resultType: "complete"` on every modern result); a modern `tools/list`/`server/discover` MUST carry `ttlMs` + `cacheScope` (Claude Code 2.1.296 drops every tool without them: measured). ⚠️ stdout is protocol only; logs go to stderr. ⚠️ The URL comes from `--url`/`CODEMAN_API_URL`, never a guess, and unconfigured it still lists tools (registries introspect) while every call answers how to configure it. ⚠️ Prompt/interrupt/delete only sessions the PROCESS started (in-memory allowlist, so a restart fails closed) or, inside a pane, the calling session's own children, unless `--allow-any-session`; never its own session. ⚠️ `read_output` returns text ONLY, no `structuredContent` (a client that prefers it showed the model metadata instead of the output: measured). Waits default 45 s (Codex's MCP tool timeout is 60 s). Registry manifest `config/mcp-registry/server.json` (`mcpName` in package.json, version kept by `scripts/sync-plugin.mjs`). Tests: `test/mcp-server.test.ts`.
|
||||
|
||||
@@ -150,13 +152,15 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
|
||||
⚠️ **A quiet pane is not always a pane that wants you.** A CLI can declare an optional `capabilities.workDetect.watchingLine` (a monitor, background shell or cloud hand-off it is still running); the idle probe reads it into `Session.watching` and `notePrompt()` opens that idle item ALREADY acknowledged, so no surface alerts. Only `idle` is eligible, and the label is pane-derived and prompt-injectable, so a pattern must anchor on chrome only that CLI draws. → [architecture-invariants#the-watching-signal-a-quiet-pane-that-is-not-waiting-for-you](docs/architecture-invariants.md#the-watching-signal-a-quiet-pane-that-is-not-waiting-for-you). Tests: `test/session-watching.test.ts`, `test/watching-no-alert.test.ts`.
|
||||
|
||||
**An exited agent in a live pane** (`paneExit`, #446): panes use `remain-on-exit on`, so `/exit` leaves a pane, session and pid that look alive; `TmuxManager.startPaneExitWatcher()` publishes `SessionState.paneExit` via `session:updated`. ⚠️ Never set `status: 'error'` or null the `pid` for it; the field is TRI-STATE (absent = UNKNOWN, never alive, scoped by `Session.paneExitApplies`); an absent `#{pane_dead_status}` is not 0; a path that starts a command in a pane must clear the record AND persist. A clean exit is CLOSED via `cleanupSession()` (`pane-exit-sweep.ts`): only an explicit numeric status 0 with no signal, confirmed by 2 reads, with no start/attach in flight (`paneLifecycleInFlight`) and not within 10 s of one (a startup error keeps its row); a crashed agent keeps its row. → [architecture-invariants#an-exited-agent-in-a-live-pane-paneexit](docs/architecture-invariants.md#an-exited-agent-in-a-live-pane-paneexit)
|
||||
**An exited agent in a live pane** (`paneExit`, #446): panes use `remain-on-exit on`, so `/exit` leaves a pane, session and pid that look alive; `TmuxManager.startPaneExitWatcher()` publishes `SessionState.paneExit` via `session:updated`. ⚠️ Never set `status: 'error'` or null the `pid` for it; the field is TRI-STATE (absent = UNKNOWN, never alive, scoped by `Session.paneExitApplies`); an absent `#{pane_dead_status}` is not 0; a dead pane may have NO pid (tmux 3.8 prints `#{pane_pid}` blank), so never skip a no-pid row whose `#{pane_dead}` tmux answered, and never signal the recorded pid of a dead pane in `killSession()` (dead = flag 1 plus a blank pid or a `#{pane_dead_time}`; a pid below 2 is no pid, since an empty pane prints 0 before tmux 3.8); a path that starts a command in a pane must clear the record AND persist. A clean exit is CLOSED via `cleanupSession()` (`pane-exit-sweep.ts`): only an explicit numeric status 0 with no signal, confirmed by 2 reads, with no start/attach in flight (`paneLifecycleInFlight`) and not within 10 s of one (a startup error keeps its row); a crashed agent keeps its row. → [architecture-invariants#an-exited-agent-in-a-live-pane-paneexit](docs/architecture-invariants.md#an-exited-agent-in-a-live-pane-paneexit)
|
||||
|
||||
**Dead-pane respawn resume pin** (`_buildRespawnPaneOptionsWithResumePin()`, session.ts): recovering a dead pane, like a custom-model `restartCli()`, must pin the conversation or claude refuses the reused `--session-id`. The pin takes the first transcript-backed candidate (chain tail, launch seed, own id), never `_claudeSessionId`, adds nothing when none is backed, and is never applied to remote or docker sessions. → [architecture-invariants#dead-pane-respawn-the-resume-pin](docs/architecture-invariants.md#dead-pane-respawn-the-resume-pin)
|
||||
|
||||
**Workspace-trust dialog auto-accept** (`session-trust-dialog.ts`, pure): Claude Code's per-directory trust dialog is always answered yes, or the session is stuck. ⚠️ Match the compacted SCREEN (`compactScreenText()`, all whitespace removed), never the stream (tmux sends words joined by cursor-forwards, not spaces). ⚠️ Never answer with a blind `\r` (newer versions highlight "No, exit" first): `trustDialogNextKey()` returns ONE key per re-read frame (arrow, then Enter only once `❯` is on the trust option), and the LAST marked option wins. ⚠️ All three guards must hold: startup window `TRUST_DIALOG_WINDOW_MS` (90s), two-marker match (`isTrustDialogScreen`), attempt cap `TRUST_DIALOG_MAX_ATTEMPTS` (6). ⚠️ Read `capturePaneText()`; only a direct-PTY session falls back to a SHORT buffer tail. ⚠️ The scan must schedule its own next read (`_trustDialogTimer`, cleared in `_clearAllTimers()`), not rely on PTY output, and a throttled read is DEFERRED onto that timer, never dropped (the dialog's paint is often the pane's last output); a stopped session never scans. → [architecture-invariants#workspace-trust-dialog-auto-accept](docs/architecture-invariants.md#workspace-trust-dialog-auto-accept)
|
||||
|
||||
**Process-tree walks are bounded** (`proc-tree.ts`, pure): `collectDescendants(pid, byParent)` is the ONE descendant traversal, fed by one cached `ps -eo pid=,ppid=` snapshot (`refreshProcSnapshot()` in tmux-manager.ts: async, in-flight-shared, and ANY error discards the result rather than caching a truncated `ps`). ⚠️ Never walk a process tree with per-node `pgrep` or unbounded recursion (the unbounded version took a machine down): the walk must terminate on cycles, cap depth (`PROC_WALK_MAX_DEPTH`) and node count (`PROC_WALK_MAX_NODES`), and never spawn anything. ⚠️ Keep it in its own module so the test exercises the shipped code, and report truncation through `onTruncated` naming both caps, never silently. → [architecture-invariants#process-tree-walks-are-bounded](docs/architecture-invariants.md#process-tree-walks-are-bounded)
|
||||
**Process-tree walks are bounded** (`proc-tree.ts`, pure): `collectDescendants(pid, byParent)` is the ONE descendant traversal, fed by one cached `ps -eo pid=,ppid=` snapshot (`refreshProcSnapshot()` in tmux-manager.ts: async, in-flight-shared, and ANY error discards the result rather than caching a truncated `ps`). ⚠️ Never walk a process tree with per-node `pgrep` or unbounded recursion (the unbounded version took a machine down): the walk must terminate on cycles, cap depth (`PROC_WALK_MAX_DEPTH`) and node count (`PROC_WALK_MAX_NODES`), and never spawn anything. ⚠️ Keep it in its own module so the test exercises the shipped code, and report truncation through `onTruncated` naming both caps, never silently. ⚠️ **A kill never takes pid 0 or 1** (`isSignalablePid()`): the children of pid 0 are the whole machine, and tmux really answers 0 for an empty pane (`split-window ''`), which the pane list at server start records as `session.pid`; a close then signalled every process of the account. `killSession` signals only through `signalProcess()`, walks nothing for such a pid and leaves the close to `tmux kill-session`. Never call `process.kill` in tmux-manager.ts with a signal anywhere else, and never drive a real `killSession` from a script: stub `process.kill` in vitest (`test/kill-pid-guard.test.ts`). → [architecture-invariants#process-tree-walks-are-bounded](docs/architecture-invariants.md#process-tree-walks-are-bounded)
|
||||
|
||||
**A `persistent: false` chokidar watcher stops on its first error**: ⚠️ its `'error'` handler goes through `closeWatcherOnError()` (`utils/close-watcher-on-error.ts`), never a bare log or `close()`. chokidar 3 retries a failed `fs.watch` (EMFILE once the inotify instances are used up, ENOSPC once the watches are) on the parent directory up to `/` forever, logging every pass (one server wrote 174 GiB of log that way); a bare `close()` turns the follow-up TypeError into an unhandled rejection, and a callback already in flight can reopen it through `add()`. The watcher's own poll must cover what it watched and create it again on a later tick (`TeamWatcher`, `WorkflowRunWatcher`): chokidar 3 reports a one-off ENOENT race (a new file gone between its `stat` and `watch`) through the same TypeError, so a watcher that stayed closed would end live updates until a restart. Tests: `test/watcher-fs-watch-failure.test.ts`.
|
||||
|
||||
**Auto-resume on usage limit** (opt-in per session, top of the Respawn tab): when Claude halts on a subscription limit, `usage-limit-patterns.ts` (pure, unit-tested) parses the reset time and `SessionAutoOps` arms a timer for reset+2min, then sends Esc + `continue`. ⚠️ Respawn cycles are blocked while paused (`isLimitPaused` guard in `onIdleDetected`), which is what prevents `/clear` from wiping the paused conversation. Claude-mode only. → [architecture-invariants#auto-resume-on-usage-limit](docs/architecture-invariants.md#auto-resume-on-usage-limit)
|
||||
|
||||
@@ -182,11 +186,11 @@ 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)
|
||||
|
||||
**DeepSeek web UI** (`POST`/`GET`/`DELETE /api/deepseek/web`, `deepseek-web-server.ts`): the Run menu's "DeepSeek web UI..." entry supervises ONE background `dsh web` child process, deliberately **NOT a shell session**. ⚠️ Every piece is load-bearing: exactly one server (a second click REUSES it), restarted when the browser authority changes (`--trusted-host`, last asker wins), killed on shutdown via `stopDeepSeekWeb()` (the detached child would otherwise outlive Codeman and hold its port), and failures returned to the caller. ⚠️ Never hardcode the port: search from 3080 across 40, detect free ports by BINDING, then wait for the server to really answer. ⚠️ Both `POST` and `DELETE` must stay behind `canUsernameRunPrivilegedCommands` (booting a profile runs its plugin code; the server is shared). → [architecture-invariants#deepseek-web-ui](docs/architecture-invariants.md#deepseek-web-ui)
|
||||
**DeepSeek web UI** (`POST`/`GET`/`DELETE /api/deepseek/web`, `deepseek-web-server.ts`): the Run menu's "DeepSeek web UI..." entry supervises ONE background `dsh web` child process, deliberately **NOT a shell session**. ⚠️ Every piece is load-bearing: exactly one server (a second click REUSES it, but only for the same starter and while its cookie works), restarted when the browser authority changes (`--trusted-host`, last asker wins), killed on shutdown via `stopDeepSeekWeb()` (the detached child would otherwise outlive Codeman and hold its port), and failures returned to the caller. ⚠️ Never hardcode the port: search from 3080 across 40, detect free ports by BINDING, then wait for the server to really answer. ⚠️ Both `POST` and `DELETE` must stay behind `canUsernameRunPrivilegedCommands` (booting a profile runs its plugin code; the server is shared). ⚠️ The launch token is traded for dsh's session cookie once at startup, and the web-tab proxy presents it on both legs only to the `managed: 'deepseek-web'` tab on the `127.0.0.1` port it was minted for (in multi-user mode, only to a granted owner who started it). → [architecture-invariants#deepseek-web-ui](docs/architecture-invariants.md#deepseek-web-ui)
|
||||
|
||||
**Case rename** (`POST /api/cases/:name/rename`, `src/case-rename.ts`; `docs/wiki/Core-Concepts.md#case`): a case under the cases dir is its folder name and always moves; a linked case renames its alias and moves its real folder only with `renameFolder`; remote and Docker cases are refused. ⚠️ A folder that sessions have open is the hazard: live sessions at or under it make the route answer `409 requiresStop` with their names, and only `stopSessions: true` ends them (via `ctx.cleanupSession`: closed like a tab close, uploads included, nothing is restarted); the free-target pre-check runs before that and refuses a dangling symlink too (`lstat`, as `moveCaseFolder` does), so no session is ended for a move that cannot happen. `withCaseLock` holds the old and new paths for the whole operation (`isCasePathLocked`; the `Session` constructor throws for a working directory inside a held path, so nothing is constructed mid-move). ⚠️ A create awaits the owner's layout lock and a settings read between `new Session` and the server's map, where the rename looks for open sessions, so the constructor also records the session (`noteCaseSessionStarting`) until `registerSessionWithLayout()` or `stop()` settles it (30 s TTL for one that never registers), and a folder move refuses `409` with `renameCode: "BUSY"` while one is recorded at or under the folder (`isCaseSessionStarting`, checked in the same tick that takes the lock); an alias-only rename is not refused. A create whose path was validated before the move but whose `Session` is constructed after it is not covered (the plain check-then-use race of any create path), `moveCaseFolder` refuses an existing target itself (POSIX `rename` would silently replace an EMPTY directory) and retries `EBUSY`/`EPERM`/`EACCES` before answering `423 LOCKED`. If the registries (`linked-cases.json`, `caseOrder`, `lastUsedCase`, `lastPickedCase`, `caseSettings`) fail after the move, `settings.json` and the folder are put back (a failed move-back says the folder is now at the new path), and an error after `stopSessions` carries `stoppedSessions`. Claude Code keys history by path (`claudeProjectDirName`: every non-alphanumeric becomes `-`), so `<claude config>/projects/<old>` is renamed too, or merged entry by entry, never overwriting, into one already at the new key (case delete never removes history, so an earlier case of the new name leaves one); other CLIs' history, Docker bind mounts, `git worktree` links, cron jobs' `workingDir`, Claude history of subfolder sessions and Claude Code's per-project entry in `~/.claude.json` (local-scope `mcpServers`, `allowedTools`, trust; writing another CLI's config is the opt-in MCP sync's job) are NOT migrated. The history scanner prefers the decoded project key over a transcript's `cwd` that no longer exists, so Resume follows a rename. Only an admin's rename touches the server-wide `settings.json` (`caseOrder`, `lastUsedCase`, `lastPickedCase`, `caseSettings`); the owner's default session group is carried across with `TabLayoutService`. `settings.json` is written before `linked-cases.json`, so a failed or refused registry write puts `settings.json` back and leaves the registry as it was. ⚠️ Every write to `linked-cases.json` (link, unlink, rename, and a create or clone into a custom folder) goes through `mutateLinkedCases()` (`src/web/linked-cases-writer.ts`: serialized, temp file + rename, and a file that does not parse is refused, never read as `{}`; the one direct writer is config-backup restore, `restoreConfigBackup()`, which must work on such a file), and a check that must still hold when the entry is written (the name is free; for a rename, the old entry still names the folder) runs INSIDE its callback: two clones that claimed one name used to both pass a re-read made outside it and both answer success. Pinned by `test/linked-cases-writer.test.ts`, and for a rename by `test/routes/case-rename-routes.test.ts`.
|
||||
|
||||
@@ -194,7 +198,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
|
||||
⚠️ **llama-swap endpoints** (one model at a time): the apply routes check `GET /running` and return `requiresConfirmation` before evicting a model another live session uses; `confirmedSwap` and `confirmedContext` are SEPARATE flags and must stay so. Claude alone gets a context floor (`CLAUDE_MIN_SAFE_CONTEXT_TOKENS`); context is parsed from `/running`'s `cmd`, never trusted from `/props`. The floor also divides that context by the model's parallel slot count (`modelSlotCounts`: `--parallel`/`-np` from `cmd`, else `/props` `total_slots`; `perSlotContext()`), and `/props` only ever RAISES that warning: it supplies the context only when `cmd` states none and the count only when `cmd` has no `--parallel`, never a larger pool. `/props` is probed once per launch command (it refreshes llama-swap's last-use time, so a `ttl` would never expire), and a `/props` context beside an explicit `--parallel N` is already per slot, so it is not divided again. Backend log lines come from llama-swap's `/api/events` `upstream` source, never `/logs`. → [architecture-invariants#custom-model-endpoint-profiles](docs/architecture-invariants.md#custom-model-endpoint-profiles)
|
||||
|
||||
**Local model recommendation** (`GET /api/local-model`, `src/local-model/`, `src/config/local-model-catalog.ts`, `src/types/local-model.ts`; EXPERIMENTAL): the server looks at the Mac it runs on and says which local coding model fits it and with which agent CLI. ⚠️ The READ side stays read-only: the probe, the catalogue and `recommend()` download nothing, install nothing and write nothing; everything that changes the machine is the install below, behind an explicit request. Apple silicon macOS only: anywhere else the answer is a `200` with verdict `none` (reasons `not-macos`, `intel`, `memory`, `disk`, `macos`, `no-harness`), and a failed probe is an answer, never a 500. The probe (`hardware.ts`) is ONE bounded async spawn of `/usr/sbin/sysctl` WITHOUT `-n`, parsed as `key: value` lines by the pure `parseSysctl()`, plus `statfs` of the data dir (probed bounded first, #516) and `node:os` fallbacks, cached 60 s; ⚠️ never `system_profiler`, never a second spawn, and `iogpu.wired_limit_mb` of 0 means not set. The catalogue is a compiled constant validated by a Zod schema: ⚠️ no override file and no runtime data, and a model id is `name:tag` in lowercase with no slash (`LOCAL_MODEL_ID_PATTERN`, so an id can never name another registry host). ⚠️ A harness is a catalogue ROW (`{ cli, minContext, rank, gated?, slowFirstTurn? }`) plus a `HarnessFact` built from the CLI registry at call time (`harness-facts.ts`); no code compares a CLI id (both id-branching guards scan these files). `recommend()` (`recommend.ts`) is pure. ⚠️ A model's need is its PEAK (`bytes + heldBytesPerToken * context + overheadBytes + peakExtraBytes`, measured on a Mac for one row and marked `estimated` on the others), and every row names its `runner` (`mlx` or `llamacpp`, the build a Mac really pulls) and carries figures of its OWN: computed from its model's config.json by that runner's rule (catalogue header, MEMORY), never borrowed from another row; `test/local-model-catalog.test.ts` recomputes them, and the `llamacpp` rows assume the runtime's `OLLAMA_KV_CACHE_TYPE=q8_0`, `LLAMA_ARG_CACHE_RAM=1024` and `LLAMA_ARG_CTX_CHECKPOINTS=8` (`runtimeEnv()`) and count what llama-server keeps beside the cache (8 context checkpoints of the recurrent or sliding-window state, and for a GGUF with a prediction layer one rollback copy of the recurrent state per drafted token and that layer's cache in f16), so change the two together. The need is judged against a budget that is `estimated` until the runtime ran and `measured` from then on (`RecommendOptions.measuredTotalBytes`). ⚠️ Ranking, lexicographic: tested on a Mac like this first, then speed `ok` before `unknown` before `slow`, then model rank, harness rank, larger context; the fit grade decides whether a row is listed and what it says, it does NOT sort, so a model is offered at the largest context it fits at. ⚠️ The answer lists EVERY model that fits, and the install accepts only a listed row: `MAX_ALTERNATIVES` is a bound above the catalogue's size (`test/local-model-catalog.test.ts` fails for a catalogue that outgrows it), never a way to shorten the list. ⚠️ `limited` is a statement about the MAC (no model with 12 billion parameters or more fits), judged before the disk filter and whatever the pick is; a small pick under `ok` carries `noteSmallPick`, and a model left out for disk space is named in `noteDiskDropped`, never dropped in silence. ⚠️ The word "Recommended" exists only in `headlineTested`, and the tag "Tested on a Mac like this" only on a row whose model has a `tested` entry for exactly this chip, memory size and harness. ⚠️ Speed is `ok`/`slow`/`unknown`, graded on the unrounded figure, and a chip in no chips row is `unknown`: never guess a bandwidth. ⚠️ ONE unit for every computed size a person reads: decimal GB text from `formatGb()` (`format.ts`), sent beside the bytes, and the browser never divides bytes; the one exception is the installed memory, shown as `memClassGb` (the size the Mac is sold as, 48 and not 51.5). ⚠️ Every sentence the server chooses is a `LOCAL_MODEL_LABELS`, `LOCAL_MODEL_TAG_LABELS` or `LOCAL_MODEL_INSTALL_LABELS` text with `{placeholder}` slots filled from `vars` (no apostrophe in a text: the zh-CN key is single-quoted), and each needs a zh-CN entry. Admin only in multi-user mode (403 before anything is probed). Tests: `test/local-model-*.test.ts`, `test/routes/local-model-routes.test.ts`. Window rules: `src/web/CLAUDE.md` (Run a model on this Mac). → `docs/api-reference.md` (Local model), `docs/versioning-policy.md`
|
||||
**Local model recommendation** (`GET /api/local-model`, `src/local-model/`, `src/config/local-model-catalog.ts`, `src/types/local-model.ts`; EXPERIMENTAL): the server looks at the Mac it runs on and says which local coding model fits it and with which agent CLI. ⚠️ The READ side stays read-only: the probe, the catalogue and `recommend()` download nothing, install nothing and write nothing; everything that changes the machine is the install below, behind an explicit request. Apple silicon macOS only: anywhere else the answer is a `200` with verdict `none` (reasons `not-macos`, `intel`, `memory`, `disk`, `macos`, `no-harness`), and a failed probe is an answer, never a 500. The probe (`hardware.ts`) is ONE bounded async spawn of `/usr/sbin/sysctl` WITHOUT `-n`, parsed as `key: value` lines by the pure `parseSysctl()`, plus `statfs` of the data dir (probed bounded first, #516) and `node:os` fallbacks, cached 60 s; ⚠️ never `system_profiler`, never a second spawn, and `iogpu.wired_limit_mb` of 0 means not set. The catalogue is a compiled constant validated by a Zod schema: ⚠️ no override file and no runtime data, and a model id is `name:tag` in lowercase with no slash (`LOCAL_MODEL_ID_PATTERN`, so an id can never name another registry host). ⚠️ A harness is a catalogue ROW (`{ cli, minContext, rank, gated?, slowFirstTurn? }`) plus a `HarnessFact` built from the CLI registry at call time (`harness-facts.ts`); no code compares a CLI id (both id-branching guards scan these files). `recommend()` (`recommend.ts`) is pure. ⚠️ A model's need is its PEAK (`bytes + heldBytesPerToken * context + overheadBytes + peakExtraBytes`, measured on a Mac for two rows, the MLX builds of Qwen3.6 35B-A3B and Muse Glimmer 30B, and marked `estimated` on the others), and every row names its `runner` (`mlx` or `llamacpp`, the build a Mac really pulls) and carries figures of its OWN: computed from its model's config.json by that runner's rule (catalogue header, MEMORY), never borrowed from another row; `test/local-model-catalog.test.ts` recomputes them, and the `llamacpp` rows assume the runtime's `OLLAMA_KV_CACHE_TYPE=q8_0`, `LLAMA_ARG_CACHE_RAM=1024` and `LLAMA_ARG_CTX_CHECKPOINTS=8` (`runtimeEnv()`) and count what llama-server keeps beside the cache (8 context checkpoints of the recurrent or sliding-window state, and for a GGUF with a prediction layer one rollback copy of the recurrent state per drafted token and that layer's cache in f16), so change the two together. The need is judged against a budget that is `estimated` until the runtime ran and `measured` from then on (`RecommendOptions.measuredTotalBytes`). ⚠️ Ranking, lexicographic: tested on a Mac like this first, then speed `ok` before `unknown` before `slow`, then model rank, harness rank, larger context; the fit grade decides whether a row is listed and what it says, it does NOT sort, so a model is offered at the largest context it fits at. ⚠️ The answer lists EVERY model that fits, and the install accepts only a listed row: `MAX_ALTERNATIVES` is a bound above the catalogue's size (`test/local-model-catalog.test.ts` fails for a catalogue that outgrows it), never a way to shorten the list. ⚠️ `limited` is a statement about the MAC (no model with 12 billion parameters or more fits), judged before the disk filter and whatever the pick is; a small pick under `ok` carries `noteSmallPick`, and a model left out for disk space is named in `noteDiskDropped`, never dropped in silence. ⚠️ The word "Recommended" exists only in `headlineTested`, and the tag "Tested on a Mac like this" only on a row whose model has a `tested` entry for exactly this chip, memory size and harness. ⚠️ Speed is `ok`/`slow`/`unknown`, graded on the unrounded figure, and a chip in no chips row is `unknown`: never guess a bandwidth. ⚠️ ONE unit for every computed size a person reads: decimal GB text from `formatGb()` (`format.ts`), sent beside the bytes, and the browser never divides bytes; the one exception is the installed memory, shown as `memClassGb` (the size the Mac is sold as, 48 and not 51.5). ⚠️ Every sentence the server chooses is a `LOCAL_MODEL_LABELS`, `LOCAL_MODEL_TAG_LABELS` or `LOCAL_MODEL_INSTALL_LABELS` text with `{placeholder}` slots filled from `vars` (no apostrophe in a text: the zh-CN key is single-quoted), and each needs a zh-CN entry. Admin only in multi-user mode (403 before anything is probed). Tests: `test/local-model-*.test.ts`, `test/routes/local-model-routes.test.ts`. Window rules: `src/web/CLAUDE.md` (Run a model on this Mac). → `docs/api-reference.md` (Local model), `docs/versioning-policy.md`
|
||||
|
||||
**Local model install** (`POST /api/local-model/install|use|cancel|resume|runtime|agent`, `DELETE /api/local-model`, `DELETE /api/local-model/models`; `src/local-model/{install-job,runtime,ollama-client,connect,state-store,paths,developer-tools}.ts`; EXPERIMENTAL, admin only in multi-user mode on EVERY verb; guide `docs/local-models.md`): installs the chosen model on the Mac the server runs on and ends on a session of the coding agent running on it. ONE job of five idempotent steps (`runtime`, `model`, `verify`, `agent`, `connect`; `agent` only when the coding agent is missing), a pure reducer (`reduceInstallJob()`) over three tables in `install-job.ts` driven by one service per process (`getLocalModelService()`); the window polls the GET once a second, no SSE event. ⚠️ A LIBRARY with ONE model in use: the store may hold several models and `LocalModelStateFile.library` lists the ones that passed the check (written by the service when `verify` passes, carried by the reducer, dropped by `remove`; an `installed` file without it counts its one model, `libraryOf()`), but the endpoint record lists ONE model, the runtime holds one and only the state's model is ever launched: never widen the record to every checked model. `install` from `installed` adds a model (the earlier one stays: `replacedModelFor()` never names a library model), `use` switches to a checked one (a job of `USE_JOB_STEPS`, `verify` then `connect`; the stored digest is compared before anything is loaded, else `model-changed`), and both answer 409 `sessions-open` while a live session uses the endpoint; until such a job ends `installed`, no session starts (`launchRefusal()` answers `job-unfinished`). `DELETE /api/local-model/models` deletes ONE model by its NAME (`LOCAL_MODEL_ID_PATTERN`, never a path), only a name of the server's own listing, only through the runtime's own delete, never the model of the installation or of the current job (409 `model-active`), and it is no reducer event: its row is the `delete-model` action of `INSTALL_STATE_TABLE`. ⚠️ The view's `library` (state entries joined with the runtime's `/api/tags`: `ready`, `changed`, `missing`, `unverified`) and `store` (the blob folder's size, `measureModelStore()`) are cached (5 s, 30 s), refreshed in the background and thrown away by every verb and step that changes them (`forgetStore()`): never ask the runtime or the disk on the one-second poll, and a runtime that does not answer keeps the last list. ⚠️ Layout only through `localModelPaths()` (all `dataPath()`): `local-model/runtime/ollama-<version>/`, `local-model/models/`, `local-model/home/` (the runtime's PRIVATE HOME, so the user's `~/.ollama` is never touched) and the state file `local-model.json` (0600, ONE serialized writer, total reader, holds NO path); nothing is written or deleted outside `local-model/` except that file and the two writes of the connect step. ⚠️ The runtime pin (`OLLAMA_RUNTIME_PIN`: version, URL, size, sha256) is a COMPILED constant no file, setting or request may supply; the hash is compared BEFORE anything is unpacked. ⚠️ The runtime is a NON-detached child whose environment comes from the `runtimeEnv()` ALLOWLIST, never `process.env` (no `CODEMAN_*`, none of the user's `OLLAMA_*`); the port is chosen ONCE by binding (from 11435, never 11434) and stored; a listener on it is adopted or replaced only when its stored pid runs a binary under OUR runtime folder, anything else is `port-in-use`; started at boot when installed and enabled, max 3 restarts, SIGTERM at shutdown beside `stopDeepSeekWeb()`; under vitest nothing spawns or fetches. ⚠️ Consent is bound to the size: `acknowledgedBytes` must equal the server's own total (`Candidate.installBytes`) or the answer is 409 `size-changed`; the model, context and CLI must be a row the current recommendation offers (400). ⚠️ ONE job at a time (409 `job-running`); a job a restart interrupted comes back `paused` and NEVER continues without a click (so `shutdown()` writes nothing), and an interrupted step is never recorded as failed. ⚠️ An event the transition table does not list is refused (same object back, 409 `wrong-state`): add a row to the table, never a special case. ⚠️ The budget is MEASURED from the runtime's "inference compute" log line and the model judged against it BEFORE it is downloaded. ⚠️ The pull stream is parsed incrementally (about 1.4 million lines for 23 GB): never buffer it, never write state per line. ⚠️ A failure is a code with ONE next step (`LOCAL_MODEL_ERROR_NEXT`), never a bare "failed"; a probe that ended on its token limit is `probe-unfinished`, not `no-tool-call`. ⚠️ The coding agent is installed through the shared runner `src/cli-install-runner.ts` (extracted from `cli-registry-routes.ts`, ONE install slot per CLI for both callers) with `stockInstallCommand()`, the COMPILED stock command, never the `clis.json`-merged one (this path has no `cliManagementEnabled` gate); only for a catalLine truncated
|
||||
|
||||
@@ -202,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)
|
||||
|
||||
@@ -224,9 +228,9 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
|
||||
**Circuit breakers**: the Ralph breaker prevents respawn thrashing (`CLOSED` → `HALF_OPEN` → `OPEN`; reset via `/api/sessions/:id/ralph-circuit-breaker/reset`). **Distinct: the PTY-exit breaker** (`session-pty-exit-breaker.ts`) trips after repeated rapid PTY exits and blocks auto-restarts. ⚠️ It resets ONLY via an explicit `{clearBreaker:true}` body on `POST /api/sessions/:id/interactive`; the frontend's auto-reattach in `selectSession()` sends no body and must never clear it. → [architecture-invariants#circuit-breakers-ralph-and-pty-exit](docs/architecture-invariants.md#circuit-breakers-ralph-and-pty-exit)
|
||||
|
||||
**Full-scrollback replay**: `GET /api/sessions/:id/terminal?full=1` returns the whole tmux scrollback ALONE (`source='mux-full-history'`), superseding the byte buffer. First load of each non-shell TUI session requests it (`_fullHistoryLoaded`); Shell selection, drop recovery, clear and a tile's load use `SHELL_LOAD_QUERY` (constants.js), a bounded window of tmux's RENDERED history (`?full=1&tail=1MiB&alt=recording&lines=10000`), never the raw byte recording, whose full-screen repaints replayed at another pane height push copies of their top row into scrollback; the route reports a client `lines=` bound below the history ceiling that left lines in tmux as `truncationReason: 'tail'`, and `alt=recording` falls back to the visible frame over the tailed byte recording when the pane is in the alternate screen (a nested tmux in a remote or Docker case keeps no tmux history; vim/less take it too while open). A Shell scroll-to-top pulls a bounded `?full=1&tail=` window (a window no longer than the browser's buffer is skipped before the downgrade guard, so it never marks the session exhausted); the unbounded pull stays behind **Load full history**. A Shell split-pane Pane B has its own copy of the bounded pull against its own xterm (`TerminalTile._pullHistory`, terminal-tile.js); keep the two in step. → [architecture-invariants#split-pane-sessions](docs/architecture-invariants.md#split-pane-sessions) ⚠️ The capture ends with a RELATIVE cursor move back to the pane's caret (never `CUP`), so no line-deleting transform may run over it; those skips key on `isFullCapture`, never on `?full=1` alone. ⚠️ A re-pull must never shrink the buffer (`_replayWouldShrinkBuffer()`). ⚠️ `captureCols`/`captureRows` are absent when no frame was positioned: test `Number.isFinite`, never truthiness. ⚠️ A frame dropped at the 128 KiB render cap MUST be recovered, and the recovery verifies itself: `_scheduleDroppedOutputRecovery` re-arms (bounded by `DROP_RECOVERY_MAX_ATTEMPTS`) while `_onSessionNeedsRefresh` reports no repaint, but never after a capture-fetch `'deadline'`. → [architecture-invariants#full-scrollback-replay](docs/architecture-invariants.md#full-scrollback-replay)
|
||||
**Full-scrollback replay**: `GET /api/sessions/:id/terminal?full=1` returns the whole tmux scrollback ALONE (`source='mux-full-history'`), superseding the byte buffer. First load of each non-shell TUI session requests it (`_fullHistoryLoaded`); Shell selection, drop recovery, clear and a tile's load use `SHELL_LOAD_QUERY` (constants.js), a bounded window of tmux's RENDERED history (`?full=1&tail=1MiB&alt=recording&lines=10000`), never the raw byte recording, whose full-screen repaints replayed at another pane height push copies of their top row into scrollback; the route reports a client `lines=` bound below the history ceiling that left lines in tmux as `truncationReason: 'tail'`, and `alt=recording` falls back to the visible frame over the tailed byte recording when the pane is in the alternate screen (a nested tmux in a remote or Docker case keeps no tmux history; vim/less take it too while open). A Shell scroll-to-top pulls a bounded `?full=1&tail=` window (a window no longer than the browser's buffer is skipped before the downgrade guard, so it never marks the session exhausted); the unbounded pull stays behind **Load full history**. A Shell split-pane Pane B has its own copy of the bounded pull against its own xterm (`TerminalTile._pullHistory`, terminal-tile.js); keep the two in step. → [architecture-invariants#split-pane-sessions](docs/architecture-invariants.md#split-pane-sessions) ⚠️ The capture ends with a RELATIVE cursor move back to the pane's caret (never `CUP`), so no line-deleting transform may run over it; those skips key on `isFullCapture`, never on `?full=1` alone. ⚠️ A re-pull must never shrink the buffer (`_replayWouldShrinkBuffer()`). ⚠️ `captureCols`/`captureRows` are absent when no frame was positioned: test `Number.isFinite`, never truthiness. ⚠️ A frame dropped at the 128 KiB render cap MUST be recovered, and the recovery verifies itself: `_scheduleDroppedOutputRecovery` re-arms (bounded by `DROP_RECOVERY_MAX_ATTEMPTS`) while `_onSessionNeedsRefresh` reports no repaint, but never after a capture-fetch `'deadline'`. ⚠️ **Reload history** (#814, manual early repair; rules in the invariants paragraph "Repair while reading"): only a `mux-full-history` replay whose live-output generation is unchanged since before its fetch clears `_liveOutputSinceFullPull` and `_historyReloadDismissed`; a refused or non-mux answer to a manual reload retires the action until then; and the buffer load opens BEFORE the fetch, so download-time output queues behind the replay. → [architecture-invariants#full-scrollback-replay](docs/architecture-invariants.md#full-scrollback-replay)
|
||||
|
||||
**Terminal scrollback strip + wheel/touch forwarding**: codex/claude/gemini get the FULL strip (alt-screen, `3J`, mouse DECSETs); tmux-backed opencode, copilot and pi get the MIDDLE strip (alt-screen toggles + mouse DECSETs, `3J` kept); every other tmux-backed mode (shell/antigravity/grok/deepseek/omp) gets the NARROW strip (alt-screen toggles only). Table: `CliCapabilities.altScreen` JSDoc, pinned in test/claude-scrollback-strip.test.ts. ⚠️ Gated on `useMux`: direct-PTY sessions must keep the alt screen. Wheel and touch forward only with observed `cliMouseTracking`: **Claude ≥ 2.1.187, tracked Codex, tracked Copilot, or tracked Pi**. Codex 0.163.0 fullscreen was measured with `alternate_on=1`, `mouse_any_flag=1`: one SGR report moves one transcript row; see the fresh measurement in architecture-invariants. Inline/untracked Codex retains local history or the capability-gated paging fallback. Copilot has no version gate; a stale/false tracking flag falls back to PageUp/PageDown. Pi has no version gate either, and is fullscreen by default since 1.0.0: it enables tracking once at start, so the flag is what survives a tab switch or reload (xterm's own mode does not). ⚠️ Pi deliberately has no `transcriptPageKeys`: its `tuiMode: regular` binds those keys to the editor, so paging there moves a draft's caret. Touch alone has one more branch (`_shouldForwardTouchToApp`): in any mode, a drag also forwards as SGR wheel reports while xterm ITSELF tracks the mouse with SGR encoding (an app in the pane asked for it; a tracking mode other than `x10` and `coreMouseService.activeEncoding === 'SGR'`, so DEFAULT, X10 and SGR-pixel apps fail closed), because xterm encodes a wheel there but the touch listeners consume the drag. ⚠️ `getClaudeCliVersion()` must never cache a FAILED probe. ⚠️ Hand-report clicks only while the CLI has mouse tracking on: `_shouldReportMouseToCli()` gates all three report sites on `cliMouseTracking` (from `_recordStrippedMouseMode()`, session.ts), or a plain shell prints the reports as literal text. ⚠️ A `TerminalTile` (grid tile, split Pane B) forwards the wheel as SGR reports, pages it and reports clicks through these SAME gates with itself as the target (its terminal, its session, never `activeSessionId`), and scrolls Shift+wheel itself (xterm makes it a horizontal no-op); never copy the mode lists into terminal-tile.js. ⚠️ The hollow-buffer PageUp/PageDown fallback (`_maybePageCliTranscript`) stands down when the last capture reported tmux scrollback (`paneHistoryLines` > 0: a tail replayed after a server restart carries only the attach repaint), so the gesture scrolls locally and the scroll-to-top pull loads `full=1`; 0 and unknown keep paging. Read `_logScrollRouting()` before diagnosing a scroll report. → [architecture-invariants#terminal-scrollback-strip-flavors-and-wheeltouch-forwarding](docs/architecture-invariants.md#terminal-scrollback-strip-flavors-and-wheeltouch-forwarding)
|
||||
**Terminal scrollback strip + wheel/touch forwarding**: codex/claude/gemini get the FULL strip (alt-screen, `3J`, mouse DECSETs); tmux-backed opencode, copilot and pi get the MIDDLE strip (alt-screen toggles + mouse DECSETs, `3J` kept); every other tmux-backed mode (shell/antigravity/grok/deepseek/omp) gets the NARROW strip (alt-screen toggles only). Table: `CliCapabilities.altScreen` JSDoc, pinned in test/claude-scrollback-strip.test.ts. ⚠️ Gated on `useMux`: direct-PTY sessions must keep the alt screen. Wheel and touch forward only with observed `cliMouseTracking`: **Claude ≥ 2.1.187, tracked Codex, tracked Copilot, or tracked Pi**. Which CLIs forward is the registry's `wheelForward`, published as `window.__codemanWheelForward` and never an id list in the gate, so a custom `clis.json` entry opts in with it plus `altScreen: 'strip-mux-and-mouse'` (`docs/cli-registry.md`). Codex 0.163.0 fullscreen was measured with `alternate_on=1`, `mouse_any_flag=1`: one SGR report moves one transcript row; see the fresh measurement in architecture-invariants. Inline/untracked Codex retains local history or the capability-gated paging fallback. Copilot has no version gate; a stale/false tracking flag falls back to PageUp/PageDown. Pi has no version gate either, and is fullscreen by default since 1.0.0: it enables tracking once at start, so the flag is what survives a tab switch or reload (xterm's own mode does not). ⚠️ Pi deliberately has no `transcriptPageKeys`: its `tuiMode: regular` binds those keys to the editor, so paging there moves a draft's caret. Touch alone has one more branch (`_shouldForwardTouchToApp`): in any mode, a drag also forwards as SGR wheel reports while xterm ITSELF tracks the mouse with SGR encoding (an app in the pane asked for it; a tracking mode other than `x10` and `coreMouseService.activeEncoding === 'SGR'`, so DEFAULT, X10 and SGR-pixel apps fail closed), because xterm encodes a wheel there but the touch listeners consume the drag. ⚠️ `getClaudeCliVersion()` must never cache a FAILED probe. ⚠️ Hand-report clicks only while the CLI has mouse tracking on: `_shouldReportMouseToCli()` gates all three report sites on `cliMouseTracking` (from `_recordStrippedMouseMode()`, session.ts), or a plain shell prints the reports as literal text. ⚠️ A `TerminalTile` (grid tile, split Pane B) forwards the wheel as SGR reports, pages it and reports clicks through these SAME gates with itself as the target (its terminal, its session, never `activeSessionId`), and scrolls Shift+wheel itself (xterm makes it a horizontal no-op); never copy the mode lists into terminal-tile.js. ⚠️ The hollow-buffer PageUp/PageDown fallback (`_maybePageCliTranscript`) stands down when the last capture reported tmux scrollback (`paneHistoryLines` > 0: a tail replayed after a server restart carries only the attach repaint), so the gesture scrolls locally and the scroll-to-top pull loads `full=1`; 0 and unknown keep paging. Read `_logScrollRouting()` before diagnosing a scroll report. → [architecture-invariants#terminal-scrollback-strip-flavors-and-wheeltouch-forwarding](docs/architecture-invariants.md#terminal-scrollback-strip-flavors-and-wheeltouch-forwarding)
|
||||
**Detached start + service install**: `codeman web -d` relaunches the same entry script `detached:true` (setsid); `nohup` is not what makes it survive. ⚠️ Both `-d` and `service install` must REFUSE when a server is already up on this data dir (pidfile + `/api/status` probe), or a second instance attaches to the first one's live sessions. ⚠️ Never report success not observed: poll `/api/status` until the child answers or dies. `--stop` must verify the pid still looks like Codeman (`ps -o command=`) before signalling. Unit/label names live only in `config/service-names.ts`. `service install` bakes the installing shell's PATH into the unit and never writes `CODEMAN_PASSWORD` into it. → [architecture-invariants#detached-start-and-service-install](docs/architecture-invariants.md#detached-start-and-service-install)
|
||||
|
||||
**Self-update** (App Settings → System → Updates): in-app updater for git-clone installs under a supervisor (`systemd`, `launchd`, `launchd-daemon`, `docker-compose`, else `none`). The work runs in a DETACHED `scripts/self-update.sh` writing `update-status.json`, polled across the restart; pure helpers in `src/web/self-update.ts`. ⚠️ Compose: the restart kills the script, so nothing may be appended after the `restarting` marker; the repo must stay a host bind mount over `/opt/codeman` and the image must keep devDependencies + toolchain. ⚠️ `evaluateEnvironmentGate()` refuses releases that change `server.Dockerfile`/`docker-compose.yaml` or add `.env.example` keys, re-evaluated on `POST /api/system/update`; unknowns fail OPEN, but the exit-to-restart needs `--restart-by-exit 1` (`CODEMAN_RESTART_BY_EXIT=1` only in the Compose file). ⚠️ An install with no git checkout (`install.sh` on a machine without a working git leaves the marker `.install-source`) is kind `archive`: it cannot update in place, and both the check and the UI tell it to re-run the installer, never the npm line. ⚠️ Keep the agent CLIs in `server.Dockerfile` pinned. → [docs/docker-self-update.md](docs/docker-self-update.md), [architecture-invariants#self-update](docs/architecture-invariants.md#self-update)
|
||||
@@ -247,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)
|
||||
|
||||
@@ -299,7 +303,7 @@ The terminal provider scans `terminalLinkLine()`, which extends `terminalPathLin
|
||||
| **CSRF / Origin** | Always-on cross-site Origin guard on state-changing requests. **A missing Origin is allowed** so curl/CLI and hooks keep working. ⚠️ The body parser keeps `text/plain` RAW; auto-JSON-parsing it enabled simple-request CSRF |
|
||||
| **QR Auth** | Single-use 6-char tokens (60s TTL) for tunnel login. See `docs/qr-auth-plan.md` |
|
||||
| **Sessions** | 24h cookie (`codeman_session`), auto-extend, device context audit |
|
||||
| **Rate limit** | 10 failed auth/IP → 429 (15min decay). Multi-user mode instead checks 50/IP (`AUTH_IP_FAILURE_MAX`) and 10 per (username, IP) BEFORE the password, so past either even a correct password from that IP waits (the account still logs in from another IP), plus 10 per username AFTER it (429 to wrong guesses from any IP, never to a correct password). QR and hook-secret have separate buckets, so neither can lock out login |
|
||||
| **Rate limit** | 10 failed auth/IP → 429 (15min decay). Multi-user mode instead checks 50/IP (`AUTH_IP_FAILURE_MAX`) and 10 per (username, IP) BEFORE the password, so past either even a correct password from that IP waits (the account still logs in from another IP), plus 10 per username AFTER it (429 to wrong guesses from any IP, never to a correct password). A request with NO `Authorization` header (or an empty one, which carries no guess either) is never counted and always gets the 401 challenge (a 429 never re-prompts a browser); a malformed one is counted. QR and hook-secret have separate buckets, so neither can lock out login |
|
||||
| **Hook bypass** | `/api/hook-event` + `/api/status-telemetry` skip Basic auth (localhost-only, schema-validated), but when auth is active the loopback bypass requires `X-Codeman-Hook-Secret` **unconditionally** (Codeman cannot detect a user's own loopback reverse proxy) |
|
||||
| **Lost-frame page** | The THIRD unauthenticated 200, beside the two hook routes, and the only one decided by request headers alone: a `GET`/`HEAD` carrying `Sec-Fetch-Dest: iframe\|frame`, `Accept: text/html` and mode `navigate` (or none), for a path that is NOT a registered route (never `/api/`, `/ws/`, `/q/`), is answered BEFORE the credential checks with the static web-tab recovery page (`lostWebviewFramePage`: no reflected input, `default-src 'none'` plus its own script hash, `no-store`). `/` is the one registered route also admitted, only when the request carries neither `codeman_session` nor `Authorization` (nothing in Codeman frames its own root; a sandboxed frame has neither), since the landing page masks to exactly `/` and its reload otherwise rendered Codeman inside the web tab. ⚠️ A non-browser client can set those headers, so an unauthenticated caller can tell a registered route (401) from a non-route (200) and enumerate the route table; accepted, the routes are public in `docs/api-reference.md`. Pinned by `test/webview-auth-exemption.test.ts` + `test/webview-lost-root-frame.test.ts` |
|
||||
| **Tunnel** | Enabling a tunnel **refuses** without a login (`CODEMAN_PASSWORD` or multi-user mode) unless exposure is acknowledged via `CODEMAN_ALLOW_UNAUTHENTICATED_TUNNEL=1` / `--allow-unauthenticated-tunnel` or the per-request `acknowledgeUnauthTunnel:true` action field (never persisted). `CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK` acknowledges the BIND only and never satisfies this guard (#706: `install.sh` writes it for every passwordless LAN install). The authorization is decided ONCE per request, running or not, and required again at the `start()` site: the settings-file awaits between them let a concurrent stop land, and an unauthorized enable never writes `tunnelEnabled:true`. With no login the browser asks before every enable (welcome link, tunnel panel, App Settings save that turns it on) through ONE helper, `_confirmTunnelEnable()` (settings-ui.js), which reads `loginConfigured` from `GET /api/tunnel/status` (computed in the route by the guard's own test, never in `TunnelManager`); the 403 handler is the fallback when that read fails |
|
||||
@@ -332,7 +336,7 @@ One module per domain in `src/web/routes/` (plus a barrel; `ls src/web/routes/`
|
||||
|
||||
## State Files
|
||||
|
||||
All in `~/.codeman/`: `state.json` (sessions, settings, respawn, orchestrator, cron jobs/runs, owner tab layouts, case default groups), `mux-sessions.json` (tmux recovery), `settings.json` (user prefs), `push-keys.json` + `push-subscriptions.json`, `session-lifecycle.jsonl` (audit log), `update-status.json` (self-updater progress, polled across the service restart), `docker-env-applied.json` (Compose deployment only: sha256 of the Dockerfile + compose file the running container was built from, written by `Start-Codeman.sh`, read by the self-updater's environment gate), `docker-build-source.json` (Compose deployment only: the checkout's HEAD commit and `package-lock.json` hash the `codeman-node-modules`/`codeman-dist` volumes currently reflect, written by both `Start-Codeman.sh` and a successful in-place self-update, compared to detect and refresh a volume left stale by an externally-triggered rebuild), `linked-cases.json`, `webviews.json` (saved web-tab dashboard URLs), `remote-hosts.json` + `remote-cases.json`, `docker-hosts.json` + `docker-cases.json` + `docker-exports/`, `subagent-window-states.json` + `subagent-parents.json` (subagent window layout, GET/PUT `/api/subagent-window-states`/`-parents`), `hook-secret` (per-instance), `users.json` (multi-user, mode 0600) + `admin-audit.jsonl`, `intents.json` (Read My Mind intent profiles, mode 0600), `agent-inbox.json` (agent inbox snapshot, only while `agentInboxPersistEnabled` is on, mode 0600), `edit-history/<id>.json` (Edit history panel, one store per session, every diff an agent wrote, mode 0600), `webhook.json` (webhook notifications: enabled/service/scope plus the ntfy/Slack/Discord URL, a bearer secret, so mode 0600, kept out of `settings.json` and never returned by `/api/webhook`, which is admin-only in multi-user mode), `discord.json` (Discord bridge: bot token, a bearer secret, so mode 0600, never returned by `/api/discord`, admin-only in multi-user mode) + `discord-bridge.json` (sessionId to Discord thread id), `local-model.json` (local model install: state, step, model, port, pid, digest, the checked models of the library, the previous `customModelEndpointsEnabled` value; mode 0600, holds no path, not part of a config backup) + `local-model/` (the pinned runtime, the model store and the runtime's private HOME, removed by `DELETE /api/local-model`), `agent-skill-default-migrated.json` (written once by the 1.50.0 boot migration of `agentSkillEnabled`; while it exists the migration never runs again, so deleting it would switch a stored off on at the next start; never tracked or restored), `config-backup-id` (the random id config backups record as each manifest's `origin`, so instances sharing a backup folder keep to their own snapshots; mode 0600, never tracked or restored, and deleting it unlists this instance's earlier snapshots), `backups/config/` (the default config-backup folder, moved by `configBackupDir`: `cfg-YYYYMMDD-HHMMSS/` snapshots, 0700 with 0600 files, each with a `manifest.json` of SHA-256s, the origin and the retention in force (`keepCount`/`keepDays`), which a pass falls back to when `settings.json` lacks a retention key), `certs/` (self-signed TLS for `--https`), `.env` (CODEMAN_USERNAME/PASSWORD fallback for the `codeman attach` CLI), `install.log` (installer step output, written by `install.sh`'s `run_step`) `tailscale-rename` (the node name before `install.sh` renamed it, so uninstall can offer it back), `cli-installed` (empty, touched by `install.sh` when it installs a CLI: a running server reads only its mtime, and a change ends that CLI's negative-cache backoff) and `runtime/` (the Node.js and tmux `install.sh` downloaded on its no-admin route, linked from `~/.local/bin`; all four installer-route only). Transient: `self-update-runner.sh`. Multi-user case spaces live OUTSIDE the data dir at `~/codeman-users/<username>/cases` (shared across instances like `~/codeman-cases`, override `CODEMAN_USER_SPACES_DIR`).
|
||||
All in `~/.codeman/`: `state.json` (sessions, settings, respawn, orchestrator, cron jobs/runs, owner tab layouts, case default groups), `mux-sessions.json` (tmux recovery), `settings.json` (user prefs), `push-keys.json` + `push-subscriptions.json`, `session-lifecycle.jsonl` (audit log), `update-status.json` (self-updater progress, polled across the service restart), `docker-env-applied.json` (Compose deployment only: sha256 of the Dockerfile + compose file the running container was built from, written by `Start-Codeman.sh`, read by the self-updater's environment gate), `docker-build-source.json` (Compose deployment only: the checkout's HEAD commit and `package-lock.json` hash the `codeman-node-modules`/`codeman-dist` volumes currently reflect, written by both `Start-Codeman.sh` and a successful in-place self-update, compared to detect and refresh a volume left stale by an externally-triggered rebuild), `linked-cases.json`, `webviews.json` (saved web-tab dashboard URLs), `remote-hosts.json` + `remote-cases.json`, `docker-hosts.json` + `docker-cases.json` + `docker-exports/`, `subagent-window-states.json` + `subagent-parents.json` (subagent window layout, GET/PUT `/api/subagent-window-states`/`-parents`), `hook-secret` (per-instance), `users.json` (multi-user, mode 0600) + `admin-audit.jsonl`, `intents.json` (Read My Mind intent profiles, mode 0600), `agent-inbox.json` (agent inbox snapshot, only while `agentInboxPersistEnabled` is on, mode 0600), `edit-history/<id>.json` (Edit history panel, one store per session, every diff an agent wrote, mode 0600), `webhook.json` (webhook notifications: enabled/service/scope plus the ntfy/Slack/Discord URL, a bearer secret, so mode 0600, kept out of `settings.json` and never returned by `/api/webhook`, which is admin-only in multi-user mode), `discord.json` (Discord bridge: bot token, a bearer secret, so mode 0600, never returned by `/api/discord`, admin-only in multi-user mode) + `discord-bridge.json` (sessionId to Discord thread id) + `discord-reply-dedupe.json` (replayed-reply guard: at most 2,048 Discord message IDs with timestamps, kept 7 days, mode 0600; a file that could not be read is never overwritten), `local-model.json` (local model install: state, step, model, port, pid, digest, the checked models of the library, the previous `customModelEndpointsEnabled` value; mode 0600, holds no path, not part of a config backup) + `local-model/` (the pinned runtime, the model store and the runtime's private HOME, removed by `DELETE /api/local-model`), `agent-skill-default-migrated.json` (written once by the 1.50.0 boot migration of `agentSkillEnabled`; while it exists the migration never runs again, so deleting it would switch a stored off on at the next start; never tracked or restored), `config-backup-id` (the random id config backups record as each manifest's `origin`, so instances sharing a backup folder keep to their own snapshots; mode 0600, never tracked or restored, and deleting it unlists this instance's earlier snapshots), `backups/config/` (the default config-backup folder, moved by `configBackupDir`: `cfg-YYYYMMDD-HHMMSS/` snapshots, 0700 with 0600 files, each with a `manifest.json` of SHA-256s, the origin and the retention in force (`keepCount`/`keepDays`), which a pass falls back to when `settings.json` lacks a retention key), `certs/` (self-signed TLS for `--https`), `.env` (CODEMAN_USERNAME/PASSWORD fallback for the `codeman attach` CLI), `install.log` (installer step output, written by `install.sh`'s `run_step`) `tailscale-rename` (the node name before `install.sh` renamed it, so uninstall can offer it back), `cli-installed` (empty, touched by `install.sh` when it installs a CLI: a running server reads only its mtime, and a change ends that CLI's negative-cache backoff) and `runtime/` (the Node.js and tmux `install.sh` downloaded on its no-admin route, linked from `~/.local/bin`; all four installer-route only). Transient: `self-update-runner.sh`. Multi-user case spaces live OUTSIDE the data dir at `~/codeman-users/<username>/cases` (shared across instances like `~/codeman-cases`, override `CODEMAN_USER_SPACES_DIR`).
|
||||
|
||||
**Generated top-level dirs** (all gitignored — don't edit or commit): `dist/` (esbuild output), `out/`, `coverage/`, `test-results/`, `tmp/`, `screenshots-echo-diag/`. The committed gesture bundle (`src/web/public/gesture/gesture-codeman.js`) IS tracked, but its runtime wasm/model assets (`src/web/public/gesture/wasm/`, `*.task`) are fetched and gitignored.
|
||||
|
||||
@@ -351,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
|
||||
@@ -369,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.
|
||||
|
||||
|
||||
@@ -708,7 +708,7 @@ By default Codeman launches sessions with `--dangerously-skip-permissions`, so t
|
||||
|
||||
- **Loopback by default** — the server binary binds `127.0.0.1`, reachable only from the same machine, so the no-password default is safe out of the box (the guided installer asks about network access and configures the binding + password for you). Binding a non-loopback host without `CODEMAN_PASSWORD` _starts but prints a loud warning_ with three concrete fixes (set a password, loopback + an authenticated tunnel, or explicitly acknowledge with `--allow-unauthenticated-network`)
|
||||
- **Optional auth, real sessions** — HTTP Basic via `CODEMAN_USERNAME` (default `admin`) / `CODEMAN_PASSWORD`. Success issues an opaque 256-bit `codeman_session` cookie (`randomBytes(32)`) — validated server-side, not client-signed, so it can't be forged offline (24h TTL, auto-extend, device-context audit log)
|
||||
- **Per-IP rate limiting** — 10 failed attempts → `429` with `Retry-After` (15-min decay). A valid cookie or correct password recovers _immediately_ even while an attacker hammers the same IP — important because all tunnel traffic shares one loopback IP. Multi-user mode allows 50 failures per IP instead, plus 10 failed guesses per account from one IP; both are checked before the password, so past either a correct password from that IP also waits for the decay, while the account still logs in from another IP. QR auth has its own separate limiter
|
||||
- **Per-IP rate limiting** — 10 failed attempts → `429` with `Retry-After` (15-min decay). A valid cookie or correct password recovers _immediately_ even while an attacker hammers the same IP — important because all tunnel traffic shares one loopback IP. Multi-user mode allows 50 failures per IP instead, plus 10 failed guesses per account from one IP; both are checked before the password, so past either a correct password from that IP also waits for the decay, while the account still logs in from another IP. A request with no credentials (an open tab after a restart) is never counted and always gets the login prompt. QR auth has its own separate limiter
|
||||
- **Configurable permission mode** - `--dangerously-skip-permissions` is only the default. **App Settings → Agents & CLIs → Claude → Startup Mode** can switch new sessions to Anthropic's classifier-guarded `auto` mode (low-prompt, needs Claude Code 2.1.207+), `normal` prompting, or an explicit allowed-tools list. In multi-user mode, non-granted users are forced to `auto`, and shell sessions / skip-permissions require an explicit per-user grant
|
||||
|
||||
### Always-on browser hardening (v0.9.5)
|
||||
@@ -744,6 +744,7 @@ A full-screen dashboard for your sessions, in the terminal. Same states as the w
|
||||
codeman tui # the dashboard
|
||||
codeman tui --list # numbered session list, then exit (scriptable)
|
||||
codeman tui 2 # attach straight to session 2 of that list
|
||||
codeman tui api-docs # attach straight to the live session named api-docs
|
||||
```
|
||||
|
||||
Sessions are grouped **NEEDS YOU → WORKING → IDLE → RECENT**, longest-waiting first. `↑↓`/`j`/`k` select, `1`-`9` and `[`/`]` switch between sessions, `Enter` attaches into the tmux pane (**`F1`** to come back). Inside a pane the bar across the top keeps the session strip visible and `Alt+1`-`Alt+9` switch without leaving. `y`/`n`/digit answer a pending permission dialog right from the list, `p` sends a one-line prompt, `n` starts a session and opens straight into it, `x` kills one (`y` confirms), `/` searches, `g` shows the away digest, `?` is help, `q` quits. Below 72 columns it drops the preview pane and becomes a single-column list, so it stays usable in Termius on a phone. With no server running it still starts in attach-only degraded mode.
|
||||
|
||||
@@ -741,6 +741,7 @@ Codeman 默认用 `--dangerously-skip-permissions` 启动会话,因此 Web UI
|
||||
codeman tui # 仪表盘
|
||||
codeman tui --list # 带编号的会话列表,随即退出(可用于脚本)
|
||||
codeman tui 2 # 直接附着到列表里的第 2 个会话
|
||||
codeman tui api-docs # 直接附着到名为 api-docs 的活动会话
|
||||
```
|
||||
|
||||
会话按 **NEEDS YOU → WORKING → IDLE → RECENT** 分组,等得最久的排最前。`↑↓`/`j`/`k` 选择,`1`-`9` 与 `[`/`]` 切换会话,`Enter` 附着进 tmux 面板(按 **`F1`** 回来)。在面板里,顶部的横条会一直显示会话条,`Alt+1`-`Alt+9` 不用离开就能切换。`y`/`n`/数字可以直接在列表里回答待处理的权限对话框,`p` 发送一行提示,`n` 新建会话并直接进入,`x` 杀掉一个(`y` 确认),`/` 搜索,`g` 显示离开摘要,`?` 是帮助,`q` 退出。窄于 72 列时它会去掉预览面板、变成单列列表,所以在手机上的 Termius 里依然好用。没有服务器在跑时,它仍会以仅附着的降级模式启动。
|
||||
|
||||
+16
-13
@@ -1,16 +1,19 @@
|
||||
{
|
||||
"$schema": "https://unpkg.com/knip@5/schema.json",
|
||||
"entry": [
|
||||
"scripts/*.mjs",
|
||||
"scripts/*.js",
|
||||
"scripts/watch-subagents.ts",
|
||||
"scripts/remotion/Root.tsx",
|
||||
"scripts/remotion/index.ts",
|
||||
"test/**/*.test.ts",
|
||||
"test/mobile/vitest.config.ts",
|
||||
"test/**/*.mjs"
|
||||
],
|
||||
"project": ["src/**/*.{ts,tsx}", "scripts/**/*.{ts,tsx,mjs,js}", "test/**/*.{ts,mjs}"],
|
||||
"$schema": "https://unpkg.com/knip@6/schema.json",
|
||||
"workspaces": {
|
||||
".": {
|
||||
"entry": [
|
||||
"scripts/*.{mjs,js,mts,ts}",
|
||||
"scripts/dev/*.mjs",
|
||||
"scripts/remotion/Root.tsx",
|
||||
"scripts/remotion/index.ts",
|
||||
"test/**/*.test.ts"
|
||||
],
|
||||
"project": ["src/**/*.{ts,tsx}", "scripts/**/*.{ts,tsx,mjs,js,mts}", "!scripts/remotion/**", "test/**/*.{ts,mjs}"]
|
||||
}
|
||||
},
|
||||
"ignoreExportsUsedInFile": true,
|
||||
"ignoreDependencies": ["@remotion/cli", "@remotion/transitions", "esbuild", "agent-browser"]
|
||||
"ignoreDependencies": ["@remotion/cli", "@remotion/transitions"],
|
||||
"ignoreBinaries": ["ffprobe", "ffmpeg", "wslpath", "vm_stat", "jq", "codex", "script", "mkfifo"],
|
||||
"tags": ["-knipignore"]
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
"name": "io.github.Ark0N/codeman",
|
||||
"title": "Codeman",
|
||||
"description": "Start, prompt and read AI coding agent sessions (Claude Code, Codex, Gemini CLI and more) in Codeman",
|
||||
"version": "1.51.0",
|
||||
"version": "1.52.0",
|
||||
"websiteUrl": "https://getcodeman.com",
|
||||
"repository": {
|
||||
"url": "https://github.com/Ark0N/Codeman",
|
||||
@@ -13,7 +13,7 @@
|
||||
{
|
||||
"registryType": "npm",
|
||||
"identifier": "aicodeman",
|
||||
"version": "1.51.0",
|
||||
"version": "1.52.0",
|
||||
"transport": {
|
||||
"type": "stdio"
|
||||
},
|
||||
|
||||
@@ -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',
|
||||
|
||||
+24
-1
@@ -156,10 +156,33 @@ ask() {
|
||||
fi
|
||||
}
|
||||
|
||||
# True when host $1 accepts a connection on port $2 within about a second.
|
||||
# A listening port answers at once and a closed one is normally refused at
|
||||
# once, but on WSL a connect to a closed 127.0.0.1 port is dropped and only
|
||||
# fails at the kernel's connect timeout, minutes later. No answer in time
|
||||
# reads as free. Bash 3.2 clean: no `timeout` (macOS ships none), no `wait -n`.
|
||||
port_answers() {
|
||||
local pid tries=0
|
||||
(exec 3<>"/dev/tcp/$1/$2") 2>/dev/null &
|
||||
pid=$!
|
||||
while kill -0 "$pid" 2>/dev/null; do
|
||||
if ((tries >= 20)); then
|
||||
kill "$pid" 2>/dev/null
|
||||
# The 2>/dev/null keeps bash 3.2 from printing a "Terminated" job line on
|
||||
# the first-run path; bash 5.2 prints nothing without it, so CI won't notice.
|
||||
wait "$pid" 2>/dev/null
|
||||
return 1
|
||||
fi
|
||||
tries=$((tries + 1))
|
||||
sleep 0.05
|
||||
done
|
||||
wait "$pid"
|
||||
}
|
||||
|
||||
# True when something on this host already accepts connections on the port.
|
||||
# bash's /dev/tcp needs no extra tool on Linux or macOS.
|
||||
port_in_use() {
|
||||
(exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null || (exec 3<>"/dev/tcp/::1/$1") 2>/dev/null
|
||||
port_answers 127.0.0.1 "$1" || port_answers ::1 "$1"
|
||||
}
|
||||
|
||||
first_free_port() {
|
||||
|
||||
@@ -905,6 +905,49 @@ already serves non-media text inert (`text/plain`, `nosniff`), so this just
|
||||
keeps the server from storing what it would serve or an agent could run, and
|
||||
html and svg are the ones deliberately kept out.
|
||||
|
||||
## Listing a directory (`GET /api/v1/sessions/:id/files?lazy=1`)
|
||||
|
||||
The Files panel opts into one-directory listings for local workspaces with
|
||||
`lazy=1`. Without `path`, the response lists immediate children of the selected
|
||||
root. Expanding a folder sends its returned `path` to the same endpoint.
|
||||
Directories omit `children` until the browser loads them. No descendant scan or
|
||||
shared depth/node budget is spent on a lazy listing.
|
||||
|
||||
For example, the panel starts with `?lazy=1&root=live-any`, then requests
|
||||
`?lazy=1&root=live-any&path=<returned-path>` to expand a folder. URL-encode the
|
||||
returned path; it is not necessarily relative to the selected root.
|
||||
|
||||
The success envelope contains `data.root`, `lazy: true`, `tree`, per-page
|
||||
`totalFiles`/`totalDirectories`, and `truncated`. Pages contain at most 500 entries,
|
||||
directories first and then names in ascending order. A non-final page includes
|
||||
an opaque `nextCursor`; pass it back as `cursor` with the same session, root,
|
||||
path and `showHidden` preference. A cursor is a continuation key, not a filesystem
|
||||
snapshot: changes before that key become visible on Refresh. Each request reads
|
||||
the named directory's entries and obtains file metadata only for its page.
|
||||
|
||||
`showHidden=true` adds dot-prefixed entries; the existing generated-directory
|
||||
exclusions remain. Requested folders retain workspace realpath confinement and
|
||||
bounded reachability probes. Missing folders return 404, non-directories 400,
|
||||
out-of-scope/excluded/hidden paths 403, and unavailable folders 422. Invalid or
|
||||
incompatible cursors return 400.
|
||||
|
||||
Symbolic links retain the existing file-row representation, so the browser does
|
||||
not expand directory links. Preview and download still use their existing path guards.
|
||||
|
||||
The existing `root=live`/`root=live-any` worktree rules and `worktree` metadata
|
||||
apply. Paths remain relative to `workingDir` for inside worktrees and absolute
|
||||
for followed outside worktrees. SSH sessions retain the existing listing behavior;
|
||||
this mode adds no remote filesystem capability.
|
||||
|
||||
Without `lazy=1`, recursive listing responses are unchanged. A valid `q` query
|
||||
uses the existing flat search response, including when `lazy=1` is present.
|
||||
Search retains its 5,000-entry scan budget, 1,000-match cap, depth limit (default
|
||||
5, maximum 10), and read ceiling. It reports `truncated: true` when a limit or an
|
||||
unreachable folder leaves the search incomplete. Existing `q` responses are unchanged.
|
||||
|
||||
The panel's filtering, search, pagination and retry controls are described in
|
||||
[Working With Files](wiki/Working-With-Files.md#the-file-viewer).
|
||||
|
||||
## Deleting a file (`DELETE /api/v1/sessions/:id/files?path=`)
|
||||
|
||||
The Files panel's delete button. `path` is what the listing gave the row: relative to the
|
||||
|
||||
@@ -18,7 +18,9 @@ Implementation detail extracted from `CLAUDE.md` so that file stays small enough
|
||||
|
||||
### The prefix table on Codeman's socket holds only send-prefix
|
||||
|
||||
**Browser tabs are tmux clients, so tmux's prefix table must not reach `switch-client`** (`src/tmux-prefix-table.ts`, called from `createSession` before `respawn-pane`, and from `reconcileSessions()` at boot whenever the socket lists a pane, so sessions that survived an upgrade are covered). Every keystroke typed into a browser terminal reaches the `tmux attach-session` client behind it, and app.js deliberately lets Ctrl+B through to the terminal (readline, Claude Code's "ctrl+b ctrl+b"). With tmux's stock prefix table, Ctrl+B then `(` `)` `L` `s` `w` moved that client onto ANOTHER session, which the tab then showed and typed into under the original's label; `d` detached it, `$` renamed the session, `:` opened tmux's prompt. So the table is reduced to `<prefix> send-prefix` (the socket's configured prefix, read with `show-options -gv prefix`), once per tmux server in practice: the reset only runs while `list-keys -T prefix` shows anything else. The same reduction is applied when Codeman creates the nested tmux behind a Docker case (`-L codeman-docker`) or an owned remote session (`-L codeman-remote`). Those servers set `prefix C-q` and used to keep tmux's stock prefix table, so inside the pane Ctrl+Q then `)` `(` `s` `w` or `L` ran `switch-client` / `choose-tree` on the inner server and moved its client onto a sibling session. `nestedPrefixTableResetCommands()` (bind `C-q send-prefix`, then `unbind-key -a -T prefix`, then bind it again, so a user config that left the prefix table empty cannot make `unbind-key -a` abort the `\;` chain) is appended to both create chains, before `remain-on-exit failed` on the remote chain so a remote tmux that rejects `failed` cannot drop it. Those sockets are dedicated to Codeman, so the server-global table is the right scope. A non-owned remote attach joins another Codeman's `-L codeman` and does not run it. ⚠️ Keep `send-prefix`: Claude Code inside tmux backgrounds a command with "ctrl+b ctrl+b". ⚠️ Never touch the `root` table, and tolerate (and re-bind after a reset) `C-<letter> detach-client`: `codeman tui`'s attach claims F1 and Alt+1..9 in `root` and the held-Ctrl alias `C-d` in `prefix` (`beginAttachHandoff`), and a session created mid-attach must not take that way out away. ⚠️ Key tables are server-wide. F1 and the held-Ctrl `C-d` still detach every client for the length of an attach (a way out, not a session move). **`M-1`..`M-9` do not move other clients.** `bindSwitchKey` binds them to `if-shell -F` (`tuiSwitchGuard`) so `switch-client` runs only when `#{client_tty}` is the TUI's terminal and `#{client_pid}` equals `@codeman-tui-pid`. A one-shot `client-attached[90]` hook (`tuiSwitchAttachHook`) sets that option as the TUI's client attaches, then removes itself. It is armed as the handoff's last tmux call before `spawnSync`, after the keys and the per-session bars, so only a TUI killed during the attach's own startup can leave that hook armed for its tty. A browser tab does not match, including Esc followed by a digit within `escape-time` (500 ms on tmux 3.4), which arrives as the same `M-<digit>`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-<digit>`, which writes Esc and the digit into that client's own pane, so a vim `<Esc>2j` in a browser tab is not eaten by the root binding. If the TUI is killed before `restore()`, the binding can remain, but the stored pid is the dead client and the hook will not re-arm a pty that reuses the number, so the key never switches and every client gets it in its pane through the else branch. `restore()` removes the keys only while they still name this tty, and the next attach that claims the strip releases any of these bindings first. A second TUI attach replaces the keys (one binding per key). Escape-time on Codeman's socket stays at tmux's default: lowering it would change Esc delivery for every pane, and the guard already refuses other clients. ⚠️ The consequence for every terminal attach: `Ctrl+B d` does not exist on this socket. Anything that attaches a user's terminal claims its own way out for the attach, as `beginAttachHandoff` and `scripts/tmux-manager.sh` (F1 in `root`) do, and never advertises tmux's stock chord. Tests: `test/tmux-prefix-table.test.ts` (real tmux on a private socket, driven through a pty attach client, including the nested `C-q` table), `test/tui/tui-switch-guard.test.ts` (the guarded Alt keys against a second client), the wiring in `test/tmux-manager.test.ts`, the script in `test/tmux-manager-script-attach.test.ts`.
|
||||
**Browser tabs are tmux clients, so tmux's prefix table must not reach `switch-client`** (`src/tmux-prefix-table.ts`, called from `createSession` before `respawn-pane`, and from `reconcileSessions()` at boot whenever the socket lists a pane, so sessions that survived an upgrade are covered). Every keystroke typed into a browser terminal reaches the `tmux attach-session` client behind it, and app.js deliberately lets Ctrl+B through to the terminal (readline, Claude Code's "ctrl+b ctrl+b"). With tmux's stock prefix table, Ctrl+B then `(` `)` `L` `s` `w` moved that client onto ANOTHER session, which the tab then showed and typed into under the original's label; `d` detached it, `$` renamed the session, `:` opened tmux's prompt. So the table is reduced to `<prefix> send-prefix` (the socket's configured prefix, read with `show-options -gv prefix`), once per tmux server in practice: the reset only runs while `list-keys -T prefix` shows anything else. A blank answer there is read from the full `list-keys` listing instead (its `-T prefix` lines only): tmux 3.7 through 3.7c (tmux commit 09bd686327, fixed in 3.8 by 7ec94fda08) print nothing on stdout for `list-keys -T <table>` when the table holds exactly one binding (the line goes to a status message instead), which is the reduced shape, so the reduced table read as needing a reset on every call. `codeman tui` reads its key tables the same way (`listKeyTable` in `src/tui/tui-client.ts`), or a bound key there reads as free. The same reduction is applied when Codeman creates the nested tmux behind a Docker case (`-L codeman-docker`) or an owned remote session (`-L codeman-remote`). Those servers set `prefix C-q` and used to keep tmux's stock prefix table, so inside the pane Ctrl+Q then `)` `(` `s` `w` or `L` ran `switch-client` / `choose-tree` on the inner server and moved its client onto a sibling session. `nestedPrefixTableResetCommands()` (bind `C-q send-prefix`, then `unbind-key -a -T prefix`, then bind it again, so a user config that left the prefix table empty cannot make `unbind-key -a` abort the `\;` chain) is appended to both create chains, before `remain-on-exit failed` on the remote chain so a remote tmux that rejects `failed` cannot drop it. Those sockets are dedicated to Codeman, so the server-global table is the right scope. A non-owned remote attach joins another Codeman's `-L codeman` and does not run it. ⚠️ Keep `send-prefix`: Claude Code inside tmux backgrounds a command with "ctrl+b ctrl+b". ⚠️ Never touch the `root` table, and tolerate (and re-bind after a reset) `C-<letter> detach-client`: `codeman tui`'s attach claims F1 and Alt+1..9 in `root` and the held-Ctrl alias `C-d` in `prefix` (`beginAttachHandoff`), and a session created mid-attach must not take that way out away. ⚠️ Key tables are server-wide. F1 and the held-Ctrl `C-d` still detach every client for the length of an attach (a way out, not a session move). **`M-1`..`M-9` do not move other clients.** `bindSwitchKey` binds them to `if-shell -F` (`tuiSwitchGuard`) so `switch-client` runs only when `#{client_tty}` is the TUI's terminal and `#{client_pid}` equals `@codeman-tui-pid`. A one-shot `client-attached[90]` hook (`tuiSwitchAttachHook`) sets that option as the TUI's client attaches, then removes itself. It is armed as the handoff's last tmux call before `spawnSync`, after the keys and the per-session bars, so only a TUI killed during the attach's own startup can leave that hook armed for its tty. A browser tab does not match, including Esc followed by a digit within `escape-time` (500 ms on tmux 3.4), which arrives as the same `M-<digit>`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-<digit>`, which writes Esc and the digit into that client's own pane, so a vim `<Esc>2j` in a browser tab is not eaten by the root binding. If the TUI is killed before `restore()`, the binding can remain, but the stored pid is the dead client and the hook will not re-arm a pty that reuses the number, so the key never switches and every client gets it in its pane through the else branch. `restore()` removes the keys only while they still name this tty, and the next attach that claims the strip releases any of these bindings first. A second TUI attach replaces the keys (one binding per key). Escape-time on Codeman's socket stays at tmux's default: lowering it would change Esc delivery for every pane, and the guard already refuses other clients. ⚠️ The consequence for every terminal attach: `Ctrl+B d` does not exist on this socket. Anything that attaches a user's terminal claims its own way out for the attach, as `beginAttachHandoff` and `scripts/tmux-manager.sh` (F1 in `root`) do, and never advertises tmux's stock chord. Tests: `test/tmux-prefix-table.test.ts` (real tmux on a private socket, driven through a pty attach client, including the nested `C-q` table), `test/tui/tui-switch-guard.test.ts` (the guarded Alt keys against a second client),Line truncated
|
||||
|
||||
**The attach keeps each window it dressed following the client used last** (`TUI_FOLLOW_HOOKS` in `src/tui/tui-client.ts`, `set-hook -t` per session, never `-g`). Codeman's web resize runs `resize-window` and its own attach runs `setManualWindowSize()`, and either puts the window on `manual` at the browser's size, so before this a phone opening the session mid-attach pinned the terminal to a phone-sized pane until a detach. One hook, `client-active[91]`, puts `latest` back when the TUI's client becomes the latest one again (typing, pasting or resizing the terminal after another client was used, measured on tmux 3.8). A browser resize makes the tab's client the latest one, because `Session.resize()` resizes that client's pty before tmux sees the `resize-window`. ⚠️ A forced resize at an unchanged size (Redraw, a closing pop-out window, the split pane; a browser opening a session sends none, since `selectSession` resizes without `force` and the server drops an unchanged size) would not change the pty, so tmux would keep the terminal as the latest client and its next key would undo the user's Redraw. `Session.resize()` nudges the pty one row first (`FORCED_RESIZE_NUDGE_MS`), then applies the real size: under `manual` with no attach the window ignores the client's pty, so the agent sees no change. The nudge runs only for a tmux-backed session (`_useMux` and a mux session): on a direct PTY the process is the agent itself, which would get two height changes for nothing. Cost: the first browser resize after the terminal was used changes the agent's height twice (the window is on `latest`, so the tab's pty moves it, then `resize-window` does), where master changes it once; later resizes from the same tab cost one. Height changes cost Claude's inline renderer transcript lines (#672), which is why there is no second hook on `after-resize-window`: keeping `latest` through every browser resize cost three. The hook is a constant command that reads the session option `@codeman-tui-follow` (the owner's tty), so a hook whose owner is gone does nothing. `@codeman-tui-follow-pid` records the TUI process, because a tty proves nothing: Linux hands the next terminal the pty that just closed, and a browser tab's attach client can land on it. `restore()` drops the owner first, then the hook, only while the owner is this tty, and before the window sizes are put back. `clearLeakedFollowTyping()` drops every owner this process did not arm whose recorded pid is not another live process; it runs at TUI startup and again before each attach dresses its sessions, since a leaked hook undoes `presizeWindow()` and `codeman tui <n>` has no dashboard. ⚠️ When ours is the only entry of the event, the whole session array is unset: `set-hook -u` on one index leaves an empty session-level array, which keeps hiding a global hook on that event (the same trap as `status-format[0]`). For the same reason nothing is armed while the user has a global `client-active` hook. ⚠️ The command carries no `-t`: tmux parses a hook command when it is set, and an unquoted `#{session_name}` there starts a comment. Tests: `test/tui/tui-follow-typing.test.ts` (real tmux, two pty clients), `test/session-resize-arbitration.test.ts` (the nudge).
|
||||
|
||||
### Reverse-proxy base path
|
||||
|
||||
@@ -41,7 +43,7 @@ Pure helpers unit-tested in `test/base-path.test.ts` + `test/webview-proxy.test.
|
||||
|
||||
### External CLI modes (OpenCode, Codex, Gemini, Antigravity, Pi, Grok, DeepSeek, OMP)
|
||||
|
||||
**External CLI modes (OpenCode, Codex, Gemini, Antigravity, Pi, Grok, DeepSeek, OMP, Copilot, jcode)**: `isExternalCliMode()` in `session.ts` (`mode === 'opencode' || 'codex' || 'gemini' || 'antigravity' || 'pi' || 'grok' || 'deepseek'`) gates Claude-specific behavior — Ralph tracker, BashToolParser, token/CLI-info parsing, and ❯-prompt readiness detection are all skipped (these CLIs render their own TUIs; readiness = output stabilization instead). ⚠️ **Work detection left this gate in #385** and is now per-CLI `capabilities.workDetect` data (`promptGlyph` + `workingLine`), because gating it on the mode left every Codex session reporting `idle` for its entire life; a CLI declaring neither falls back to Claude's pair, which is logic-identical to the pre-registry behaviour. All seven modes **require tmux — no direct PTY fallback** — because secrets are injected via `tmux setenv` (socket-scoped `${this.tmux()} setenv`, never on the spawn command line): OpenCode gets `OPENCODE_CONFIG_CONTENT` etc., Codex gets `OPENAI_API_KEY`/`CODEX_API_KEY`/`CODEX_HOME` (`setCodexEnvVars`), Gemini gets `GEMINI_API_KEY`/`GOOGLE_API_KEY`/`GOOGLE_CLOUD_PROJECT`/`GOOGLE_APPLICATION_CREDENTIALS`/`GOOGLE_GENAI_USE_VERTEXAI` etc. (`setGeminiEnvVars`, all in `tmux-manager.ts`). Codex specifics: command built by `buildCodexCommand()` (`--no-daemon` behind the `noDaemonFlag` gate at 0.162.0, measured against codex's own version, local launches only; `--model`, `--config model_reasoning_effort=<level>` from `reasoningEffort`, `--config sandbox_workspace_write.network_access=true` from `networkAccess` (the **Allow network access** app setting `codexNetworkAccess`, a launch default and a privileged param; ⚠️ with it on, a command in codex's sandbox can call Codeman's API and start a session outside that sandbox, password or not), `--config tui.animations=<bool>` from `animations`, `resume <id>`, `--dangerously-bypass-approvals-and-sandbox` from the `codexConfig` payload / `codexDangerouslyBypassApprovals` app setting; `renderMode` is schema-coerced to `'hybrid'`, the only supported mode). Gemini specifics: command built by `buildGeminiCommand()` (`--skip-trust` always, `--approval-mode <default|auto_edit|yolo|plan>` defaulting to `yolo` for parity with Claude's `--dangerously-skip-permissions`, `--model`, `--resume` from the `geminiConfig` payload); availability via `GET /api/gemini/status` — session/quick-start routes fail with `OPERATION_FAILED` + install hint (`npm install -g @google/gemini-cli`) when missing. Codex, Gemini, Antigravity, Pi, Grok, DeepSeek and OMP export `COLORTERM=truecolor` and unset `NO_COLOR`; `opencode` unsets `COLORTERM`. **Terminal colour env** under Session launch modes covers Claude and says which panes those declarations actually reach. Gemini joins `isAltScreenStripMode()` (Codex/Claude/Gemini are Ink TUIs that repaint inline → strip alt-screen/`3J` so scrollback survives). Codex availability via `GET /api/codex/status`. Antigravity specifics: command built by `buildAntigravityCommand()` (`--model`, `--conversation <id>` resume, `--dangerously-skip-permissions` from the `antigravityConfig` payload); availability via `GET /api/antigravity/status` — routes fail with `OPERATION_FAILED` + install hint (`curl -fsSL https://antigravity.google/cli/install.sh | bash`) when missing. Unlike the other three it is NOT an npm package (standalone binary, `~/.local/bin/agy`), which is why `docker/agent.Dockerfile` installs it with its own `--dir /usr/local/bin` step rather than in the `npm install -g` line, and why it does NOT join `isAltScreenStripMode()`. Frontend: run-mode dropdown → `runCodex()`/`runGemini()` in `session-ui.js` ("Run CX"/"Run GM" labels), App Settings → Agents & CLIs → Codex; Respawn/Ralph options are Claude-only, so session options open on the Session tab for external CLI sessions. ⚠️ `run*()` MUST unwrap the `{success,data}` envelope (`(await res.json()).data.available` / `data.data.sessionId`) — reading the raw shape silently breaks the run. Tests: `test/run-mode-ui.test.ts` + `test/gemini-mode.test.ts` (vm-sandbox harness, no real DOM). Grok specifics: command built by `buildGrokCommand()` (`--always-approve` from `grokConfig.alwaysApprove` — grok's `bypassPermissions` permission mode, deny rules still apply; `--model`; `--resume <id>` / `--continue`, id-regexed so grok's resume-by-TITLE feature can never put an arbitrary string on the spawn line); availability via `GET /api/grok/status`, which carries `version` because the resolver version-probes candidates (`grok` has npm squatters, e.g. @vibe-kit/grok-cli — `GROK_VERSION_REGEX` is shared with the dependency registry so doctor and run mode agree). Like antigravity it is a standalone binary (xAI installer → `~/.grok/bin`, symlinked into `~/.local/bin`), so `docker/agent.Dockerfile` installs it in its own step (copy to `/usr/local/bin`, drop root's `~/.grok` in the same layer) and it stays OUT of `isAltScreenLine truncated
|
||||
**External CLI modes (OpenCode, Codex, Gemini, Antigravity, Pi, Grok, DeepSeek, OMP, Copilot, jcode)**: `isExternalCliMode()` in `session.ts` (`mode === 'opencode' || 'codex' || 'gemini' || 'antigravity' || 'pi' || 'grok' || 'deepseek'`) gates Claude-specific behavior — Ralph tracker, BashToolParser, token/CLI-info parsing, and ❯-prompt readiness detection are all skipped (these CLIs render their own TUIs; readiness = output stabilization instead). ⚠️ **Work detection left this gate in #385** and is now per-CLI `capabilities.workDetect` data (`promptGlyph` + `workingLine`), because gating it on the mode left every Codex session reporting `idle` for its entire life; a CLI declaring neither falls back to Claude's pair, which is logic-identical to the pre-registry behaviour. All seven modes **require tmux — no direct PTY fallback** — because secrets are injected via `tmux setenv` (socket-scoped `${this.tmux()} setenv`, never on the spawn command line): OpenCode gets `OPENCODE_CONFIG_CONTENT` etc., Codex gets `OPENAI_API_KEY`/`CODEX_API_KEY`/`CODEX_HOME` (`setCodexEnvVars`), Gemini gets `GEMINI_API_KEY`/`GOOGLE_API_KEY`/`GOOGLE_CLOUD_PROJECT`/`GOOGLE_APPLICATION_CREDENTIALS`/`GOOGLE_GENAI_USE_VERTEXAI` etc. (`setGeminiEnvVars`, all in `tmux-manager.ts`). Codex specifics: command built by `buildCodexCommand()` (`--no-daemon` behind the `noDaemonFlag` gate at 0.162.0, measured against codex's own version, local launches only; `--model`, `--config model_reasoning_effort=<level>` from `reasoningEffort`, `--config sandbox_workspace_write.network_access=true` from `networkAccess` (the **Allow network access** app setting `codexNetworkAccess`, a launch default and a privileged param; ⚠️ with it on, a command in codex's sandbox can call Codeman's API and start a session outside that sandbox, password or not), `--config tui.animations=<bool>` from `animations`, `resume <id>`, `--dangerously-bypass-approvals-and-sandbox` from the `codexConfig` payload / `codexDangerouslyBypassApprovals` app setting; `renderMode` is schema-coerced to `'hybrid'`, the only supported mode). Gemini specifics: command built by `buildGeminiCommand()` (`--skip-trust` always, `--approval-mode <default|auto_edit|yolo|plan>` defaulting to `yolo` for parity with Claude's `--dangerously-skip-permissions`, `--model`, `--resume` from the `geminiConfig` payload); availability via `GET /api/gemini/status` — session/quick-start routes fail with `OPERATION_FAILED` + install hint (`npm install -g @google/gemini-cli`) when missing. Codex, Gemini, Antigravity, Pi, Grok, DeepSeek and OMP export `COLORTERM=truecolor` and unset `NO_COLOR`; `opencode` unsets `COLORTERM`. **Terminal colour env** under Session launch modes covers Claude and says which panes those declarations actually reach. Gemini joins `isAltScreenStripMode()` (Codex/Claude/Gemini are Ink TUIs that repaint inline → strip alt-screen/`3J` so scrollback survives). Codex availability via `GET /api/codex/status`. Antigravity specifics: command built by `buildAntigravityCommand()` (`--model`, `--conversation <id>` resume, `--dangerously-skip-permissions` from the `antigravityConfig` payload); availability via `GET /api/antigravity/status` — routes fail with `OPERATION_FAILED` + install hint (`curl -fsSL https://antigravity.google/cli/install.sh | bash`) when missing. Unlike the other three it is NOT an npm package (standalone binary, `~/.local/bin/agy`), which is why `docker/agent.Dockerfile` installs it with its own `--dir /usr/local/bin` step rather than in the `npm install -g` line, and why it does NOT join `isAltScreenStripMode()`. Frontend: run-mode dropdown → `run()` → the shared `_runCliMode(mode)` in `session-ui.js` ("Run CX"/"Run GM" labels), App Settings → Agents & CLIs → Codex; Respawn/Ralph options are Claude-only, so session options open on the Session tab for external CLI sessions. ⚠️ `run*()` MUST unwrap the `{success,data}` envelope (`(await res.json()).data.available` / `data.data.sessionId`) — reading the raw shape silently breaks the run. Tests: `test/run-mode-ui.test.ts` + `test/gemini-mode.test.ts` (vm-sandbox harness, no real DOM). Grok specifics: command built by `buildGrokCommand()` (`--always-approve` from `grokConfig.alwaysApprove` — grok's `bypassPermissions` permission mode, deny rules still apply; `--model`; `--resume <id>` / `--continue`, id-regexed so grok's resume-by-TITLE feature can never put an arbitrary string on the spawn line); availability via `GET /api/grok/status`, which carries `version` because the resolver version-probes candidates (`grok` has npm squatters, e.g. @vibe-kit/grok-cli — `GROK_VERSION_REGEX` is shared with the dependency registry so doctor and run mode agree). Like antigravity it is a standalone binary (xAI installer → `~/.grok/bin`, symlinked into `~/.local/bin`), so `docker/agent.Dockerfile` installs it in its own step (copy to `/usr/local/bin`, drop root's `~/.grok` in the same layer) and it stays OUTLine truncated
|
||||
|
||||
**DeepSeek Harness (`dsh`) specifics** — the mode that breaks three of the assumptions the six above share, so read this before changing anything about it.
|
||||
|
||||
@@ -135,7 +137,7 @@ Further detail: ⚠️ An ADOPTED container may back SEVERAL cases at different
|
||||
|
||||
⚠️ **`param` is TWO namespaces.** `launch.params` keys, `env.configSetenv[].fromParam` and `capabilities.privilegedParams[].param` all name a LAUNCH PARAM; the legacy `<Mode>Config` wire field is a separate namespace, bridged only by `launch.legacyConfigAliases`. Getting `privilegedParams[].param` wrong is SILENT — it is the multi-user bypass clamp's only handle on a CLI's privilege switch, and a wrong name clamps nothing with no load error and no failing test — so `schema.ts` rejects an entry naming a param it never declared. Codex is the entry where the two names differ (`bypassApprovals` vs `dangerouslyBypassApprovals`) and therefore the one that catches a regression.
|
||||
|
||||
⚠️ Five fields are DECLARED-FOR-LATER and read by nothing (`accent`, `capabilities.echo`/`wheelForward`/`keyboardAccessory`/`maxFrameBytes`): all frontend behaviour, transcribed rather than measured (except `accent`, measured against styles.css on 2026-09-21), so re-measure before wiring one up; the list is pinned so it cannot quietly grow. (`shortBadge` left the list when the Settings CLI management list started showing it.)
|
||||
⚠️ Four fields are DECLARED-FOR-LATER and read by nothing (`accent`, `capabilities.echo`/`keyboardAccessory`/`maxFrameBytes`): all frontend behaviour, transcribed rather than measured (except `accent`, measured against styles.css on 2026-09-21), so re-measure before wiring one up; the list is pinned so it cannot quietly grow. (`shortBadge` left the list when the Settings CLI management list started showing it, and `wheelForward` when the browser's wheel gate started reading it.)
|
||||
|
||||
Spawn commands are pinned as literal strings in `test/cli-registry-spawn-golden.test.ts`, remote/docker pane commands in `test/location-overlay-commands.test.ts`. ⚠️ That second golden no longer covers **remote claude or remote omp**: both now have their own arm in `buildRemoteLaunchCommand` (a `--session-id || --resume` pair, and `--continue`, so a respawn continues the same conversation) and never reach `defaultRemoteCommandForMode`, which is what that test asserts. Their real pins are `toContain` substrings in `test/tmux-manager.test.ts` and `test/remote-shared-sessions.test.ts`; changing either arm will NOT fail the golden.
|
||||
|
||||
@@ -145,11 +147,11 @@ 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
|
||||
|
||||
**The env allowlist has two tiers, and exceptions go in the exact-key tier, never a widened prefix** (#255): `ALLOWED_ENV_PREFIXES` in `src/web/schemas.ts` carries the CLI-namespace prefixes, and `ALLOWED_ENV_KEYS` carries exact keys (currently only `CLAUDE_CONFIG_DIR`). `CLAUDE_CONFIG_DIR` relocates the Claude CLI's user config (credentials, settings, stats), which is how one machine runs sessions on separate Claude subscriptions: point a case's sessions at e.g. `~/.claude-clients/acme` via `envOverrides` and run `/login` there once against the client's account. The exact match matters: `CLAUDE_` as a prefix would open every future Claude CLI variable unreviewed, and near-misses (`CLAUDE_CONFIG_DIR_EXTRA`) stay rejected (`test/env-overrides-schema.test.ts`). No new security boundary is crossed: sessions already run as the server's OS account, and `applyEnvOverrides()` shellescapes values into socket-scoped `tmux setenv`. Two carry rules: **(1)** the key must survive `getEnvOverridesForPersist()` in `session.ts` (it is a path, not a secret; dropping it from state.json would silently move a rebuilt-after-reboot session back to the default account); **(2)** ⚠️ a relocated config dir writes transcripts outside `homedir()/.claude/projects`, which `subagent-watcher.ts`, `workflow-run-watcher.ts`, the response-viewer routes and Read My Mind capture all hardcode — those surfaces go blind for such a session. Documented workaround: symlink the transcripts back into the shared tree (`ln -s ~/.claude/projects <configDir>/projects`), keeping credentials separate while the watchers keep working.
|
||||
**The env allowlist has two tiers, and exceptions go in the exact-key tier, never a widened prefix** (#255): `ALLOWED_ENV_PREFIXES` in `src/web/schemas.ts` carries the CLI-namespace prefixes, and `ALLOWED_ENV_KEYS` carries exact keys (currently only `CLAUDE_CONFIG_DIR`). `CLAUDE_CONFIG_DIR` relocates the Claude CLI's user config (credentials, settings, stats), which is how one machine runs sessions on separate Claude subscriptions: point a case's sessions at e.g. `~/.claude-clients/acme` via `envOverrides` and run `/login` there once against the client's account. The exact match matters: `CLAUDE_` as a prefix would open every future Claude CLI variable unreviewed, and near-misses (`CLAUDE_CONFIG_DIR_EXTRA`) stay rejected (`test/env-overrides-schema.test.ts`). No new security boundary is crossed: sessions already run as the server's OS account, and `applyEnvOverrides()` shellescapes values into socket-scoped `tmux setenv`. Two carry rules: **(1)** the key must survive `getEnvOverridesForPersist()` in `session.ts` (it is a path, not a secret; dropping it from state.json would silently move a rebuilt-after-reboot session back to the default account); **(2)** ⚠️ a relocated config dir writes transcripts outside `homedir()/.claude/projects`, which `subagent-watcher.ts`, `workflow-run-watcher.ts` and Read My Mind capture all hardcode: those surfaces go blind for such a session. Documented workaround: symlink the transcripts back into the shared tree (`ln -s ~/.claude/projects <configDir>/projects`), keeping credentials separate while the watchers keep working. The response viewer is no longer one of them (#701): `claudeConversationDirs()` in `session-routes.ts` gives `lastResponseFor` (the viewer, `codeman agent read`, the Discord bridge's last message) and the rename's `/resume` title the folder the session's claude really writes to, `<config dir>/projects` and `<config dir>/history.jsonl`, resolved by `claudeProjectsDir()` like the relaunch pin and the Edit history panel: the session's own override, then the server's `CLAUDE_CONFIG_DIR` (a pane inherits it through tmux), then `~/.claude`. ⚠️ Only a LOCAL session reads its override: in a Docker case or on a remote host the value names a folder over there. ⚠️ A relocated folder is a user-chosen path, so it is probed bounded first (#516), and anything but a directory reads as "no transcript": never fall back to `~/.claude`, where a file of the same name is another account's conversation. The default folder is not probed, so that path is unchanged. Tests: `test/routes/session-routes-claude-last-response.test.ts` (relocated folder block), `test/routes/session-name-routes.test.ts`.
|
||||
|
||||
⚠️ **As of the custom-model endpoint feature, `CLAUDE_CONFIG_DIR` is ALSO admin-only in multi-user mode**, which is a change to the above rather than a restatement of it. It joined claude's `privilegedEnvKeys` (`stock.ts`) alongside `CLAUDE_CODE_MAX_CONTEXT_TOKENS`, because the rule that every traffic-redirecting var that feature can inject must be listed there is worth keeping literally true. `privilegedEnvKeys` has exactly one consumer, `ownerClampedEnvKeys()` in `src/session-env-clamp.ts`, which feeds the generic `envOverrides` clamp on `POST /api/sessions`, `POST /api/quick-start` and reboot-restore. So for a non-granted owner two things now follow: the key cannot be set through `envOverrides` at all, and an ALREADY-PERSISTED one is stripped on reboot-restore, which silently moves that session back to the default Claude account. That second consequence is the one to watch, since it turns a working per-client setup into a wrong-account one across a host reboot with no error anywhere. `session-env-clamp.ts`'s own fileoverview used to state the opposite invariant (that claude's privileged keys are the five `ANTHROPIC_*` names, so a persisted record cannot carry a clamped key) and was corrected when this landed; a claude clamp test now pins the behaviour next to the deepseek and omp ones.
|
||||
|
||||
@@ -251,7 +253,9 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect`
|
||||
|
||||
### Full-scrollback replay
|
||||
|
||||
**Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 0.3 s at 100k lines); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes may still re-pull `full=1` at the TOP, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; outpLine truncated
|
||||
**Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 1 s at 100k lines; measured capture details below); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marLine truncated
|
||||
|
||||
**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not Docker or adopted (their local pane hosts a nested tmux client in the alternate screen, so `?full=1` returns one screen the downgrade guard refuses; remote sessions stay eligible, since the route splices the remote scrollback in), not detached, not owned by tiles, with no pull or buffer load in flight, no terminal load state for the session (a tab switch sets it before the buffer load opens), and no drop-recovery refresh owning the session (`_terminalRefreshOwner`, set for the whole fetch, before that refresh opens its buffer load). `_maybeRefetchFullHistory` returns early on that same owner, so Reload, Load full history and the top-of-buffer pull all stand aside instead of running a second capture whose download-time queue the refresh's own load would replace; the refresh re-syncs the action when it starts and when its `finally` releases the owner. `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). The bar is a polite live region (`role="status"`), but only the truncation notice is announced: a reload-only bar sets `aria-live="off"` before it re-renders, since it comes back on nearly every scroll-up in a busy tab, and its button stays reachable with Tab. Its × is labelled for what the bar carries: "Dismiss history notice" with the notice, "Dismiss Reload history" without it. A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line, and shares Reload's loading state, so the re-render the in-flight pull triggers keeps it on Loading… instead of bringing it back enabled; otherwise it keeps the top anchor and no loading state, so the bar still hides on a scroll back to live output. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrLine truncated
|
||||
|
||||
**The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`.
|
||||
|
||||
@@ -267,7 +271,7 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect`
|
||||
|
||||
⚠️ **What a mouse-DECSET strip (full or mouse) removes, it must REMEMBER.** Stripping the mouse DECSETs means xterm's `modes.mouseTrackingMode` is permanently `'none'` for those modes, so the browser hand-encodes click reports to compensate (`_sendSyntheticSgrTap`). With no state to consult it did that on EVERY click, which delivered mouse reports to programs that never asked for them: the same pane runs a plain shell whenever the CLI has exited or a `shell` was started inside a claude-mode session, and a shell prints the report as literal text (`[<0;88;20M`), garbling the next line typed. `_recordStrippedMouseMode()` therefore records each stripped sequence as it goes and publishes `cliMouseTracking` through `toState()`, and `_shouldReportMouseToCli()` requires it. ⚠️ Only the TRACKING modes count (1000/1001/1002/1003): 1005/1006 select an ENCODING and 1007 is alt-scroll, and counting those would put the stray reports straight back. ⚠️ The change broadcasts IMMEDIATELY rather than through `broadcastSessionStateDebounced`, because the flag flips when a dialog opens and the user can click that dialog inside the 500ms debounce window. Measured on a live claude 2.x: the CLI holds a tracking mode on continuously in fullscreen (so clicks keep being reported exactly as before; the default inline renderer holds none, measured on 2.1.283 even with `/model` open), while a bash prompt in the same stripped mode reports nothing. Fails toward silence: after a server restart the flag is false until the CLI re-emits, which tmux does at client attach.
|
||||
|
||||
**Wheel forwarding requires observed mouse tracking: Claude ≥ 2.1.187, tracked Codex, tracked Copilot or tracked Pi** (`terminal-ui.js:_shouldForwardWheelToApp`). The original #227 measurement remains valid for **Codex 0.147.0 inline**: `alternate_on=0`, `mouse_any_flag=0`, growing tmux history, and SGR wheel reports do nothing. Claude 2.1.280 inline similarly reports `alternate_on=0`, `mouse_any_flag=0`; forwarding there swallows gestures, so it keeps local scrollback. Fullscreen Claude (`CLAUDE_CODE_NO_FLICKER=1` or `"tui": "fullscreen"`) enables mouse tracking and accepts reports. **Fresh Codex 0.163.0 fullscreen measurement (2026-10-18, isolated local tmux pane)**: `alternate_on=1`, `mouse_any_flag=1`; one `\x1b[<64;10;10M` report moves the transcript one row upward, and `\x1b[<65;10;10M` restores the original screen. This is capability evidence, not a minimum-version promise: untracked Codex (including a 0.162.0 measurement (2026-10) with `mouse_any_flag=0`) keeps local history or the hollow-pane paging fallback. Codex does not publish the Claude-only CLI version field, so its gate requires the observed flag rather than a Claude version. The registry records this as `wheelForward.mode: 'always'` (observed mouse tracking is still required); Claude remains `version-gated`. A stale/false flag after startup cannot authorize forwarding. ⚠️ A strip mode alone is not evidence that a CLI consumes SGR reports. Verify with a real `\x1b[<64;c;rM` write into a live pane before adding a mode here. Hand-encoded SGR taps remain independently gated by `_shouldReportMouseToCli()`; the older #325 no-op measurement describes untracked inline Codex and must not be generalized to newer tracked fullscreen renderers. Shift/local-history opt-outs and xterm's native mouse/alternate-screen handling remain intact.
|
||||
**Wheel forwarding requires observed mouse tracking: Claude ≥ 2.1.187, tracked Codex, tracked Copilot or tracked Pi** (`terminal-ui.js:_shouldForwardWheelToApp`). The original #227 measurement remains valid for **Codex 0.147.0 inline**: `alternate_on=0`, `mouse_any_flag=0`, growing tmux history, and SGR wheel reports do nothing. Claude 2.1.280 inline similarly reports `alternate_on=0`, `mouse_any_flag=0`; forwarding there swallows gestures, so it keeps local scrollback. Fullscreen Claude (`CLAUDE_CODE_NO_FLICKER=1` or `"tui": "fullscreen"`) enables mouse tracking and accepts reports. **Fresh Codex 0.163.0 fullscreen measurement (2026-10-18, isolated local tmux pane)**: `alternate_on=1`, `mouse_any_flag=1`; one `\x1b[<64;10;10M` report moves the transcript one row upward, and `\x1b[<65;10;10M` restores the original screen. This is capability evidence, not a minimum-version promise: untracked Codex (including a 0.162.0 measurement (2026-10) with `mouse_any_flag=0`) keeps local history or the hollow-pane paging fallback. Codex does not publish the Claude-only CLI version field, so its gate requires the observed flag rather than a Claude version. The registry records this as `wheelForward.mode: 'always'` (observed mouse tracking is still required); Claude remains `version-gated`. That field is the gate's only per-CLI rule: `renderIndexHtml` publishes every CLI's `wheelForward` (disabled ones included, since their sessions keep running; `never` left out) as `window.__codemanWheelForward`, so a custom `clis.json` entry forwards under its own id, and a `minVersion` that is not `MAJOR.MINOR.PATCH` refuses forwarding. A stale/false flag after startup cannot authorize forwarding. ⚠️ A strip mode alone is not evidence that a CLI consumes SGR reports. Verify with a real `\x1b[<64;c;rM` write into a live pane before adding a mode here. Hand-encoded SGR taps remain independently gated by `_shouldReportMouseToCli()`; the older #325 no-op measurement describes untracked inline Codex and must not be generalized to newer tracked fullscreen renderers. Shift/local-history opt-outs and xterm's native mouse/alternate-screen handling remain intact.
|
||||
|
||||
**Copilot also receives forwarded reports** (1.0.95 measured in tmux: alt screen, `mouse_any_flag=1`): its mouse DECSETs are stripped so a drag selects, which also stops xterm encoding the wheel for it, so `_shouldForwardWheelToApp` sends the same SGR reports by hand while `cliMouseTracking` is true; six `\x1b[<64;…M` reports moved its transcript 18 lines, a phone swipe takes the same gate, and there is NO version gate.
|
||||
|
||||
@@ -297,7 +301,7 @@ Further detail, closing: ⚠️ **Closing has the mirror-image race and one owne
|
||||
|
||||
### An exited agent in a live pane (`paneExit`)
|
||||
|
||||
**Codeman creates every pane with `remain-on-exit on`, so a session whose agent exited still looks alive.** `/exit` ends the CLI, tmux keeps the pane and the tmux session, and the `tmux attach-session` process Codeman records as `Session.pid` runs on, so no PTY exit handler fires and the record keeps its pid and `status: 'idle'` (Ark0N/Codeman#446). `SessionState.paneExit` (`{status?, signal?, at}`) is the fact tmux already knows, published through `toState()` so it rides `session:updated` and lands in `state.json` on the same persist — there is no SSE event for it. One batched `tmux list-panes -a` per tick fills it, from `TmuxManager.startPaneExitWatcher()`, which has its OWN always-on interval: the stats collector cannot carry it, because the browser arms and disarms that one with the Monitor panel (`panels-ui.js`) and boot skips it entirely when no session was recovered. ⚠️ **The field is TRI-STATE and its third state is absence**, meaning UNKNOWN, which renders as nothing and must NEVER read as alive; it covers a running pane, a session the read did not list, a failed probe, and every session shape a dead local pane does not describe. `Session.paneExitApplies` is the single place that scoping lives, and it fails closed for four shapes: a direct-PTY session (no pane), a remote SSH session (the local pane is the ssh client, whose death is a transport drop OR an exit — the whole of #355), a docker case (the local pane is a `docker exec` into the container's own tmux), and a session rebuilt from the socket (`MuxSession.discovered`: its synthetic `restored-<fragment>` id matches no `state.json` entry, so a remote session rediscovered after `mux-sessions.json` was lost would arrive looking local). ⚠️ **Never set `status: 'error'`** for an exited pane — that value is the PTY-exit breaker's and the browser answers it with a "restart it?" confirm — and **never null the `pid`**, which is what makes `selectSession()` re-attach and launch a fresh CLI. Local panes keep `remain-on-exit on`; flipping them to `failed` ends the tmux session, nulls the pid and reintroduces the auto-revive #355 removed. ⚠️ **An absent `#{pane_dead_status}` is not 0**: measured on tmux 3.2a a SIGKILLed pane reports neither a status nor a signal (`#{pane_dead_signal}` did not exist before tmux 3.4), so folding it into 0 would turn an unexplained death into a clean exit. A session answers only when the read listed EXACTLY ONE pane for it, since Codeman never splits a pane and a session the user split by hand has none that speaks for the agent. The three synchronous `isPaneDead()` callers (the `/wait` route, the TUI, the attach path) keep their own probes — this watcher is never fresh enough for them. ⚠️ **A path that starts a command in a pane must clear the record AND persist**, since the watcher's next tick sees the field already cleared and writes nothing. ⚠️ **The always-on timer gates the READ, never the tick.** `hasObservablePaneSession()` (`tmux-manager.ts`) skips the tmux exec while every session on the manager is one of the shapes `paneExitApplies` forces to UNKNOWN, so an instance running only remote or Docker work keeps ticking and costs nothing; the two predicates are two copies of one rule, and `test/session-pane-exit.test.ts` pins them against each other for the four session shapes that exist today — a FIFTH condition added to one and not the other still fails nothing, so change them together. Skipping retracts nothing, for the same reason a failed read does not. ⚠️ **The muted status dot is a specificity fight, and it is fought on three surfaces.** The tab renders `status` as before, and `tab-agent-exited` only quiets the dot, so the rule excludes three states BY HAND: `.tab-alert-action` and `.tab-alert-idle` on the tab, and `.tab-status.error` on the dot itself. Each of those colours means "this needs you" — the two alerts because a human is blocked, `error` because the browser answers it with a "restart it?" confirm — and each must survive the exit. The rich tab rail needs a SECOND copy of the rule, because its own `tab-state-*` dot rules are (0,9,1) against the strip's (0,5,0) — measured, an exited session on a detailed rail kept a full green dot and the working halo beside a badge reading "exited". Its twin matches that specificity exactly and therefore must stay BELOW those rules in source order. mobile.css needs a THIRD copy, with `!important`, because the phone block enlarges a `busy` dot and gives it a green glow that way, and `status` stays `busy` for a pane whose agent died mid-turn — without it a phone renders a grey dot still wearing the green halo. `test/session-pane-exit-ui.test.ts` resolves the real stylesheets in jsdom rather than matching selector text — styles.css for the desktop cases and both files for the phone ones — so the ordering, the hand-written exclusions and a missing phone rule all fail there. Tests: `test/session-pane-exit.test.ts`, `test/tmux-manLine truncated
|
||||
**Codeman creates every pane with `remain-on-exit on`, so a session whose agent exited still looks alive.** `/exit` ends the CLI, tmux keeps the pane and the tmux session, and the `tmux attach-session` process Codeman records as `Session.pid` runs on, so no PTY exit handler fires and the record keeps its pid and `status: 'idle'` (Ark0N/Codeman#446). `SessionState.paneExit` (`{status?, signal?, at}`) is the fact tmux already knows, published through `toState()` so it rides `session:updated` and lands in `state.json` on the same persist — there is no SSE event for it. One batched `tmux list-panes -a` per tick fills it, from `TmuxManager.startPaneExitWatcher()`, which has its OWN always-on interval: the stats collector cannot carry it, because the browser arms and disarms that one with the Monitor panel (`panels-ui.js`) and boot skips it entirely when no session was recovered. ⚠️ **The field is TRI-STATE and its third state is absence**, meaning UNKNOWN, which renders as nothing and must NEVER read as alive; it covers a running pane, a session the read did not list, a failed probe, and every session shape a dead local pane does not describe. `Session.paneExitApplies` is the single place that scoping lives, and it fails closed for four shapes: a direct-PTY session (no pane), a remote SSH session (the local pane is the ssh client, whose death is a transport drop OR an exit — the whole of #355), a docker case (the local pane is a `docker exec` into the container's own tmux), and a session rebuilt from the socket (`MuxSession.discovered`: its synthetic `restored-<fragment>` id matches no `state.json` entry, so a remote session rediscovered after `mux-sessions.json` was lost would arrive looking local). ⚠️ **Never set `status: 'error'`** for an exited pane — that value is the PTY-exit breaker's and the browser answers it with a "restart it?" confirm — and **never null the `pid`**, which is what makes `selectSession()` re-attach and launch a fresh CLI. Local panes keep `remain-on-exit on`; flipping them to `failed` ends the tmux session, nulls the pid and reintroduces the auto-revive #355 removed. ⚠️ **An absent `#{pane_dead_status}` is not 0**: measured on tmux 3.2a a SIGKILLed pane reports neither a status nor a signal (`#{pane_dead_signal}` did not exist before tmux 3.4), so folding it into 0 would turn an unexplained death into a clean exit. ⚠️ **A dead pane may have no pid**: measured on tmux 3.8, `#{pane_pid}` prints blank once the pane's program exits, so `parsePaneRows()` keeps a row with no pid whenever tmux answered `#{pane_dead}`, and skips only a row with neither. On tmux 3.8 the pid goes blank when the pty closes, and `#{pane_dead}` turns 1 only once tmux has collected the exit status, which took several seconds for some exits (measured on tmux 3.4, where the pid itself stays): a row with no pid and `pane_dead` 0 is that window, and a restart in it must not drop the session. `#{pane_dead_time}` then tells one exit from the next, next to the pid, so two reads of one exit still count as two and a hand-run `respawn-pane` that exits 0 again starts a new observation. `reconcileSessions()` keeps such a tracked session alive with its last known pid, and does not rediscover an untracked one, since a made-up pid would reach `killSession()`'s process-tree walk. ⚠️ Kept alive means restored: at the next server start the restore goes through the dead-pane branch of `Session._setupOrAttachMuxSession()`, which respawns the pane and clears `paneExit` (measured on tmux 3.8, and what tmux 3.7 and older always did, since they still printed the pid). So a row kept as evidence of a crash or a startup error survives a restart only until the CLI is relaunched in it. `killSession()` reads `#{pane_dead}` with the pid and, for a dead pane, signals nothing and walks no tree: the recorded pid belongs to the program that exited and may since have been reused by an unrelated process, so only `kill-session` runs (`parsePaneKillRead()`). ⚠️ The flag alone is not trusted: before tmux 3.7 `#{pane_dead}` means only that the pty is closed, so a program that closed its tty and ignores SIGHUP reads dead while it runs. A dead reading counts only with a blank pid or a set `#{pane_dead_time}`, which keeps the old close on tmux 3.3a to 3.6. A pid below 2 is no pid: an empty active pane (`split-window ''`) prints 0 before tmux 3.8, so the close falls back to the recorded pid (`pane.pid || session.pid`), and `isSignalablePid()` refuses 0 or 1 wherever it comes from. A session answers only when the read listed EXACTLY ONE pane for it, since Codeman never splits a pane and a session the user split by hand has none that speaks for the agent. The three synchronous `isPaneDead()` callers (the `/wait` route, the TUI, the attach path) keep their own probes — this watcher is never fresh enough for them. ⚠️ **A path that starts a command in a pane must clear the record AND persist**, since the watcher's next tick seLine truncated
|
||||
|
||||
⚠️ **The tab's badge is translated (zh-CN), so its updates compare with English, never the DOM.** `applyPaneExitBadge()` remembers the last English badge text (`data-label`) and the tab's accessible name (`data-aria-source`), both also seeded by the full render, and writes only when those change: the translator rewrites both in zh-CN, and a DOM compare (or an unconditional set) would write the English back on every incremental pass for it to translate again. i18n.js has `exited` and patterns for `exited (N)`, `exited (signal N)` and `<name> session, agent exited ...` (the name passed through); `test/i18n-exit-run-help.test.ts` covers every `paneExitLabel()` form.
|
||||
|
||||
@@ -682,6 +686,8 @@ Adding the header changed the preamble, so `CODEMAN_PREAMBLE` was bumped (1.22.0
|
||||
|
||||
⚠️ Both `POST` and `DELETE` sit at the **same privilege bar as the profile installer** (`canUsernameRunPrivilegedCommands`) even though the action reads as "open a page": booting a dsh profile executes the plugin code in it, and the server is a single shared instance, so stopping it in multi-user mode takes it out from under other users' tabs.
|
||||
|
||||
⚠️ dsh's browser-auth gate answers only a request carrying the one-time launch token from its boot banner, so the supervisor trades that token for dsh's `dsh-auth-*` session cookie once at startup (`getDeepSeekWebCookie()`), and the web-tab proxy presents the cookie on BOTH legs, HTTP and WebSocket, only to a `managed: 'deepseek-web'` tab whose upstream is `127.0.0.1` on the port it was minted for. Reuse therefore needs the same starter AND a working cookie: a server whose exchange failed, or one another owner started, is restarted rather than reused. The owner check applies only in multi-user mode (a record keeps the owner it was created under, while a single-user start has none), and the browser's own `codeman_session` cookie is filtered out of both legs whether or not the dsh cookie is injected. Details: `docs/deepseek-integration.md`.
|
||||
|
||||
### Custom Model Endpoint Profiles
|
||||
|
||||
**Custom Model Endpoint Profiles** (opt-in, `customModelEndpointsEnabled`, SYNCED, default OFF; `docs/custom-model-endpoints.md`, design doc `docs/custom-model-endpoints-plan.md`; full stack — settings-panel CRUD + the Run-menu picker, on top of the backend below): points a session at a user-configured custom OpenAI-compatible endpoint — local (llama.cpp, DGX Spark, Strix Halo) or cloud (Azure AI Foundry, OpenRouter) — instead of its harness's native cloud backend. Endpoints are a read/write-array store (`custom-model-hosts.ts`, `~/.codeman/custom-model-hosts.json`) discovered via `GET <baseUrl>/v1/models`; `CustomModelHost.authStyle` is `'bearer'` (default, `Authorization: Bearer`) or `'api-key'` (Azure's convention) — **never both**, live-tested against a real server: sending both headers on one request reliably hangs it indefinitely, reproduced 3×.
|
||||
@@ -822,6 +828,32 @@ Frontend `readmymind-ui.js`: header 🧠 marker-hidden (`btn-readmymind--hidden`
|
||||
|
||||
### Files panel search
|
||||
|
||||
The panel browses local workspaces through opt-in `lazy=1` directory pages (#759),
|
||||
documented in [Listing a directory](api-reference.md#listing-a-directory-get-apiv1sessionsidfileslazy1).
|
||||
Each request reads one directory, returns at most 500 entries and supplies `nextCursor`
|
||||
when more remain. Cursor scope includes the session, selected root, directory and hidden
|
||||
preference. Directories without `children` are unloaded; symbolic links keep their legacy
|
||||
file-row representation, so the browser does not expand directory links. Path confinement, bounded
|
||||
probes and the inside/outside worktree rules apply to every request.
|
||||
|
||||
The browser caches loaded pages in the current tree epoch. Owner, epoch, hidden preference,
|
||||
selected root and tree identity guard folder/page responses. Typing filters loaded entries
|
||||
without a request; Enter uses the existing workspace search, and clearing restores the tree.
|
||||
Expand All opens only loaded folders. Refresh retains visible expansion state; automatic
|
||||
restoration skips recorded load errors and hidden-off expansions before requesting pages.
|
||||
Hidden-path checks are relative to the listing root, so a worktree's dotted prefix does not
|
||||
hide its ordinary folders. Explicit Retry loads the failed folder/page; errors retain entries
|
||||
already loaded. A page lists the folder's directories before its files, and that order holds
|
||||
across pages, so a restore or a reveal that has a file loaded for a folder stops asking for
|
||||
more pages: the folder it looks for is not there. A restore then forgets that expansion
|
||||
(the folder was deleted or renamed); one stopped by a failed page keeps it. An expanded
|
||||
folder whose own request has not started is drawn with the loading line, never as an empty
|
||||
folder, and a search-result folder opened while the tree was still loading runs the restore
|
||||
when it is done. Tests: `test/routes/file-routes-lazy.test.ts`, `test/file-browser-lazy.test.ts`
|
||||
and `test/mobile/file-browser.test.ts`.
|
||||
|
||||
The recursive listing and `q` search policies below remain unchanged for existing callers.
|
||||
|
||||
**Files panel search** (COD-236, the `q` param on `GET /api/sessions/:id/files`): `compileFileQuery()` (`utils/file-query.ts`, pure, no IO, so it unit-tests directly) compiles the query into a reusable predicate, which is what lets the server-side walk prune instead of streaming the whole tree.
|
||||
|
||||
⚠️ **A query turns that endpoint into a FLAT match list rather than a nested tree**, and the walk deliberately recurses past non-matching directories, since the whole point of searching is to reach a file whose ancestors do not match. An empty or whitespace-only query compiles to `null`, which is what keeps the default tree response byte-identical when no search is requested.
|
||||
@@ -1081,7 +1113,7 @@ Tests: `test/tab-rail-search.test.ts` (gate) and `test/tab-rail-search.browser.t
|
||||
|
||||
### Split-pane sessions
|
||||
|
||||
**Split-pane sessions** (`showSplitButton`, header button, default OFF, per-device like `showFileViewerButton` — not in `SettingsUpdateSchema`, `displayKeys` in settings-ui.js): shows two live sessions side-by-side in one Codeman window. Pane A is the untouched, existing singleton terminal (`this.terminal`/`this._ws` in terminal-ui.js); Pane B is an independent `TerminalTile` (terminal-tile.js, constructed by the orchestration in terminal-split.js) with its own xterm instance and its own `/ws/sessions/:id/terminal` WebSocket, whose `cid` is the tab's identity with a `:tile` suffix, so it can never supersede the primary pane's socket (the registry supersedes by cid per session). ⚠️ **Pane B is deliberately plainer than Pane A** — no local-echo overlay, no CJK IME, no touch/mobile handlers, no keyboard accessory bar (it does carry the primary pane's hollow-buffer wheel paging and desktop click report, through terminal-ui.js's own gates aimed at the tile, and its own keyCode-229 soft-keyboard controller from terminal-keycode229-recovery.js, the #441 next-keydown drain and #541's edit-based diff for Android autocorrect, since the 1180px width gate is reachable by a wide Android tablet; see terminal-tile.js's fileoverview) — since this is a desktop-only feature (a split view needs a wide viewport) and those features exist for mobile/touch input; `.btn-split` is hard-hidden below 1180px regardless of the setting by the `@media (max-width: 1179px)` rule in styles.css (mobile.css only carries a comment pointing at it: that file loads up to 1023px, so it cannot cover the 1024-1179px tablet range the feature also needs to stay off), and the per-device setting means turning it on at a desk can never sync it onto a phone in the first place. No persistence: closing the browser tab or reloading always returns to the normal single-pane view; there is no localStorage key for split state. ⚠️ Splitting a session against itself is disallowed (the picker excludes the active session), **as is splitting against a popped-out (detached) session** — `buildSplitPickerSessions()` excludes `detachedSessions` because a detached session's own window is already claiming its PTY size, and `MAX_WS_PER_SESSION` needs no change since Pane A/B are always two different sessions. ⚠️ Either pane's session ending (deleted locally or from another client) auto-collapses the split — Pane A's session ending promotes Pane B to the new single pane via `selectSession(id, { auto: true })` (an app-driven selection, so it must not spend the session's idle alert — see the Approvals Inbox note above), never by trying to hot-swap the lightweight `TerminalTile` object into the primary singleton state. ⚠️ Pane B refits on every window/sidebar/tab-rail resize via the SAME trailing-edge `ResizeObserver` callback that resizes Pane A (`throttledResize` in terminal-ui.js) — it only ever measured Pane A's own container, so without the explicit `this._forEachTile?.((tile) => tile.fit(), { grid: false })` call there (grid tiles are left out: the grid's own observer refits them on the same resize) Pane B silently kept its stale PTY size through every resize that did not happen to be a divider drag. ⚠️ A dropped WebSocket writes a `[disconnected, reconnecting…]` marker into Pane B and reconnects on the primary pane's backoff ladder (`CodemanWsReconnect` plus jitter; the attempt count resets only on a successful open), then refreshes the buffer to close the output gap. ⚠️ The open handler clears `_wsClosed`/`_markerOwed` BEFORE that refresh, or the refresh re-owes the marker and stamps it under a healthy pane. ⚠️ 4003/4004/4009/4010 stop the pane for good, report once through `onExit(code)` and write a marker saying why (`CodemanWsReconnect` alone would retry 4003). ⚠️ A replacement socket detaches the old one first and every handler ignores a socket that is no longer `this.ws`, so a late 4010 from a superseded socket cannot stop its successor; `destroy()` cancels a pending reconnect. Related but distinct: `detachSession()` already opens one session in a separate OS-level browser window (`isSoloWindow`) — that is prior art for "two sessions visible at once" but not for one window with a draggable in-page divider, which is what this feature adds. ⚠️ Pane B installs its own `attachCustomKeyEventHandler` gating the same app-level chords Pane A's own handler gates (command palette, Alt+1-9/[/] tab nav, Alt+B sidebar toggle, Ctrl+Z suspend, Shift/Ctrl+Enter newline, smart-copy Ctrl+C) — without it the document capture-phase handler's `preventDefault()` (which never stops xterm) let each chord ALSO write its raw byte/escape sequence into Pane B's live PTY on top of whatever the app action did to Pane A (COD-153). Ctrl+Z is swallowed unless Pane B's own session is `mode === 'shell'`, mirroring terminal-ui.js's reasoning: in a plain shell it is the user's own job-control tool, everywhere else it silently suspends an unattenLine truncated
|
||||
**Split-pane sessions** (`showSplitButton`, header button, default OFF, per-device like `showFileViewerButton` — not in `SettingsUpdateSchema`, `displayKeys` in settings-ui.js): shows two live sessions side-by-side in one Codeman window. Pane A is the untouched, existing singleton terminal (`this.terminal`/`this._ws` in terminal-ui.js); Pane B is an independent `TerminalTile` (terminal-tile.js, constructed by the orchestration in terminal-split.js) with its own xterm instance and its own `/ws/sessions/:id/terminal` WebSocket, whose `cid` is the tab's identity with a `:tile` suffix, so it can never supersede the primary pane's socket (the registry supersedes by cid per session). ⚠️ **Pane B is deliberately plainer than Pane A** — no local-echo overlay, no CJK IME, no touch/mobile handlers, no keyboard accessory bar (it does carry the primary pane's hollow-buffer wheel paging and desktop click report, through terminal-ui.js's own gates aimed at the tile, and its own soft-keyboard input owner: the iOS native-input owner (`_iosNativeInput`, terminal-ios-native-input.js, #830) on iOS WebKit touch, otherwise the keyCode-229 controller from terminal-keycode229-recovery.js, the #441 next-keydown drain and #541's edit-based diff for Android autocorrect, since the 1180px width gate is reachable by a wide Android tablet; see terminal-tile.js's fileoverview) — since this is a desktop-only feature (a split view needs a wide viewport) and those features exist for mobile/touch input; `.btn-split` is hard-hidden below 1180px regardless of the setting by the `@media (max-width: 1179px)` rule in styles.css (mobile.css only carries a comment pointing at it: that file loads up to 1023px, so it cannot cover the 1024-1179px tablet range the feature also needs to stay off), and the per-device setting means turning it on at a desk can never sync it onto a phone in the first place. No persistence: closing the browser tab or reloading always returns to the normal single-pane view; there is no localStorage key for split state. ⚠️ Splitting a session against itself is disallowed (the picker excludes the active session), **as is splitting against a popped-out (detached) session** — `buildSplitPickerSessions()` excludes `detachedSessions` because a detached session's own window is already claiming its PTY size, and `MAX_WS_PER_SESSION` needs no change since Pane A/B are always two different sessions. ⚠️ Either pane's session ending (deleted locally or from another client) auto-collapses the split — Pane A's session ending promotes Pane B to the new single pane via `selectSession(id, { auto: true })` (an app-driven selection, so it must not spend the session's idle alert — see the Approvals Inbox note above), never by trying to hot-swap the lightweight `TerminalTile` object into the primary singleton state. ⚠️ Pane B refits on every window/sidebar/tab-rail resize via the SAME trailing-edge `ResizeObserver` callback that resizes Pane A (`throttledResize` in terminal-ui.js) — it only ever measured Pane A's own container, so without the explicit `this._forEachTile?.((tile) => tile.fit(), { grid: false })` call there (grid tiles are left out: the grid's own observer refits them on the same resize) Pane B silently kept its stale PTY size through every resize that did not happen to be a divider drag. ⚠️ A dropped WebSocket writes a `[disconnected, reconnecting…]` marker into Pane B and reconnects on the primary pane's backoff ladder (`CodemanWsReconnect` plus jitter; the attempt count resets only on a successful open), then refreshes the buffer to close the output gap. ⚠️ The open handler clears `_wsClosed`/`_markerOwed` BEFORE that refresh, or the refresh re-owes the marker and stamps it under a healthy pane. ⚠️ 4003/4004/4009/4010 stop the pane for good, report once through `onExit(code)` and write a marker saying why (`CodemanWsReconnect` alone would retry 4003). ⚠️ A replacement socket detaches the old one first and every handler ignores a socket that is no longer `this.ws`, so a late 4010 from a superseded socket cannot stop its successor; `destroy()` cancels a pending reconnect. Related but distinct: `detachSession()` already opens one session in a separate OS-level browser window (`isSoloWindow`) — that is prior art for "two sessions visible at once" but not for one window with a draggable in-page divider, which is what this feature adds. ⚠️ Pane B installs its own `attachCustomKeyEventHandler` gating the same app-level chords Pane A's own handler gates (command palette, Alt+1-9/[/] tab nav, Alt+B sidebar toggle, Ctrl+Z suspend, Shift/Ctrl+Enter newline, smart-copy Ctrl+C) — without it the document capture-phase handler's `preventDefault()` (which never stops xterm) let each chord ALSO write its raw byte/escape sequence into Pane B's live PTY on top of whatever the app action did to Pane A (COD-153). Ctrl+Z is swallowed unless Pane B's own session is `mode === 'shell'`, mirroring Line truncated
|
||||
|
||||
### Tile grid
|
||||
|
||||
@@ -1123,7 +1155,7 @@ Tests: `test/tab-rail-search.test.ts` (gate) and `test/tab-rail-search.browser.t
|
||||
|
||||
**Adding a skin means touching four places, and each one fails silently on its own**: (1) the `html[data-skin="…"]` token block in `styles.css`; (2) the xterm ANSI palette in `CODEMAN_XTERM_THEMES` (terminal-ui.js) — a missing entry falls back to `daylight-blue`, so the terminal simply stays the wrong color; (3) the pre-paint allowlist array in `index.html` — a skin missing there is coerced to `daylight-blue` on every reload, which reads as "my theme keeps resetting"; (4) the `<select>` in App Settings → Appearance → Theme. `test/skin-themes.test.ts` is the static four-way guard.
|
||||
|
||||
**Light skins carry three extra obligations.** `color-scheme: light` on the `html[data-skin]` block, or the UA renders native `<select>` popups, date pickers and scrollbars as dark widgets on a light page. xterm `minimumContrastRatio: 4.5` (set at construction in terminal-ui.js **and** panels-ui.js for teammate terminals, and re-applied in `applyTerminalSkin()`), because CLIs emit colors chosen for dark backgrounds; dark skins keep `1` to avoid the per-cell contrast work. And `applyTerminalSkin()` must call `this._localEchoOverlay?.refreshFont()` — the zero-lag overlay **caches** the terminal fg/bg at construction, so without the refresh typed-but-not-yet-flushed text keeps the previous theme's dark backing after a live skin switch.
|
||||
**Light skins carry three extra obligations.** `color-scheme: light` on the `html[data-skin]` block, or the UA renders native `<select>` popups, date pickers and scrollbars as dark widgets on a light page. xterm `minimumContrastRatio: 4.5` (set at construction in terminal-ui.js **and** terminal-tile.js, and re-applied in `applyTerminalSkin()`), because CLIs emit colors chosen for dark backgrounds; dark skins keep `1` to avoid the per-cell contrast work. And `applyTerminalSkin()` must call `this._localEchoOverlay?.refreshFont()` — the zero-lag overlay **caches** the terminal fg/bg at construction, so without the refresh typed-but-not-yet-flushed text keeps the previous theme's dark backing after a live skin switch.
|
||||
|
||||
**Shared surface tokens, not literals.** Elevated/floating surfaces resolve through `--floating-bg`, `--control-bg{,-hover}`, `--control-border{,-hover}`, `--banner-bg-a/b`, `--modal-backdrop` and `--elevated-shadow`, so modals, the command palette, dropdowns, subagent/ultracode windows, file previews and the mobile sheets follow the skin instead of hardcoded near-black rgba. ⚠️ Every skin that wants its own elevated look must override these — a skin that omits `--floating-bg` silently inherits the `:root` value, which is how the OG skin's near-black modals drifted slate. `styles.css` also defines **compatibility aliases** (`--bg-primary/secondary/tertiary`, `--text-primary/secondary`, `--border-color`, `--accent-color`, `--success`, `--error`, `--danger`, `--font-mono`, `--shadow-lg`) that forward to the canonical tokens; panels written against those names previously resolved to *nothing* (invalid at computed-value time), so the aliases are load-bearing, not cosmetic.
|
||||
|
||||
@@ -1139,7 +1171,9 @@ Tests: `test/tab-rail-search.test.ts` (gate) and `test/tab-rail-search.browser.t
|
||||
|
||||
**A fold is not a keyboard.** `KeyboardHandler.handleViewportResize()` (mobile-handlers.js) used to read any visual-viewport height drop over 150px as the keyboard appearing. A virtual keyboard only ever takes HEIGHT, so a resize that changes the WIDTH is the device changing shape (a rotation, or a foldable opening or closing) and is skipped by both detection branches. Closing an iPhone Duo (626→466pt wide, 890→678pt tall) otherwise latched `keyboardVisible` with no keyboard on screen: the accessory bar appeared, `main` grew 84px of dead padding, and `updateAppHeight()`, which bails while the keyboard is up, stopped refreshing `--app-height`. The latch was sticky because clearing it needed the height back within 100px of a baseline belonging to a display the user was no longer looking at. The shape branch re-baselines instead, which is also what lets a keyboard opened after the fold be detected, and `init()` seeds `lastViewportWidth` so the first resize of the page is not itself read as a shape change.
|
||||
|
||||
**With the keyboard up, the new baseline is `window.innerHeight`, never the shrunk visual height.** The page sets no `interactive-widget`, so the default resizes-visual mode holds on both engines: the keyboard shrinks only the visual viewport and the layout viewport stays the display's full height (`updateLayoutForKeyboard()` relies on the same fact). The first version baselined to the shrunk height, which made `heightDiff` 0, so the settle event the OS animation fires at the new width (or any later address-bar drift) satisfied the hide branch and ran `onKeyboardHide()` with the keyboard still on screen: accessory bar hidden, the toolbar lift dropped, `main`'s padding cleared. It could not recover, because no further 150px drop can re-arm the show branch against a baseline already sitting at the shrunk height. Reproduced against the real handler in the vm harness with both the fold flavour (626x590 → 466x378 → 466x378) and the rotation flavour (393x359 → 852x150 → 852x160); `test/viewport-shape-change.test.ts` models the two heights separately and pins both.
|
||||
**With the keyboard up, the new baseline is `window.innerHeight`, never the shrunk visual height.** The page sets no `interactive-widget`, so the default resizes-visual mode holds on both engines: the keyboard shrinks only the visual viewport and the layout viewport stays the display's full height (`updateLayoutForKeyboard()` relies on the same fact, but measures that height as the larger of `innerHeight` and `documentElement.clientHeight`: on a first keyboard open iOS Safari briefly reported `innerHeight` as the shrunk visual height, 323 against a 640 layout viewport, which zeroed the bars' lift). The first version baselined to the shrunk height, which made `heightDiff` 0, so the settle event the OS animation fires at the new width (or any later address-bar drift) satisfied the hide branch and ran `onKeyboardHide()` with the keyboard still on screen: accessory bar hidden, the toolbar lift dropped, `main`'s padding cleared. It could not recover, because no further 150px drop can re-arm the show branch against a baseline already sitting at the shrunk height. Reproduced against the real handler in the vm harness with both the fold flavour (626x590 → 466x378 → 466x378) and the rotation flavour (393x359 → 852x150 → 852x160); `test/viewport-shape-change.test.ts` models the two heights separately and pins both.
|
||||
|
||||
**A pan of the visual viewport moves `.app` with it.** In resizes-visual mode a focused field that starts behind the keyboard makes Android pan the visual viewport down to reveal it: the pinned `#cjkInput` sits at the bottom of the layout viewport, and Chrome panned 285px with a 458px visual viewport in a 744px layout one. `.app` is sized to the visual viewport (`--app-height`) but laid out at the top of the layout viewport, so that pan left only the terminal's last line on screen. On phones `updateLayoutForKeyboard()` therefore sets `.app`'s `translateY` to `visualViewport.offsetTop` while the keyboard is up, whatever has focus (no pan, the usual case, moves nothing), and clears it on every other branch and in `resetLayout()`. ⚠️ The transform makes `.app` the box its `position: fixed` children are placed against (header, `.toolbar`, the accessory bar, which is inserted before the toolbar, `#cjkInput`, and the phone case sheet, `#mobileCasePickerModal`), so their lift is measured from `.app`'s bottom (`insideLift`), not the layout viewport's: lifting them by the layout gap as well floated them above the keyboard on a partial pan. Separately, `KeyboardHandler.isInputElement()` skips `#cjkInput` like xterm's inputs, because the focusin `scrollIntoView({ block: 'center' })` centred the fixed field in its ancestors and pushed the terminal off screen. Pinned by `test/keyboard-handler-pinned-field.test.ts`.
|
||||
|
||||
**The hinge is a reserved region, and the CSS is inert by construction.** The CSS Viewport Segments media features report two segments only while a foldable is actually bent; `--fold-inline-end` / `--fold-block-end` (end of styles.css) measure the strip to keep clear from the LEADING segment (`env(viewport-segment-right 0 0)` and `env(viewport-segment-bottom 0 0)`, physical sides in every text direction) and are `0px` on everything else. The seven centred overlays are all `position: fixed; inset: 0` flex boxes; each shrinks its CONTENT box with padding rather than the box itself, so the backdrop still covers the far side of the fold and still swallows taps there. The cascade traps, each measured in headless Chromium against styles.css + mobile.css in index.html link order: (1) a later `padding-right` longhand beats the earlier `padding` shorthand it composes with, so each fold rule re-states the overlay's own gutter; (2) a base gutter that a LATER `@media` block overrides needs its own fold restatement in that block on a ZERO base, since the unconditional rules at the end of the file otherwise put the gutter back (the phone path picker and path preview drop to `padding: 0` under 600px and came back at 16px and 18px on every phone); (3) a compound rule written to outrank a mobile.css shorthand must be scoped to the band where that shorthand applies, because outside it there is no gutter to compose with (the palette's `.modal.command-palette-modal` added 0.75rem at 393, 900 and 1400px and pushed the shell 6px off centre, and inside the band it lost its bottom gutter to the shorthand until it restated that side too); (4) mobile.css loads AFTER styles.css, so a same-specificity rule there wins under its own breakpoint (the response viewer's `max-height: 92dvh` under 600px beat the tabletop cap, which now has a twin at the end of mobile.css). `test/foldable-layout.test.ts` DERIVES the overlay list from the stylesheet, simulates the cascade across both files at every breakpoint with and without the fold rules, and requires the two results to differ by exactly the fold strip, so each of the four fails there instead of on hardware nobody has.
|
||||
|
||||
@@ -1207,7 +1241,7 @@ Tests: `test/terminal-touch-tap.test.ts`, `test/session-swipe-gesture.test.ts` (
|
||||
|
||||
⚠️ **The boxes ARE a DOM grouping**, unlike by state, which is safe only because a tab changes case far less often than it changes state: `_tabClusterLayout().key` is the whole structure, and the incremental path rebuilds whenever it differs from the last full render's. The keyboard walk keeps boxes together (box index first, then computed order, since a sorted rail orders rows inside each box). Drag only reorders inside one box, as it only reorders inside one state group (`_isTabDropAcrossGroups()`).
|
||||
|
||||
**Ledger.** CSS only, on `.tabs-ledger` inside `@media (min-width: 768px)` and the header host: the flat list on an auto-fill column grid with equal cells, mono type and a 3px status bar (`--ledger-bar`: yellow for a waiting alert, red for an action alert or an error, muted for stopped, exited and web tabs) instead of the dot. ⚠️ It must not change the markup (pinned: the ledger's innerHTML equals classic's); the rail, the sidebar and narrower strips show the plain list.
|
||||
**Ledger.** CSS only, on `.tabs-ledger` inside `@media (min-width: 768px)` and the header host: the flat list on an auto-fill column grid with equal cells, mono type and a 3px status bar (`--ledger-bar`: yellow for a waiting alert, red for an action alert or an error, muted for stopped, exited and web tabs) instead of the dot. ⚠️ A WORKING cell keeps the dot (`.tab-status:not(.busy)` is what is hidden): the bar is green for idle and working alike, and the spinner is the dot's own `.tab-status.busy::after` ring, so hiding every dot left a busy session with no mark (pinned by `test/tab-clusters.test.ts`); an exited agent's cell hides it, as the classic strip hides the ring there. ⚠️ It must not change the markup (pinned: the ledger's innerHTML equals classic's); the rail, the sidebar and narrower strips show the plain list.
|
||||
|
||||
**Classic, wrapped: the L-shaped strip.** Once a classic desktop strip in the header host wraps (`tabs-auto-wrap`, or the manual `tabs-two-rows`), `_syncTabStripCorner()` (app.js) adds `.tabs-corner`: `#headerRight` goes `position: absolute` over the strip's top-right corner and the strip runs the header's full width, so only the row(s) beside the toolbar stop short of it and every later row uses the width under it. A flex line cannot be shortened on its own, so in that state the strip is `display: block` with `inline-flex` tabs flowing around a `::before` float sized from the toolbar's box (`--tab-corner-width` / `--tab-corner-height`); the old `row-gap` (lineage's `--lineage-row-gap` included) becomes the tabs' bottom margin and the bottom padding shrinks by the same amount, so row spacing and lineage routing room are unchanged. ⚠️ `updateTabOverflowMode()` removes `.tabs-corner` BEFORE it measures the wrap (the corner takes the toolbar out of the header's flow, which widens the strip), so the wrap is still judged against the one-row layout and an unwrapped strip looks exactly as before. ⚠️ Flex-only rules do not apply to the strip in that state. ⚠️ A strip that already scrolls (past `--tab-strip-max-height`) keeps the plain wrap, checked on the plain strip before the class goes on: the float scrolls with the tabs while the toolbar stays put, and toggling the class on a scrolled strip lets scroll anchoring move it; a strip pushed past the max-height by the float itself falls back too. A first tab too wide for the room beside the toolbar (the whole first line would drop below it) is trimmed to the room instead (`tab-corner-fit`, `max-width: var(--tab-corner-first-max)`, its name ellipsized): a selected tab is wider (gear and close show), so a fallback here made the whole layout follow the selection. Only a room under `TAB_CORNER_MIN_FIRST_TAB` keeps the plain wrap. ⚠️ The cap goes on the first tab on every pass, never only once it measures too wide: `selectSession()` widens a newly selected tab at once and this sync is debounced, so a cap set afterwards leaves the first row below the toolbar until it runs. It changes nothing on a tab narrower than the room. A `ResizeObserver` on the toolbar re-decides wrap and corner and redraws the connection lines when a reading or the header divider resizes it without a tab render. Scope: classic arrangement, desktop, header host only; state/case/ledger, the sidebar and the vertical rail never get the class (`applySessionListLayout()` drops it when the strip moves). Tests: `test/tab-strip-corner.browser.test.ts` (browser suite).
|
||||
|
||||
@@ -1255,7 +1289,7 @@ The age stamps are refreshed **in place** by a 20s clock (`_tickHomeSessionsTime
|
||||
|
||||
⚠️ **The `@font-face` descriptor, not the file, is what the browser synthesizes from**: `fonts/jetbrains-mono-variable.woff2` carries a `wght` axis of 100-800, and while `styles.css` declared it `400 700` every weight below 400 rendered identically to 400 and 800 identically to 700 — measured — so the setting was a no-op for anyone without Fira Code or Cascadia Code installed, which is most installs. It is declared `100 800`; re-narrowing it silently guts the feature (`test/terminal-font-weight.test.ts` pins the range).
|
||||
|
||||
⚠️ A live save must reach **both echo overlays** (`refreshFont()` — they cache `terminal.options.fontWeight` and paint it into their spans, so typed characters otherwise keep the old weight, most visible on a phone) **and open Agent Teams panes** (they read their options at construction, exactly like `applyTerminalSkin()` propagates).
|
||||
⚠️ A live save must reach **both echo overlays** (`refreshFont()` — they cache `terminal.options.fontWeight` and paint it into their spans, so typed characters otherwise keep the old weight, most visible on a phone) **and every open tile and split pane** (`_forEachTile`: they read their options at construction, exactly like `applyTerminalSkin()` propagates).
|
||||
|
||||
⚠️ `_awaitTerminalFont()` is deliberately untouched: `CharSizeService` measures through the CSS `font` shorthand, which RESETS the weight, so the measured face is always the 400 one and a weighted descriptor would ask for nothing new.
|
||||
|
||||
@@ -1269,7 +1303,7 @@ The age stamps are refreshed **in place** by a 20s clock (`_tickHomeSessionsTime
|
||||
|
||||
⚠️ It must disarm on ALL of: use, second tap, any other accessory key, session switch, keyboard dismissal, and a layout swap; a modifier left armed turns the next innocent keystroke into a control byte.
|
||||
|
||||
⚠️ **onData is not the only input path** — with `cjkInputEnabled` on, the CJK textarea owns the keyboard (onData returns early for everything it swallows, and the focus router sends `terminal.focus()` there, which is where the bar refocuses after every key), so `_handleCjkInput()` applies the modifier too. It is that module's single choke point to the PTY, so one call covers typed characters, IME flushes, Enter, backspace and arrows. Without it an armed modifier could neither fire NOR be spent, and survived to a later keystroke.
|
||||
⚠️ **onData is not the only input path** — with `cjkInputEnabled` on, the CJK textarea owns the keyboard (onData returns early for everything it swallows, and the focus router sends `terminal.focus()` there, which is where the bar refocuses after every key), so `_handleCjkInput()` applies the modifier too. It is that module's single choke point to the PTY in live mode, so one call covers typed characters, IME flushes, Enter, backspace and arrows; in Send on Enter a held answer leaves through `_sendCjkPrompt()` instead, which spends the modifier, while an armed next character still goes through `_handleCjkInput()`. Without it an armed modifier could neither fire NOR be spent, and survived to a later keystroke.
|
||||
|
||||
Mapping is `ctrlByteFor()` (`code & 0x1f` over @A-Z[\]^_ and a-z, plus Ctrl+Space=NUL / Ctrl+?=DEL); characters with no control equivalent pass through unchanged, like a hardware keyboard.
|
||||
|
||||
@@ -1281,7 +1315,7 @@ Mapping is `ctrlByteFor()` (`code & 0x1f` over @A-Z[\]^_ and a-z, plus Ctrl+Spac
|
||||
|
||||
⚠️ **Drafts are per-session and in memory only** (`_composerDrafts`, never persisted: prompts routinely carry secrets, and persisting them would need the 0600 treatment the intent store gets). Every non-Send exit (Cancel, backdrop, Escape, "Use terminal keyboard") leaves the taken text ONLY in the draft, with the dot on the key (`has-draft`, kept in step by `_syncComposerDraftIndicator`) as the signal that the terminal prompt is empty on purpose, and `_cleanupSessionData` discards the draft with the session.
|
||||
|
||||
⚠️ **Delivery is a hand-built bracketed-paste frame** (`\x1b[200~` + the text with newlines mapped to `\r` + `\x1b[201~`, byte-identical to what `terminal.paste()` would emit) through `_sendInputAsync` WITHOUT `{ useMux: true }`, plus a SEPARATE Enter 120 ms later WITH it (codex drops keys that share a PTY read with a bracketed paste). Not `terminal.paste()`, for two reasons: xterm's `bracketedPasteMode` mirror is false for every session after a tab switch or reload (`terminal.reset()` in the replay re-clones the DEC modes, the tmux capture carries no `?2004h`, and tmux never forwards the pane's DECSET to a client after attach), so a paste through xterm would go out unbracketed and the CLI would submit at the first `\r`; and xterm's onData is where the local-echo paste branch flushes pending overlay text AHEAD of the block, text the composer has already taken and erased from the PTY, so the frame goes straight to the wire with the composer as the prompt's only owner. The unconditional frame is safe for a CLI that never enabled DECSET 2004 because tmux does the gating (measured against a live pane: markers stripped for a `cat -v` pane, forwarded intact to a process that had emitted `?2004h`).
|
||||
⚠️ **Delivery is a hand-built bracketed-paste frame** (`\x1b[200~` + the text with newlines mapped to `\r` + `\x1b[201~`, byte-identical to what `terminal.paste()` would emit) enqueued on the session FIFO (`_enqueueInput`, `_sendBracketedPaste()`) WITHOUT `{ useMux: true }`, then a 120 ms `gap` and a SEPARATE Enter WITH it, all reserved for the composer's session at Send (codex drops keys that share a PTY read with a bracketed paste). Not `terminal.paste()`, for two reasons: xterm's `bracketedPasteMode` mirror is false for every session after a tab switch or reload (`terminal.reset()` in the replay re-clones the DEC modes, the tmux capture carries no `?2004h`, and tmux never forwards the pane's DECSET to a client after attach), so a paste through xterm would go out unbracketed and the CLI would submit at the first `\r`; and xterm's onData is where the local-echo paste branch flushes pending overlay text AHEAD of the block, text the composer has already taken and erased from the PTY, so the frame goes straight to the wire with the composer as the prompt's only owner. The unconditional frame is safe for a CLI that never enabled DECSET 2004 because tmux does the gating (measured against a live pane: markers stripped for a `cat -v` pane, forwarded intact to a process that had emitted `?2004h`).
|
||||
|
||||
⚠️ The frame must never take the mux fallback: `TmuxManager.sendInput()` strips every `\r`, the frame's line separator, so the lines weld into one, pasted inside a second pair of markers, and get submitted.
|
||||
|
||||
@@ -1299,6 +1333,8 @@ Tests: `test/mobile-prompt-composer.test.ts` (in the CI gate, deliberately not u
|
||||
|
||||
**(2)** In `_handleMobileTerminalTap`, a second tap on **inert `content`** (`startedWithTerminalFocus`) blurs instead of re-focusing. ⚠️ Scoped to `content` on purpose: the prompt row (`input`) keeps focus-then-position so a second tap still places the caret, and actionable rows blur earlier via `_isActionableMobileTerminalTap`.
|
||||
|
||||
⚠️ **The pinned CJK field keeps its focus through a swipe.** `initTerminal`'s touchstart blurs the focused input on `content` before the gesture is known to be a tap or a scroll. For xterm's helper textarea that blur, with the `preventDefault` beside it, is what keeps the compatibility click from opening the keyboard. The visible `#cjkInput` owns the keyboard instead, so `_contentTouchStartBlurs()` leaves it focused; blurring it closed the keyboard on every swipe that started on the live screen. A real tap still closes it: inert content through (2), a link in `_handleMobileTerminalTap`'s link branch (which blurs because touchstart did not), a long press in `_beginTouchSelection`. A sideways session swipe keeps it open, since the field's draft is per session. Pinned by `test/terminal-touch-tap.test.ts`.
|
||||
|
||||
⚠️ **A scroll ends in `touchend` too** — dismissing there closes the keyboard and drops the composer mid-read, so travel is tracked from `touchstart` and multi-touch is never a tap. Both classifiers MUST share one threshold: `initTerminal`'s `TAP_THRESHOLD` reads `MOBILE_KEYBOARD_DISMISS_TAP_SLOP`, since a gesture the terminal calls a scroll and the dismiss handler calls a tap is exactly that bug.
|
||||
|
||||
⚠️ **An accessory key that keeps the keyboard up must not take focus on the press.** The keys that act on the terminal and leave the keyboard open (`ACCESSORY_REFOCUS_ACTIONS` in keyboard-accessory.js: scroll, arrows, Tab, Shift+Tab, Ctrl, Esc, clear input and the rest) cancel the `mousedown` default, the same pattern as the Attach input, so the hidden textarea keeps focus through the press; the `terminal.focus()` in the click handler stays as the fallback. Letting the tap blur the terminal and refocusing it afterwards made every such key start a keyboard dismissal, a blur/focus pair per tap that shifted the toolbar each time. A first tap on clear/compact only arms the confirm and is treated the same; the confirming tap, and keys that open a dialog or dismiss the keyboard on purpose, keep the default. Pinned against the real module by `test/accessory-keeps-terminal-focus.test.ts`.
|
||||
@@ -1321,7 +1357,7 @@ Tests: `test/mobile-prompt-composer.test.ts` (in the CI gate, deliberately not u
|
||||
|
||||
### PTY and browser terminal geometry
|
||||
|
||||
**The PTY and the browser terminal must never disagree about size** (issue #464, `syncTerminalGeometry()` in terminal-ui.js): Claude Code's TUI wraps its frame at the width the PTY reported and erases the previous frame by walking the cursor up the number of rows it BELIEVES that frame occupied. A browser terminal of a different width makes each logical line take more physical rows than Ink counted, so `eraseLines(n)` clears too few and the new frame paints over rows nothing erased — the doubled lines and half-overwritten prose in #464, **measured** against this repo's xterm (a 120-column PTY against a 62-column terminal renders every wrapped line twice; `test/terminal-pty-geometry.test.ts` pins it, and pins the clean render at matching widths so the assertion cannot pass against code that fixes nothing). ⚠️ **`fitAddon.fit()` is NOT the way to resize this terminal.** It resizes xterm to `proposeDimensions()` RAW while every server-facing path reports those floored at 40x10, so whenever the floor bit the two diverged silently — **measured in Chrome at 430px**: font size 44 proposed 13 columns, the server was told 40, and xterm stayed at 13. `syncTerminalGeometry()` fits, floors and applies as one step and is the ONE function that may change the size; `test/terminal-pty-geometry.test.ts` sweeps the seven modules that touch the main terminal (terminal-ui, mobile-handlers, app, ralph-panel, settings-ui, tab-rail-resize, notification-manager) for a bare fit; the split pane and teammate terminals own their own sizing and are out of scope. ⚠️ **Withhold the fit wherever you withhold the SIGWINCH.** `throttledResize` (virtual keyboard up) and `sendResize` (session detached into its own window) used to reflow locally and skip only the server write, which is the one combination that cannot be right. ⚠️ **A font change is a geometry change**: `setFontSize`/`setFontFamily`/`setFontWeight` move the cell size and told the server nothing, so raising the font on a phone left the CLI wrapping at the old column count (`_refitAfterCellSizeChange`). ⚠️ **Resize is no longer write-only.** `Session.resize` DECLINES a small-viewport request while a desktop connection holds an active sizing claim and says nothing, so both transports now answer with `Session.ptyGeometry` (`{"t":"zc"}` on the socket, the body of the resize POST) and `_onPtyGeometryReport` adopts it — a terminal that keeps a WIDTH the PTY refused renders GARBLED, not merely wrong-sized. ⚠️ While that refusal stands (`_paneWidthRefused`), a resize ASKS for the container's width without applying it (`_geometryForResizeRequest`: rows follow the container, columns stay at the PTY's): fitting first re-wrapped the whole buffer to the container and back on every 30s mobile retry, and ran the scrollback clear for a resize that brings no redraw. `selectSession` clears the flag, since it belongs to the previous pane. ⚠️ **`ptyGeometry` is null without a live pane**, never the field values: they are seeded at spawn (`_notePtySpawnGeometry`, so a reattached pane reports its tmux window's real size) and moved by `resize()`, but a dead-pane session still holds the constructor defaults of 120x40 or a gone pane's size — reporting those made a client adopt a size no process was ever told and claim another device owned the pane when none existed. ⚠️ **COLUMNS ONLY** (one documented exception, the keyboard row hold in the next paragraph). Adopting the PTY's ROWS was a regression: a phone taking a desktop's 43 rows into a viewport with room for 18 painted an `.xterm-screen` far taller than its container, xterm's own viewport then had nothing to scroll, and the CLI's input line sat below the container with no gesture able to reach it — output visible, typing invisible, for as long as the claim stayed hot. Width is the axis the wrap arithmetic depends on; rows only decide how much is on screen, and keeping the local count keeps the composer at the bottom of a viewport that scrolls. ⚠️ **`.term-overflows-x` keys on what does not FIT, not on a PTY mismatch**, because the 40-column floor widens the terminal past a narrow container with the PTY agreeing throughout (measured at 360px: font 18 paints 433px, font 24 paints 578px — 38% unreachable, and `increaseFontSize` reaches 24 in two taps). `_syncTerminalOverflowAffordance()` MEASURES `.xterm-screen` against the container on the next frame rather than deriving it from cell arithmetic. ⚠️ That rule sets **both** overflow axes — mobile.css loads later with `.terminal-container { overflow: visible }`, and a bare `overflow-x` would leave overflow-y computing to `auto`, handing the browser a vertical scroll container the terminal's touch handler does not know about — and sets **no `touch-action`**: the terminal's own touchmove handler pans it (`canPanHorizontally`), because `touchstart` preventDefault()s every 'content' tap and that cancels a native `pan-x` before it starts (measured: a 140px Line truncated
|
||||
**The PTY and the browser terminal must never disagree about size** (issue #464, `syncTerminalGeometry()` in terminal-ui.js): Claude Code's TUI wraps its frame at the width the PTY reported and erases the previous frame by walking the cursor up the number of rows it BELIEVES that frame occupied. A browser terminal of a different width makes each logical line take more physical rows than Ink counted, so `eraseLines(n)` clears too few and the new frame paints over rows nothing erased — the doubled lines and half-overwritten prose in #464, **measured** against this repo's xterm (a 120-column PTY against a 62-column terminal renders every wrapped line twice; `test/terminal-pty-geometry.test.ts` pins it, and pins the clean render at matching widths so the assertion cannot pass against code that fixes nothing). ⚠️ **`fitAddon.fit()` is NOT the way to resize this terminal.** It resizes xterm to `proposeDimensions()` RAW while every server-facing path reports those floored at 40x10, so whenever the floor bit the two diverged silently — **measured in Chrome at 430px**: font size 44 proposed 13 columns, the server was told 40, and xterm stayed at 13. `syncTerminalGeometry()` fits, floors and applies as one step and is the ONE function that may change the size; `test/terminal-pty-geometry.test.ts` sweeps the seven modules that touch the main terminal (terminal-ui, mobile-handlers, app, ralph-panel, settings-ui, tab-rail-resize, notification-manager) for a bare fit; the split pane and the tiles own their own sizing and are out of scope. ⚠️ **Withhold the fit wherever you withhold the SIGWINCH.** `throttledResize` (virtual keyboard up) and `sendResize` (session detached into its own window) used to reflow locally and skip only the server write, which is the one combination that cannot be right. ⚠️ **A font change is a geometry change**: `setFontSize`/`setFontFamily`/`setFontWeight` move the cell size and told the server nothing, so raising the font on a phone left the CLI wrapping at the old column count (`_refitAfterCellSizeChange`). ⚠️ **Resize is no longer write-only.** `Session.resize` DECLINES a small-viewport request while a desktop connection holds an active sizing claim and says nothing, so both transports now answer with `Session.ptyGeometry` (`{"t":"zc"}` on the socket, the body of the resize POST) and `_onPtyGeometryReport` adopts it — a terminal that keeps a WIDTH the PTY refused renders GARBLED, not merely wrong-sized. ⚠️ While that refusal stands (`_paneWidthRefused`), a resize ASKS for the container's width without applying it (`_geometryForResizeRequest`: rows follow the container, columns stay at the PTY's): fitting first re-wrapped the whole buffer to the container and back on every 30s mobile retry, and ran the scrollback clear for a resize that brings no redraw. `selectSession` clears the flag, since it belongs to the previous pane. ⚠️ **`ptyGeometry` is null without a live pane**, never the field values: they are seeded at spawn (`_notePtySpawnGeometry`, so a reattached pane reports its tmux window's real size) and moved by `resize()`, but a dead-pane session still holds the constructor defaults of 120x40 or a gone pane's size — reporting those made a client adopt a size no process was ever told and claim another device owned the pane when none existed. ⚠️ **COLUMNS ONLY** (one documented exception, the keyboard row hold in the next paragraph). Adopting the PTY's ROWS was a regression: a phone taking a desktop's 43 rows into a viewport with room for 18 painted an `.xterm-screen` far taller than its container, xterm's own viewport then had nothing to scroll, and the CLI's input line sat below the container with no gesture able to reach it — output visible, typing invisible, for as long as the claim stayed hot. Width is the axis the wrap arithmetic depends on; rows only decide how much is on screen, and keeping the local count keeps the composer at the bottom of a viewport that scrolls. ⚠️ **`.term-overflows-x` keys on what does not FIT, not on a PTY mismatch**, because the 40-column floor widens the terminal past a narrow container with the PTY agreeing throughout (measured at 360px: font 18 paints 433px, font 24 paints 578px — 38% unreachable, and `increaseFontSize` reaches 24 in two taps). `_syncTerminalOverflowAffordance()` MEASURES `.xterm-screen` against the container on the next frame rather than deriving it from cell arithmetic. ⚠️ That rule sets **both** overflow axes — mobile.css loads later with `.terminal-container { overflow: visible }`, and a bare `overflow-x` would leave overflow-y computing to `auto`, handing the browser a vertical scroll container the terminal's touch handler does not know about — and sets **no `touch-action`**: the terminal's own touchmove handler pans it (`canPanHorizontally`), because `touchstart` preventDefault()s every 'content' tap and that cancels a native `pan-x` before it starts (measured: a 140px swipe reaLine truncated
|
||||
|
||||
**The one exception to COLUMNS ONLY: rows held under the on-screen keyboard** (#672, `keyboardHoldsRows`, per-device, default ON): every PTY height change makes Claude Code's inline renderer clear the screen and reprint only the transcript tail that fits the new height, so the rows above that tail are gone from tmux and older ones stay in history as stale copies, and the phone keyboard opening and closing was such a change each time. **Measured** on Claude Code 2.1.306 with tmux 3.2a, a fresh session already at the phone's size printing 100 numbered lines: five keyboard cycles (PTY 62x38 to 62x15 and back, one SIGWINCH per transition) left 75 of the 100 in `tmux capture-pane` history; with the rows held the PTY stayed 62x38, no SIGWINCH reached the pane and all 100 remained. So `KeyboardHandler` captures `terminal.rows` on the show transition (`app._keyboardHeldRows`) and `getTerminalDimensions()` never reports fewer rows while the keyboard is visible; columns still follow the container, so the #464 width rule is untouched. ⚠️ **Why this is not the regression the COLUMNS ONLY note describes.** There the extra rows came from ANOTHER device's sizing claim, adopted from `ptyGeometry`, and nothing kept the composer in view: an `.xterm-screen` taller than its container with the input line below it and no gesture able to reach it. Here the rows are this device's own keyboard-free rows, held on purpose only while the keyboard is up, and the screen is translated up by `--kb-clip` (`_applyKeyboardClip()`, pure math in `keyboardClipPx()` in constants.js) so the last content row sits at the bottom of the visible box: following live output, the cursor counts only within `KEYBOARD_CLIP_CURSOR_REACH` (2) rows below the last content (a TUI that parks its cursor far below what it drew must not scroll its content away); reading history, the offset follows the scroll position so the top of the scrollback stays reachable. The local-echo overlay is bounded to the visible rows through `setRowLimit()`, which narrows the overlay renderer's existing `totalRows` bound rather than adding a second one, so a long draft grows upward from the last row the user can see. `reconcilePtyGeometry` still adopts columns only: nothing here takes rows from the PTY's report. `test/keyboard-held-rows.test.ts` pins the composer row inside the visible box with the rows held, against a real headless xterm and the shipped `_applyKeyboardClip()`. ⚠️ Holding goes through `getTerminalDimensions()`, never one caller, so the fit, the PTY resize and the capture-geometry comparisons agree; `syncTerminalGeometry()` skips `fitAddon.fit()` while held, so xterm never visits the short size. ⚠️ A shape change (rotation, fold) releases the hold AND arms the viewport settle (`_scheduleViewportSettle()`), which refits and tells the PTY: with the keyboard still up `throttledResize` stands aside and a rotation alone arms nothing, so without it xterm kept the held rows with no clip and the composer sat under the keyboard until it closed. A rotation with no hold arms nothing, as before. ⚠️ ONLY inline renderers qualify (`_keyboardHoldEligible()`): the registry's `capabilities.keyboardHold: 'inline'` (Claude alone; read through `window.__codemanKeyboardHoldModes`, never an id literal), never while `cliMouseTracking` reports Claude's fullscreen mode (it lays out the full height and has not been measured losing lines, so it resizes as before), never remote or docker (their local pane hosts a nested client). A full-height layout (codex: banner at the top, composer pinned to the bottom) cannot fit both ends above the keyboard, which is what the first, unscoped version got wrong. ⚠️ The hold lives on the shared terminal, so `_reconcileKeyboardHold()` releases it whenever the active session stops qualifying (tab switch, a `session:updated`, a reconnect, the setting turned off), and keyboard close releases it too; it never re-holds with the keyboard already up, so a session that becomes eligible mid-keyboard keeps the short rows until the keyboard closes.
|
||||
|
||||
@@ -1339,7 +1375,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`), plan agents (1100), 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 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).
|
||||
|
||||
## Security layers
|
||||
|
||||
@@ -1353,7 +1389,7 @@ Tests: `test/mobile-prompt-composer.test.ts` (in the CI gate, deliberately not u
|
||||
| **CSRF / Origin** | Always-on cross-site Origin guard rejects state-changing requests from foreign origins (covers self-update, session create/input, settings/tunnel toggles). **A missing Origin is allowed** so curl/CLI and Claude Code hooks keep working. The global body parser keeps `text/plain` RAW (no auto-JSON-parse, which had enabled simple-request CSRF); `/api/crash-diag` self-parses. WebSocket upgrade validates Origin+Host (anti-CSWSH) in `ws-routes.ts`. Added in `c669518` (closes 2026-06-09 review CRITICALs) |
|
||||
| **QR Auth** | Single-use 6-char tokens (60s TTL) for tunnel login. See `docs/qr-auth-plan.md` |
|
||||
| **Sessions** | 24h cookie (`codeman_session`), auto-extend, device context audit |
|
||||
| **Rate limit** | 10 failed logins/IP → 429 (15min decay). Multi-user mode instead has two gates checked before scrypt, so past either even a correct password from that IP gets 429: 50/IP (`AUTH_IP_FAILURE_MAX`) and 10 per (username, IP) (`AUTH_FAILURE_MAX`; the same account still logs in from another IP). A 10-per-username bucket (multi-user only) is checked after the verify: 429 to failed guesses from the 10th on, from any IP, never to a correct password. QR has separate limiter |
|
||||
| **Rate limit** | 10 failed logins/IP → 429 (15min decay). Multi-user mode instead has two gates checked before scrypt, so past either even a correct password from that IP gets 429: 50/IP (`AUTH_IP_FAILURE_MAX`) and 10 per (username, IP) (`AUTH_FAILURE_MAX`; the same account still logs in from another IP). A 10-per-username bucket (multi-user only) is checked after the verify: 429 to failed guesses from the 10th on, from any IP, never to a correct password. A request with NO `Authorization` header (or an empty one, which carries no guess either) is never counted and always gets the 401 challenge, since a 429 never re-prompts a browser; a malformed one is counted. QR has separate limiter |
|
||||
| **Hook bypass** | `/api/hook-event` (and `/api/status-telemetry`, the statusLine exporter) skip Basic auth (localhost-only, schema-validated). When auth is active (`CODEMAN_PASSWORD` set), the loopback bypass requires the per-instance `X-Codeman-Hook-Secret` header **unconditionally** — COD-54 introduced it tunnel-gated; COD-91 (PR #127) made it always-on because Codeman can't detect a user's own loopback reverse proxy (own cloudflared/`tailscale serve`/nginx → 127.0.0.1), closing that residual plain-bypass gap. Hook curls cat the secret file at exec time via `$CODEMAN_HOOK_SECRET_FILE` (session env, `config/hook-secret.ts`); a missing/wrong secret gets 401 and rate-limits in a dedicated bucket (never locks out login). Tunnel enable **refuses** without a login (`CODEMAN_PASSWORD` or multi-user mode) unless exposure is acknowledged — via `CODEMAN_ALLOW_UNAUTHENTICATED_TUNNEL=1` / `--allow-unauthenticated-tunnel` (#706; until then the guard took `CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK=1`, COD-55, which `install.sh` writes for every passwordless LAN install, so the bind acknowledgement silently published the tunnel too) **or** the per-request `acknowledgeUnauthTunnel:true` action field (1.1.9). With no login the browser asks BEFORE every enable (welcome link, tunnel panel, an App Settings save that turns it on) through `_confirmTunnelEnable()`, reading `loginConfigured` from `GET /api/tunnel/status`, and on confirm sends that flag; the 403 handler stays the fallback when the status read fails (server logs a loud warning on every passwordless tunnel start; curl/API stay refused without password/env/flag). The flag is an action field, never persisted |
|
||||
| **Env vars** | `CODEMAN_MUX` (managed session), `CODEMAN_API_URL` (auto-set for hooks), `CODEMAN_ALLOWED_HOSTS` (extra Host/Origin allowlist entries for reverse proxies, comma-separated; bare `.suffix` matches subdomains), `CODEMAN_DOCKER_BRIDGE_HOOKS`=1 (opt-in hooks-only listener on the docker bridge gateway so in-container hooks reach a loopback-bound server; bind IP from `CODEMAN_DOCKER_BRIDGE_HOST` or auto-detect) |
|
||||
| **Validation** | Zod schemas, Unicode-aware path allowlist regex, env prefix allowlist (`CLAUDE_CODE_*`/`OPENCODE_*`/`CODEX_*`/`GEMINI_*`/`GOOGLE_*`/`ANTIGRAVITY_*`/`PI_*`) |
|
||||
@@ -1379,6 +1415,8 @@ Target: 20 sessions, 50 agent windows at 60fps. Limits in `src/config/`: termina
|
||||
|
||||
⚠️ Truncation is reported through `onTruncated` rather than silently, with BOTH caps named: a silent depth cap hides a deep tree exactly as effectively as a silent node cap hides a wide one.
|
||||
|
||||
⚠️ **A kill never takes pid 0 or 1** (2026-11-25). A bound limits how MUCH a walk collects, not what it is a walk of: the children of pid 0 are init and everything below it, so `killSession()` with pid 0 signalled every process of the account, which took down every session, tmux itself and the systemd user manager (the machine did not reboot, and with the manager gone the server did not come back until the next login). It was reached by a script that drove the real `killSession()` on an empty pane lookup (`Number('')` is 0), but it needs no script. tmux answers `0` for `#{pane_pid}` of a pane without a process (`split-window ''`; measured on 3.4), `parsePaneRows()` keeps that row, and `reconcileSessions()` at server start writes it to `session.pid`, where the last pane of a session wins. The next close read 0 from tmux, fell back to the record, found 0 there too, and walked it. Reproduced on master with the signals logged instead of sent, inside a PID namespace: "Killing session codeman-feed1234 (PID 0)", "Found 15 child processes to kill". So 0 is an ordinary answer and means "nothing to signal". Three layers, all pinned in `test/kill-pid-guard.test.ts`: `killSession()` decides once (`isSignalablePid()`, an integer above 1) and otherwise leaves the close to `tmux kill-session`; `getChildPidsFresh()` walks nothing for such a root; and `signalProcess()`, the only place in `tmux-manager.ts` that sends a signal, refuses it for the group form as well (`kill(-1)` is every process, `kill(0)` is our own group). `collectDescendants()` itself stays a plain walk. A recorded 0 is deliberately left on the record rather than replaced by the older pid: that pid belongs to a process that may have exited since and been reused.
|
||||
|
||||
## Local packages and build artifacts
|
||||
|
||||
### xterm-zerolag-input is single-source
|
||||
@@ -1417,7 +1455,7 @@ Tests that delete case trees go through `safeRmHomeTree()` (`test/mocks`), which
|
||||
|
||||
**`install.sh`** (repo root) is the public entry point: `curl -fsSL <raw url> | bash` installs Node/tmux/git/build tools if missing, clones to `~/.codeman/app`, builds, and offers a systemd/launchd service. Since installer v2 (2026-09-20) it is **look, ask, work, done**: `preflight_detect` prints what is on the machine, every human step runs BEFORE the build (one consent for all missing packages, ONE sudo prompt kept warm by `sudo_session_start`, the AI CLI menu, the Tailscale login/operator/HTTPS-toggle preflight), then the clone/`npm install`/build/service/serve run unattended behind `run_step` spinners (output in `~/.codeman/install.log`, tail shown on failure), and `print_done_screen` ends on the URL with a terminal QR code (the `qrcode` package Codeman already ships). Design + verification record: `docs/installer-v2-plan.md`.
|
||||
|
||||
The network-access question is 3-way: **Tailscale** (loopback bind + `tailscale serve`, curl-verified end-to-end), **LAN** (0.0.0.0 + password prompt), or **local-only**; it preserves the existing binding on re-runs via `read_existing_binding()`, which also reads back `CODEMAN_BASE_URL`/`CODEMAN_PORT` from the unit, and the flag/env PRESET paths keep an existing password too (`${CODEMAN_PASSWORD:-$EXISTING_PASSWORD}`: `--lan --service` on a password-protected unit used to rewrite it open with the unauthenticated ack, found in review 2026-09-21); `--password`/`--port` flip `RECONFIGURE` so they reach the unit instead of taking the quiet update path.
|
||||
The network-access question is 3-way: **Tailscale** (loopback bind + `tailscale serve`, curl-verified end-to-end), **LAN** (0.0.0.0 + password prompt), or **local-only**; it preserves the existing binding on re-runs via `read_existing_binding()`, which also reads back `CODEMAN_BASE_URL`/`CODEMAN_PORT` and `CODEMAN_MULTIUSER` from the unit (both setup functions write a set `CODEMAN_MULTIUSER=1` back; systemd `Environment=` lines go through `read_systemd_environment()`, which unquotes the way systemd does, so a hand-written `KEY="value"` reads as `value`), and the flag/env PRESET paths keep an existing password too (`${CODEMAN_PASSWORD:-$EXISTING_PASSWORD}`: `--lan --service` on a password-protected unit used to rewrite it open with the unauthenticated ack, found in review 2026-09-21); `--password`/`--port` flip `RECONFIGURE` so they reach the unit instead of taking the quiet update path.
|
||||
|
||||
⚠️ The env a hand-started `codeman web` needs (host, password, ack, base URL, port) is composed in ONE place, `start_command_hint` for the done screen's Start line and `export_bind_env` for main()'s `exec` branch, so the two cannot disagree; `stop_background_helpers` runs right before that `exec`, because exec skips the EXIT trap and the sudo keepalive (keyed on `$$`, which becomes the server's pid) would otherwise refresh the sudo timestamp for the server's whole life. Ctrl+C in the HTTPS-toggle poll is trapped for the poll only and skips Tailscale for the run rather than killing the installer.
|
||||
|
||||
@@ -1549,3 +1587,7 @@ updates `lastSubmitAt` just like any other Enter.
|
||||
- **Files.** Received files come only from Discord's HTTPS hosts into `<tab folder>/.codeman-discord/` (bounded probe, refused if a symlink, self-ignoring). A sent file's real path must lie inside the tab's folder; both the folder and the file are probed with the bounded probe first.
|
||||
- **The whole last message.** A finished turn or an error posts the CLI's whole last message, not the screen: `WebServer.lastResponseFor` is the response viewer's reader (the body of `GET /api/sessions/:id/last-response`, registered on the route context by `registerSessionRoutes`), so the source is the same per-CLI transcript, or the pane split into turns where a CLI keeps none; a dialog and a shell keep the screen tail (its composer row and the status lines under it cut, never a `❯ 1.` option row). The read is bounded to 4 s and any failure or empty read falls back to the screen. It is split into at most 8 posts of 1,900 characters, a cut code fence closed and reopened, and Markdown tables become aligned code blocks (the separator test strips whitespace first: a regex over a run of spaces is quadratic, and the text is steerable by whatever the agent read). The repeat check is keyed on the text plus the turn it came from (the transcript stamp, else the last submit) and is recorded only after the first post succeeds, so a failed post is sent again and a later turn ending on the same words is not dropped. Only some CLIs raise a turn end (`/api/hook-event`: Claude's `stop` and `idle_prompt`, DeepSeek's `stop`), so the others reach this path through errors, a blocked respawn or a crash loop.
|
||||
- **Cost guards.** The alert tail is a function called only once a post will happen (no tmux exec while off), and `discord-notify` is a per-session token bucket (6 a minute, `429 RATE_LIMITED`).
|
||||
|
||||
### Discord reply replay metadata
|
||||
|
||||
`discord-reply-dedupe.json` is a private 0600 data-directory file containing at most 2,048 reply IDs and timestamps retained for seven days. An allowed reply is claimed by message ID before rate-limit or exited-agent checks, attachments, or terminal input. Store failures log once and fall back to memory; they never cost a reply. An unreadable or unsafe file is never overwritten, and reads retry later. Invalid or oversized regular-file ID-only content warns and heals on the next write. Recovery keeps older disk rows before newer outage claims so bounded eviction drops the oldest IDs first. Ambiguous terminal input is never replayed automatically.
|
||||
@@ -8,8 +8,8 @@ This guide documents the browser testing infrastructure, framework comparison re
|
||||
# Run standalone benchmark (recommended - avoids vitest hook issues)
|
||||
npx tsx scripts/browser-comparison.mjs
|
||||
|
||||
# Run existing browser E2E tests
|
||||
npm test -- test/browser-e2e.test.ts
|
||||
# Run the browser suite (Playwright; the files are listed in config/test-suites.ts)
|
||||
npm run test:browser
|
||||
```
|
||||
|
||||
## Framework Comparison Results
|
||||
@@ -67,7 +67,7 @@ We tested three browser automation frameworks against the Codeman web UI:
|
||||
});
|
||||
```
|
||||
|
||||
3. **Use the existing browser-e2e.test.ts pattern** which uses agent-browser CLI commands via `execSync` (avoids async hook issues)
|
||||
3. **Drive agent-browser through its CLI** with `execSync`, as `scripts/browser-comparison.mjs` does (avoids async hook issues)
|
||||
|
||||
## Test File Structure
|
||||
|
||||
@@ -93,10 +93,8 @@ fixed ports 3180-3182.
|
||||
|
||||
| File | Framework | Status |
|
||||
|------|-----------|--------|
|
||||
| `test/browser-e2e.test.ts` | agent-browser | ✅ Working |
|
||||
| `test/browser-playwright.test.ts` | Playwright | ⚠️ Vitest hook issues |
|
||||
| `test/browser-puppeteer.test.ts` | Puppeteer | ⚠️ Vitest hook issues |
|
||||
| `test/browser-agent.test.ts` | agent-browser | ⚠️ Vitest hook issues |
|
||||
| `test/*.browser.test.ts` and the other files in `BROWSER_TEST_GLOBS` (`config/test-suites.ts`) | Playwright | ✅ `npm run test:browser` |
|
||||
| `test/mobile/**` | Playwright | ✅ `npm run test:mobile` |
|
||||
| `scripts/browser-comparison.mjs` | All three | ✅ Working (standalone) |
|
||||
|
||||
## Framework-Specific Patterns
|
||||
|
||||
+11
-1
@@ -298,9 +298,15 @@ 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.wheelForward`, `capabilities.keyboardAccessory` and `capabilities.maxFrameBytes` are **declared but not yet read**. (`shortBadge` was on this list until the CLI management list in Settings started showing it.) They all describe frontend behaviour, and the frontend is deliberately untouched here: `app.js`, `terminal-ui.js` and `styles.css` keep their own hand-authored per-CLI rules, and moving them is its own piece of work verified by a browser/mobile suite the CI gate cannot see.
|
||||
`accent`, `capabilities.echo`, `capabilities.keyboardAccessory` and `capabilities.maxFrameBytes` are **declared but not yet read**. (`shortBadge` was on this list until the CLI management list in Settings started showing it, and `capabilities.wheelForward` until the browser's wheel gate started reading it, see below.) They all describe frontend behaviour, and the frontend is deliberately untouched here: `app.js`, `terminal-ui.js` and `styles.css` keep their own hand-authored per-CLI rules, and moving them is its own piece of work verified by a browser/mobile suite the CI gate cannot see.
|
||||
|
||||
Treat those values as **transcribed, not authoritative** — nothing enforces that `echo.policy` matches `_updateLocalEchoState`'s fallthrough, so re-measure before wiring one up. `accent` is the one exception: it was measured against styles.css on 2026-09-21 (method in the comment above `CLAUDE` in `stock.ts`), though nothing keeps it in step with the CSS either. A field that is both wrong and unread is worse than an absent one, because the next reader trusts it; `test/cli-registry-no-id-branching.test.ts` pins the list so it cannot quietly grow, and wiring one up makes its line there fail, which is the direction you want.
|
||||
|
||||
@@ -308,6 +314,10 @@ Treat those values as **transcribed, not authoritative** — nothing enforces th
|
||||
|
||||
Everything else in the interface is live, including `overlays.remote` / `overlays.docker`, which back `defaultRemoteCommandForMode()` and `defaultDockerCommandForMode()` directly. Those two used to be hardcoded `Record<…CommandMode, string>` tables duplicating the registry with nothing keeping the two in step; `test/location-overlay-commands.test.ts` pins every resulting command as a literal string.
|
||||
|
||||
### Wheel forwarding for a custom full-screen CLI
|
||||
|
||||
`capabilities.wheelForward` reaches the browser as `window.__codemanWheelForward` (id to rule, every CLI whose mode is not `never`, disabled ones included, since disabling a CLI leaves its running sessions open), and `_shouldForwardWheelToApp` in terminal-ui.js reads only that map, so a custom entry gets the same wheel as a stock one under its own id. A full-screen TUI that turns mouse tracking on itself (a wrapper around pi, for example) needs two values in its `clis.json` entry, the ones stock pi carries: `"altScreen": "strip-mux-and-mouse"` (the server strips its mouse DECSETs and publishes `cliMouseTracking`, and a drag selects locally) and `"wheelForward": { "mode": "always" }` (the wheel goes to the CLI as SGR reports while that flag is on). With the custom-entry defaults (`strip-mux-only`, `never`) the DECSETs reach xterm, which handles the wheel only until a tab switch or reload replays the pane without them; from then on the wheel scrolls an empty local buffer. Use `always` rather than `version-gated` for such an entry: a `version-gated` rule forwards only when the session has a `cliVersion`, and the server probes one only for an entry that declares `capabilities.gates` (`cliNeedsVersionProbe` in `session.ts`), so a custom entry with `version-gated` and no gates never forwards, and nothing says why. ⚠️ Saving the entry from the Settings form rebuilds its capabilities from those defaults, so both values have to be set again in the file after an edit there.
|
||||
|
||||
## Consumers outside the server
|
||||
|
||||
Two things need the catalogue but cannot import TypeScript, so `npm run generate:cli-catalog`
|
||||
|
||||
@@ -288,6 +288,39 @@ dsh fences its `/api` behind a browser-trust check on the request authority, and
|
||||
Codeman web tab reaches it through Codeman's own origin via the webview proxy, not
|
||||
directly. Without it the page renders and every API call fails.
|
||||
|
||||
Since dsh's browser-auth gate, the index is not public either: boot prints
|
||||
`dsh web: http://127.0.0.1:<port>/?token=<one-time token>` and only a request
|
||||
carrying that token is answered with the `dsh-auth-*` cookie that authorizes
|
||||
everything after it. The saved tab deliberately keeps the clean URL, so the
|
||||
browser can never present that token, and the tab used to open on dsh's 401 page.
|
||||
`src/deepseek-web-server.ts` now reads the token out of the captured boot output,
|
||||
trades it for the cookie once at startup, and `webview-routes.ts` presents that
|
||||
cookie on both the HTTP and WebSocket legs — scoped to the exact loopback
|
||||
authority it was minted for, so a repointed or stale tab cannot carry it
|
||||
elsewhere. The reader scans every `dsh web:` line (dsh prints diagnostics such as
|
||||
`dsh web: loading profiles` under the same prefix before the banner) and only
|
||||
complete lines, so a banner split across two output chunks is waited for rather
|
||||
than parsed truncated. Before the token URL is fetched it must name `127.0.0.1`
|
||||
on the port the supervisor just spawned, so a banner cannot aim the server-side
|
||||
request at another host or local service. A dsh without the gate prints a
|
||||
token-less banner and keeps working unchanged. If a token is printed but the
|
||||
exchange still fails, the server keeps running (its page serves, just 401) and is
|
||||
marked unusable for reuse: the next start request stops and respawns it, which is
|
||||
the "restart `dsh web`" the warning asks the user to perform.
|
||||
|
||||
The cookie is also bound to a person, not to a URL. `managed` is accepted from the
|
||||
client on `POST/PATCH /api/webviews` and `GET /api/deepseek/web` publishes the live
|
||||
port, so a saved record pointing at that port is not an entitlement by itself: the
|
||||
proxy presents the cookie only when the tab's owner holds the same
|
||||
privileged-commands grant `POST /api/deepseek/web` requires, and in multi-user mode
|
||||
only to the owner whose request started that process. A different owner's start
|
||||
request restarts the server rather than reusing a cookie that is not theirs, which
|
||||
is why the shared instance is effectively single-user at a time. On a trusted
|
||||
managed tab the cookie is sent ahead of whatever cookies dsh itself set in the
|
||||
browser, rather than replacing them; leading matters because a `Cookie` header can
|
||||
name the same cookie twice and the first value is the one the dashboard parses, so
|
||||
a stale browser copy must not shadow the one the running process minted.
|
||||
|
||||
## 7. Docker and remote cases
|
||||
|
||||
Docker cases work: the agent image installs `dsh` and bootstraps a `dsh-tui`
|
||||
|
||||
@@ -135,3 +135,9 @@ The text explains `codeman notify "message" --urgent`. `codeman` is on the PATH
|
||||
| Posts arrive but replies do nothing | Message Content Intent is off, or your user ID is not in the allowlist |
|
||||
| Thread is not deleted | The bot lacks Manage Threads on the parent channel |
|
||||
| Nothing arrives on the phone | Check the Discord app's notification setting for the server |
|
||||
|
||||
## Reply replay protection
|
||||
|
||||
The bridge remembers up to 2,048 recent Discord reply IDs for seven days in the private `discord-reply-dedupe.json` metadata file. It claims an allowed reply before rate-limit or exited-agent checks, downloading attachments, or typing into its session, so a gateway replay normally cannot type it twice, including after a restart. The file contains IDs and timestamps only, with mode 0600.
|
||||
|
||||
This is best-effort replay protection, not an exactly-once guarantee. A full disk, unreadable file, or invalid metadata logs one content-free warning and falls back to in-memory checks. Invalid or oversized regular-file ID metadata is replaced on the next write. Files that could not be read are left untouched. Reads and writes retry on later replies; a restart during a metadata outage can lose those checks. At capacity the oldest entries are evicted, so capacity never blocks new replies. Notifications retain their existing delivery and retry behavior; this store never suppresses an outbound alert or replays terminal input.
|
||||
@@ -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).
|
||||
+21
-11
@@ -20,8 +20,8 @@ in [architecture-invariants.md](architecture-invariants.md#local-model-install).
|
||||
|
||||
The window offers the best model of the catalogue (`src/config/local-model-catalog.ts`) that
|
||||
fits this Mac's memory at a context a coding agent can work with, and under it every other
|
||||
model of the catalogue that fits (ten models today: a 16 GB Mac sees one of them, a 512 GB
|
||||
Mac all ten). What the catalogue answers today, before the runtime measured anything (the
|
||||
model of the catalogue that fits (eleven models today: a 16 GB Mac sees one of them, a 512 GB
|
||||
Mac all eleven). What the catalogue answers today, before the runtime measured anything (the
|
||||
budget is then an estimate: 2/3 of the memory below 36 GB, 3/4 from 36 GB, less 1 GiB, and
|
||||
never more than the memory less 6, 8 or 12 GiB for macOS, Codeman, a browser and the agent):
|
||||
|
||||
@@ -31,9 +31,9 @@ never more than the memory less 6, 8 or 12 GiB for macOS, Codeman, a browser and
|
||||
| 16 GB | 10.4 GB | A small model (`limited`): Ornith 1.0 9B at 65,536 tokens, 9.3 GB, tight (90%). Its build has no vision projector, which makes it 0.9 GB smaller than the other two 9B builds: MiMo V2.6 9B needs 10.2 GB there, 98.7% of the budget, just past the 98% a tight fit may reach. Once the runtime measures what a 16 GB Mac mini measured (10.7 GB), all three fit and MiMo is the pick. No 9B was run on such a Mac by us: only a run settles it |
|
||||
| 18 GB | 11.8 GB | A small model (`limited`): MiMo V2.6 9B at 131,072 tokens, 11.4 GB, tight. Ornith 1.0 9B (10.5 GB) and Qwen3.5 9B are the alternatives |
|
||||
| 24 GB | 16.1 GB | The same, with room. On a base M2 or M3 (100 GB/s) it computes to 9.3 tokens per second: slow |
|
||||
| 32 GB | 21.8 GB | No longer a small-model Mac: Muse Glimmer 30B fits at 65,536 tokens (21.2 GB, 97%, tight). It is a dense model. On an M1 Max or M2 Max it computes to 11.8 tokens per second and is the pick; on a base or Pro chip it computes to under 6 and is listed as slow, and the pick stays MiMo V2.6 9B at 131,072 tokens with the note that it is a small model. North Mini Code 1.0 needs 23.2 GB at 65,536 tokens; once the runtime measures about 3/4 of the memory, as it did on a 16 and a 48 GB Mac, the Mac gets it at 131,072 tokens, or Qwen3.8 27B at 65,536 tokens on a Max chip |
|
||||
| 32 GB | 21.8 GB | No longer a small-model Mac: Muse Glimmer 30B fits at 65,536 tokens (21.2 GB, 97%, tight). It is a dense model. On an M1 Max or M2 Max it computes to 11.8 tokens per second and is the pick; on a base or Pro chip it computes to under 6 and is listed as slow, and the pick stays MiMo V2.6 9B at 131,072 tokens with the note that it is a small model. North Mini Code 1.0 needs 23.2 GB at 65,536 tokens; once the runtime measures about 3/4 of the memory, as it did on a 16 and a 48 GB Mac, the Mac gets it at 131,072 tokens, or Qwen3.8 27B at 65,536 tokens on a Max chip. Run once on a Mac (an M5 Pro with 48 GB, 2026-11-12): this GGUF build wrote 15 tokens per second, and an OpenCode worker given a one-line task showed no answer after 7 minutes. Its MLX build, which finished an OpenCode turn on a one-line prompt in 45 seconds, needs 36.1 GB and is offered from 48 GB |
|
||||
| 36 GB | 27.9 GB | Qwen3.8 27B at 131,072 tokens on an M4 or M5 Max (27.0 GB, 97%); on a slower chip, where the dense 27B computes to under 10 tokens per second, Qwen3.6 35B-A3B as a GGUF build (27.1 GB, 97%). Both tight. Muse Glimmer 30B at 131,072 tokens (21.6 GB, 78%) is the alternative with room to spare |
|
||||
| 48 GB | 37.6 GB | Qwen3.6 35B-A3B (MLX) at 131,072 tokens: the pair we tested, "Recommended" on an Apple M5 Pro with 48 GB. On a Max chip Qwen3.8 27B at 262,144 tokens (32.1 GB, tight). The test was a short task: in a long session MLX may keep up to 8 GiB more, which brings this pair to the edge of the budget, and past it while a long prompt is processed |
|
||||
| 48 GB | 37.6 GB | Qwen3.6 35B-A3B (MLX) at 131,072 tokens: the pair we tested, "Recommended" on an Apple M5 Pro with 48 GB. On a Max chip Qwen3.8 27B at 262,144 tokens (32.1 GB, tight). A session of many prompts on that Mac (a 95,000-token prompt, then twelve separate ones of 15,000 tokens, measured on 2026-11-12) ended at 33.4 GB of the 40.2 GB its runtime measures, still growing by 0.5 GiB a prompt: MLX may keep up to 8 GiB of earlier prompts, which brings this pair to the edge of the budget. Muse Glimmer 30B as its MLX build is offered here too, at 65,536 tokens (36.1 GB, tight) |
|
||||
| 64 GB | 50.5 GB | Qwen3.8 27B at 262,144 tokens on a Max chip; Qwen3.6 35B-A3B (MLX) on a Pro chip |
|
||||
| 96 GB | 76.2 GB | Qwen3.8 27B at 262,144 tokens; on an M3 Max, Qwen3.6 35B-A3B (MLX) |
|
||||
| 128 GB | 102 GB | Ornith 1.5 122B-A10B (MLX) at 131,072 tokens, 97.4 GB, tight |
|
||||
@@ -73,7 +73,10 @@ names its runner (`runner`) and its figures follow that runner's rule:
|
||||
- **MLX** grows its cache with the tokens actually used, keeps snapshots of the recurrent
|
||||
state, and may keep up to 8 GiB of snapshots of earlier prompts, which no setting bounds. A
|
||||
Mac always takes the MLX build of a tag that has one. Below 48 GB that 8 GiB does not fit
|
||||
beside a useful model, so the catalogue lists GGUF builds there.
|
||||
beside a useful model, so the catalogue lists GGUF builds there. For Muse Glimmer the MLX
|
||||
runner was measured holding 38,000 to 45,000 bytes per token, against the 7,072 its GGUF
|
||||
build computes to: close to every layer's cache at full length, so it evidently does not
|
||||
trim the sliding-window layers the way llama.cpp does.
|
||||
|
||||
Where every figure comes from:
|
||||
|
||||
@@ -84,6 +87,7 @@ Where every figure comes from:
|
||||
| `mimo-v2.6:9b-q4_k_m` | llama.cpp | the same (a fine-tune of Qwen3.5-9B) | 9.3: the same architecture and size |
|
||||
| `north-mini-code-1.0:q4_k_m` | llama.cpp | computed from its config | 13.6: the 35B-A3B's, the same 3 billion active parameters |
|
||||
| `muse-glimmer:30b-q4_k_m` | llama.cpp | computed from its config: 13 full-attention and 39 sliding-window layers | 2.95: the dense 27B's, whose weights are the same size |
|
||||
| `muse-glimmer:30b-mlx` | MLX | **measured** on an Apple M5 Pro with 48 GB, the 8 GiB of prefix snapshots counted | 5.4: measured beside the 35B-A3B on MLX, 0.32 of its 16.9 |
|
||||
| `qwen3.6:35b-a3b-mtp-q4_k_m` | llama.cpp | computed from the Qwen3.6-35B-A3B config, prediction layer included | 13.6: a published run on an M1 Max |
|
||||
| `qwen3.6:35b-a3b` | MLX | **measured** on an Apple M5 Pro with 48 GB | 16.9: a published run; 67.7 measured on the tested Mac |
|
||||
| `qwen3.8:27b-q8_0` | llama.cpp | computed from the Qwen3.8-27B config, prediction layer included | 1.7: the row below scaled by file size |
|
||||
@@ -91,12 +95,18 @@ Where every figure comes from:
|
||||
| `ornith-1.5:122b` | MLX | computed from the Qwen3.5-122B-A10B config, scaled by the measured MLX row, + 8 GiB | 5.0: the 35B-A3B's, x 3/10 active parameters |
|
||||
|
||||
Sizes are what the registry serves a Mac for each tag (every layer plus the config), read on
|
||||
2026-11-08 (the Ornith 1.0 and Muse Glimmer rows on 2026-11-10). Only one row was ever run on
|
||||
a Mac, so every other answer in the table above is a calculation. For a llama.cpp build the check after the download catches a load that was
|
||||
2026-11-08 (the Ornith 1.0 and Muse Glimmer rows on 2026-11-10, Muse Glimmer's MLX build on
|
||||
2026-11-12). Two rows carry memory figures measured on a Mac, both on an Apple M5 Pro with
|
||||
48 GB; every other answer in the table above is a calculation. Three more rows were installed
|
||||
and loaded on that Mac on 2026-11-12 (Qwen3.5 9B, Ornith 1.0 9B and Muse Glimmer as a GGUF
|
||||
build): that checked their download size and that they load on the GPU, not their memory
|
||||
figures. For a llama.cpp build the check after the download catches a load that was
|
||||
judged too kindly, but not what grows after it in host memory (the checkpoints and the prompt
|
||||
cache, which are counted, not checked); for an MLX build it catches neither (see "The check"
|
||||
below). The measured row's figures come from single long prompts, not a session of many
|
||||
requests, in which MLX may keep up to 8 GiB more. The catalogue header lists the models left
|
||||
below). The 35B-A3B's figures come from single long prompts, not a session of many
|
||||
requests, in which MLX may keep up to 8 GiB more: such a session was measured on it later
|
||||
(the 48 GB row above) and its figures were left as they are. Muse Glimmer's MLX row counts
|
||||
the 8 GiB. The catalogue header lists the models left
|
||||
out on purpose (no evidence of working tool calls, a restrictive licence, a known bug, a
|
||||
build that needs a newer runtime than the pinned one) and why. The strongest of those today
|
||||
is Ripple 65B Preview, published on 2026-11-09: every build of it requires Ollama 0.40.16,
|
||||
@@ -484,8 +494,8 @@ or `python3`.
|
||||
a session uses the model: close those sessions first.
|
||||
- **The runtime does not enforce the context length.** A prompt longer than the context was
|
||||
accepted in testing. Do not rely on the runtime to stop one.
|
||||
- **Most memory figures are calculated, not measured.** One model was run on one Mac; the
|
||||
others are computed from their architecture, and the runtime settings they assume (an 8-bit
|
||||
- **Most memory figures are calculated, not measured.** Two models were measured on one Mac;
|
||||
the others are computed from their architecture, and the runtime settings they assume (an 8-bit
|
||||
K/V cache, flash attention, a 1 GiB prompt cache) were read in its source, not yet observed
|
||||
on a Mac. "Recommended" appears only for the pair we ran, on the Mac we ran it on.
|
||||
- **A tool call that quotes a tool call can be cut off.** The pinned runtime reads the tool
|
||||
|
||||
@@ -363,5 +363,5 @@ The Orchestrator can optionally USE the Ralph Loop internally for phase executio
|
||||
| `src/types/orchestrator.ts` | Type definitions |
|
||||
| `src/prompts/orchestrator.ts` | Prompt templates |
|
||||
| `src/web/routes/orchestrator-routes.ts` | API endpoints |
|
||||
| `src/web/public/orchestrator-ui.js` | Frontend panel |
|
||||
| `src/web/public/orchestrator-panel.js` | Frontend panel |
|
||||
| `src/web/ports/orchestrator-port.ts` | Port interface |
|
||||
@@ -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.
|
||||
|
||||
@@ -837,8 +837,6 @@ POST /api/sessions/:id/auto-clear
|
||||
- `src/ralph-tracker.ts` - Core detection engine
|
||||
- `src/ralph-loop.ts` - Task orchestration
|
||||
- `src/respawn-controller.ts` - Session cycling
|
||||
- `src/spawn-orchestrator.ts` - Autonomous agent lifecycle (uses RalphTracker for completion)
|
||||
- `src/spawn-detector.ts` - Detects `<spawn1337>` tags in terminal output
|
||||
- `src/types.ts` - Type definitions
|
||||
|
||||
---
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -79,5 +79,5 @@ Uses temp file for prompt to avoid E2BIG errors with large terminal buffers.
|
||||
|
||||
- `test/respawn-scenarios.md` - Comprehensive test scenarios for edge cases
|
||||
- `test/respawn-test-plan.md` - Test environment architecture and strategies
|
||||
- `test/respawn-test-utils.ts` - Mock utilities (MockSession, MockAiIdleChecker, MockAiPlanChecker)
|
||||
- `test/mocks/mock-session.ts` - `MockSession`, the session double the respawn tests drive
|
||||
- `test/respawn-analysis.md` - Code coverage analysis and identified issues
|
||||
@@ -138,9 +138,18 @@ loopback bind matters. The auth pipeline (`src/web/middleware/auth.ts`,
|
||||
allow.
|
||||
3. **HTTP Basic** check — correct credentials short‑circuit to allow and clear
|
||||
that IP's failure counter.
|
||||
4. **Rate‑limit gate** — if neither cookie nor credentials passed and the IP is
|
||||
locked out, return `429` with a `Retry-After` header.
|
||||
5. Otherwise return `401`, incrementing the IP's failure counter.
|
||||
4. **No `Authorization` header** — return `401` with the `WWW-Authenticate`
|
||||
challenge, **without counting it** and even while the IP is locked out (both
|
||||
modes; in multi-user mode this comes before the pre-verify gates and the
|
||||
verify, which a missing header could never pass). Such a request is no guess
|
||||
and runs no password check. Counting it let an open tab's background requests
|
||||
after a restart (cookie sessions live in memory) fill the bucket in seconds,
|
||||
and a `429` carries no challenge, so the browser never showed its login dialog
|
||||
again.
|
||||
5. **Rate‑limit gate** — if the credentials did not pass and the IP is locked
|
||||
out, return `429` with a `Retry-After` header.
|
||||
6. Otherwise (wrong credentials, or an `Authorization` header that is not valid
|
||||
Basic) return `401`, incrementing the IP's failure counter.
|
||||
|
||||
### Session cookies
|
||||
|
||||
@@ -152,9 +161,10 @@ by presence in a server‑side map, so they cannot be forged offline.
|
||||
### Rate limiting / lockout recovery
|
||||
|
||||
Failed logins are tracked **per IP**: 10 failures (`AUTH_FAILURE_MAX`) → `429`, with a 15‑minute decay. Multi-user mode replaces that with three buckets, all with the same decay: a wider per-IP **pre-gate** of 50 failures (`AUTH_IP_FAILURE_MAX`), checked before the scrypt verify, which bounds scrypt cost from one source and tolerates many users behind one egress IP; a **per-(username, IP)** gate of 10 failures (`AUTH_FAILURE_MAX`), also checked before the verify, which is what caps verified guesses against one account from one source; and a **per-username** bucket, checked after the verify, that answers `429` to failed guesses from the 10th on, from any IP (the count is incremented before the check). The last two exist in multi-user mode only. So the wider per-IP cap does not widen guessing against any one account from one IP, and other IPs cannot lock an account out.
|
||||
The QR path has its own separate limiter.
|
||||
A request with no `Authorization` header, or an empty one, is never counted (step 4), so an open
|
||||
tab after a restart cannot fill any bucket. The QR path has its own separate limiter.
|
||||
|
||||
The lockout check sits **after** the cookie/credential checks (step 4, not first).
|
||||
The lockout check sits **after** the cookie/credential checks (step 5, not first).
|
||||
This is deliberate: a user with a **valid cookie or correct password recovers
|
||||
immediately** even while an attacker is hammering the same IP — important because
|
||||
all traffic through a tunnel shares one source IP (loopback). Wrong credentials
|
||||
|
||||
+25
@@ -18,6 +18,7 @@ tmux rather than proxying bytes.
|
||||
codeman tui # the dashboard
|
||||
codeman tui --list # print the numbered session list and exit
|
||||
codeman tui 2 # attach straight to session 2 of that list
|
||||
codeman tui api-docs # attach straight to the live session named api-docs
|
||||
```
|
||||
|
||||
The two fast paths are the scriptable ones.
|
||||
@@ -84,6 +85,15 @@ The same world through `--list`:
|
||||
The numbers are the same on both surfaces, so `codeman tui --list` then
|
||||
`codeman tui 4` is one thought.
|
||||
|
||||
A number moves as sessions change state; a name does not. `codeman tui <name>`
|
||||
attaches to the live session whose name is exactly `<name>` (case-sensitive,
|
||||
never a prefix, never the folder), so the same line gets you back into the same
|
||||
session from any folder or a fresh SSH login. Digits only always mean a list
|
||||
number. Session names are not unique in Codeman, so when two live sessions share
|
||||
the name it refuses and prints their numbers instead of guessing; a name only a
|
||||
RECENT row carries says the session has finished. Both refusals are printed
|
||||
before the terminal check, so a script can tell them apart without a TTY.
|
||||
|
||||
## The four groups
|
||||
|
||||
Groups are always in this order, and a session is in exactly one of them:
|
||||
@@ -206,6 +216,21 @@ exactly as it was on detach, along with each window's size. Every session the st
|
||||
can switch to is dressed and sized the same way, so switching is instant and lands
|
||||
in a pane that already fills your terminal.
|
||||
|
||||
The window follows whoever used it last, as plain tmux does. If a browser tab (a
|
||||
phone, say) resizes the session while you are attached, the window takes that tab's
|
||||
size, and your terminal shows a smaller pane. Type, paste or resize your terminal and
|
||||
the window fills it again; type in the tab, or press its Redraw, and the tab gets it
|
||||
back. A tab that only opens the session at the size it already had changes nothing.
|
||||
The TUI does this with one hook on each session it dressed (`client-active[91]`) and
|
||||
two session options naming your terminal and the TUI process (`@codeman-tui-follow`,
|
||||
`@codeman-tui-follow-pid`), and removes all three on detach. It sets nothing on a
|
||||
session where you have a hook of your own at that index, or anywhere while you have
|
||||
a global `client-active` hook, which a session hook would hide. A TUI that was killed
|
||||
while attached (a closed window, a dropped SSH) leaves them behind; the next
|
||||
`codeman tui`, including `codeman tui <n>`, removes them before it attaches. tmux
|
||||
older than 3.3 has no `client-active` hook, so there the pane stays at the browser's
|
||||
size until you detach and attach again.
|
||||
|
||||
Detaching leaves the agent running; typing `exit` or pressing `Ctrl+D` would end it,
|
||||
which is the difference the bar exists to make obvious. If an agent does exit, its
|
||||
pane stays as a corpse: the TUI refuses to attach to a dead pane and offers `r` to
|
||||
|
||||
+24
-2
@@ -144,9 +144,21 @@ per-device (`localStorage`), since that is workspace layout rather than config.
|
||||
Worth knowing, because it is where this feature does its least obvious work. Three
|
||||
layers cooperate so a dashboard talking to its own backend just works:
|
||||
|
||||
1. `<base href>` handles relative URLs in the markup.
|
||||
1. `<base href>` handles relative URLs in the markup. A page that ships its own
|
||||
**relative** base (`<base href="./">`, what a Vite build emits) has it resolved
|
||||
against the document's own directory inside the proxy prefix first, so a
|
||||
document at `/webview/<cap>/app/page.html` gets `/webview/<cap>/app/` rather
|
||||
than the proxy root: the page's URL is masked a few paragraphs below, a base is
|
||||
resolved against that URL, so `./` would otherwise point at Codeman's root and
|
||||
404 every module script behind an otherwise-painted page.
|
||||
2. Attribute rewriting handles root-absolute `src`/`href`/`action` in the page the
|
||||
proxy serves.
|
||||
proxy serves — and root-absolute dynamic `import("/...")` specifiers inside
|
||||
`<script>` bodies. The import is the one URL no other layer can reach: `<base>`
|
||||
does not apply to a `/`-rooted specifier and it is not a `fetch()`. SvelteKit's
|
||||
inline bootstrap is exactly this shape; without the rewrite the module loads
|
||||
from Codeman's root, 404s, and the app sits on its own loading spinner forever.
|
||||
Visible text is left alone: a `<pre>import("/x")</pre>` example is not a
|
||||
loader and is not rewritten.
|
||||
3. A small injected script rebases URLs built at **runtime**, which the first two
|
||||
cannot see: `fetch('/api/data')` and `new WebSocket('/live')`, but equally
|
||||
`card.innerHTML = '<img src="/api/hero">'`, `img.src = '/api/slide'`, and
|
||||
@@ -190,6 +202,16 @@ then every API call fails, which looks like the dashboard being broken.
|
||||
EventSource, normal markup, the DOM sinks a page uses to build markup at runtime,
|
||||
and `url()` inside stylesheets. Something that constructs requests by an unusual
|
||||
route can still slip through. Symptom: the page renders but a panel stays empty.
|
||||
- **Root-absolute URLs the proxy never sees.** Only the HTML is rewritten, and only
|
||||
literal `/`-rooted specifiers in it. Still escape: an `import()` built at runtime
|
||||
(`import('/' + name)`), an import written inside an external `.js`, a static
|
||||
`import x from "/x"` in an inline script, `navigator.serviceWorker.register("/sw.js")`,
|
||||
and `url(/img.png)` inside an external stylesheet. They cannot be relayed either —
|
||||
the masked frame's `Referer` carries no capability — so the failure is quiet: a
|
||||
blank page, or a spinner that never resolves. Codeman now logs
|
||||
`[Webview] <path> escaped the proxy` (once per path per five minutes) when such a
|
||||
request reaches its 404, which is the fastest way to tell this class apart from a
|
||||
dashboard that is genuinely broken.
|
||||
- **A root-absolute `url()` inside an inline `<style>` is not rescued.** Masking the
|
||||
page's URL (layer 5) trades away the `Referer` safety net of layer 4 for
|
||||
requests the shim cannot see, and only HTML is rewritten server-side. An
|
||||
|
||||
@@ -110,9 +110,10 @@ The defaults you will care about, all under **App Settings**:
|
||||
**Separate Claude accounts per session.** Set `CLAUDE_CONFIG_DIR` in a session's environment
|
||||
overrides to point it at a different Claude config directory, which is how you run one
|
||||
session on a client's subscription and another on your own. One caveat: a relocated config
|
||||
directory writes transcripts outside `~/.claude/projects`, which blinds the response viewer,
|
||||
subagent windows, ultracode panel, and Read My Mind for that session. Symlink `projects`
|
||||
back into the shared tree to keep them working:
|
||||
directory writes transcripts outside `~/.claude/projects`, which blinds subagent windows,
|
||||
the ultracode panel and Read My Mind for that session (the response viewer and the Edit
|
||||
history panel read the relocated directory). Symlink `projects` back into the shared tree
|
||||
to keep them working:
|
||||
|
||||
```bash
|
||||
ln -s ~/.claude/projects <configDir>/projects
|
||||
|
||||
@@ -67,6 +67,22 @@ below the terminal that owns composition, then delivers the composed text to the
|
||||
Ctrl- and Alt-modified navigation keys typed through it reach the CLI as the modified
|
||||
sequences, so word jumps and history keys keep working.
|
||||
|
||||
On a phone, **Input Field: Send on Enter** (beside CJK input) turns that field into a chat box:
|
||||
typed text stays in it until Enter, so you can scroll the terminal back to a question and edit
|
||||
your answer before sending. With a hardware keyboard, Shift+Enter adds a line (a phone's on-screen
|
||||
keyboard has no Shift+Enter, and the extended bar's newline key goes to the CLI, not the field),
|
||||
Esc clears the field, and autocorrect is on. Enter always goes out as its own write, a moment
|
||||
after the text, to the session the answer was typed for: a single character is typed, so CLI menus
|
||||
that take a digit still work, and anything longer goes like the prompt composer's Send, as one
|
||||
paste. The one exception is a lone digit while a permission or question dialog is waiting: the
|
||||
digit answers the dialog by itself, so no Enter follows it, which would otherwise confirm whatever
|
||||
the CLI shows next. The toolbar's Enter button sends the field too. With the keyboard bar's
|
||||
one-shot Ctrl armed, the next key you type goes out as a control key (Ctrl, then `c` is Ctrl+C)
|
||||
instead of being held. With a hardware keyboard, Ctrl shortcuts (undo, select all, copy) act on
|
||||
the field while it holds a draft and reach the CLI only when it is empty. With the keyboard down
|
||||
the field stays one line tall. A draft stays with its session: switching tabs and coming back
|
||||
brings it back.
|
||||
|
||||
## Voice dictation
|
||||
|
||||
`Ctrl+Shift+V`, or the microphone button. There are three providers and the default is
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -190,6 +190,41 @@ and is not one.
|
||||
Also make sure the proxy forwards WebSocket upgrades. The terminal is a WebSocket, and the
|
||||
upgrade runs the same Host and Origin checks, closing with code `4003` on failure.
|
||||
|
||||
### Persist the allowlist for a systemd user service
|
||||
|
||||
On Linux, add the hostname to the service environment with a systemd drop-in. For the
|
||||
default service, run:
|
||||
|
||||
```bash
|
||||
systemctl --user edit codeman-web.service
|
||||
```
|
||||
|
||||
Add this to the editable portion:
|
||||
|
||||
```ini
|
||||
[Service]
|
||||
Environment="CODEMAN_ALLOWED_HOSTS=codeman.example.com"
|
||||
```
|
||||
|
||||
If the service already has allowed hosts, include them in the same comma-separated
|
||||
value. If you already set the variable through an `EnvironmentFile=`, update that
|
||||
file. For a named instance the unit is `codeman-web-<instance>.service` (for example
|
||||
`codeman-web-beta.service`; `CODEMAN_INSTANCE=beta codeman service status` prints it).
|
||||
Use that name in both commands.
|
||||
|
||||
Save the drop-in and restart Codeman:
|
||||
|
||||
```bash
|
||||
systemctl --user restart codeman-web.service
|
||||
```
|
||||
|
||||
Re-running the installer or `codeman service install` rewrites `codeman-web.service`
|
||||
itself and does not carry `CODEMAN_ALLOWED_HOSTS` over, so keep the setting in the
|
||||
drop-in (`~/.config/systemd/user/codeman-web.service.d/override.conf`), not in the unit
|
||||
file. Installs, updates and `install.sh uninstall` leave that folder alone, so delete it
|
||||
by hand if you remove Codeman. Open the proxy URL and attach to a terminal to check both
|
||||
the page and the WebSocket connection.
|
||||
|
||||
### Mounting under a sub-path
|
||||
|
||||
By default Codeman assumes it is served at the origin root (`/`). To mount it under a
|
||||
@@ -236,7 +271,8 @@ Notes and current limits:
|
||||
The first request prompts for HTTP Basic credentials. On success the server issues an opaque
|
||||
`codeman_session` cookie (24 hour lifetime, extended on activity, validated server-side so
|
||||
it cannot be forged offline). Ten failed attempts from one IP produce a `429` with a 15
|
||||
minute decay.
|
||||
minute decay. A request with no credentials, such as an open tab whose cookie a restart
|
||||
invalidated, is never counted and always gets the login prompt.
|
||||
|
||||
A valid cookie or a correct password recovers immediately even while an attacker is hammering
|
||||
the same IP, which matters because all tunnel traffic arrives from one loopback address.
|
||||
@@ -255,6 +291,7 @@ works well in SSH clients like Termius or Blink:
|
||||
```bash
|
||||
codeman tui # the dashboard
|
||||
codeman tui 2 # attach straight to session 2
|
||||
codeman tui api-docs # attach to the live session named api-docs
|
||||
codeman tui --list # numbered list, then exit
|
||||
```
|
||||
|
||||
|
||||
@@ -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. |
|
||||
|
||||
|
||||
@@ -48,8 +48,10 @@ non-updatable. See [Running As A Service](Running-As-A-Service).
|
||||
| Local Echo | On for touch devices | Paints keystrokes locally and flushes on Enter. See [Input And Voice](Input-And-Voice). |
|
||||
| Keep Size Under Keyboard | On | For local Claude sessions, the on-screen keyboard no longer resizes the session: the terminal keeps its rows and the view scrolls so the prompt sits just above the keyboard. Resizing made Claude reprint its screen and drop transcript lines from history. Codex, Claude's fullscreen mode, remote and Docker sessions resize as before. See [Mobile Guide](Mobile-Guide). |
|
||||
| CJK Input | Off | IME composition through a dedicated text field. |
|
||||
| Input Field: Send on Enter | Off | With CJK Input on, typed text stays in the pinned field until Enter instead of streaming to the CLI, so on a phone you can scroll the terminal and edit an answer first. With a hardware keyboard, Shift+Enter adds a line (a phone's on-screen keyboard has none). Esc clears, autocorrect is on. |
|
||||
| Extended Keyboard Bar | Per device | Which accessory bar phones get. Shell sessions override it while they are active. |
|
||||
| Wheel Scrolls Local History | Off | Keeps the wheel on the local buffer instead of forwarding it to the CLI. Fullscreen pi leaves that buffer empty and has no paging fallback, so with this on the wheel does nothing there. |
|
||||
| History Reload Button | On (per device) | Offers **Reload history** in the history banner while you are scrolled up in a non-shell session that has had live output since its last full capture; a tap re-pulls the full tmux history and keeps your reading position. |
|
||||
| Auto Copy Selection | Off | Copies highlighted terminal text to the clipboard the moment you finish selecting it. Ctrl+C still copies on demand. |
|
||||
| Trim The Pane Margin On Copy | On | Takes the left margin a full-screen agent CLI paints down its own edge off a copy, so the text pastes flush. Each CLI declares its own width, and the strip never exceeds the indent every selected line shares, so nesting is kept. Claude Code and Codex declare a margin; a shell does not. |
|
||||
| Normal / Bold font weight | xterm defaults | Per device, each slot from 100 to 900. The bundled JetBrains Mono renders every step, so a lighter normal weight makes Claude's bold headings stand out. Applies live to the terminal, both echo overlays and open team panes. |
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -108,9 +108,9 @@ are not reading.
|
||||
|
||||
- **A session pointed at a relocated Claude config directory goes blind here.** Transcripts
|
||||
written outside `~/.claude/projects` are invisible to the watchers, so subagent windows,
|
||||
the ultracode panel, the response viewer, and Read My Mind all stop working for that
|
||||
session. Symlink `projects` back into the shared tree to fix it. See
|
||||
[Agent CLIs](Agent-CLIs).
|
||||
the ultracode panel and Read My Mind stop working for that session. Symlink `projects`
|
||||
back into the shared tree to fix it. The response viewer reads the session's own
|
||||
directory and keeps working. See [Agent CLIs](Agent-CLIs).
|
||||
- **Closing a window does not cancel the agent.** Nothing on this page controls agents; it
|
||||
observes them.
|
||||
- **Windows are opt-in for ultracode, automatic for subagents.**
|
||||
|
||||
@@ -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,
|
||||
|
||||
+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
-11
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "aicodeman",
|
||||
"version": "1.51.0",
|
||||
"version": "1.52.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "aicodeman",
|
||||
"version": "1.51.0",
|
||||
"version": "1.52.0",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
@@ -52,7 +52,6 @@
|
||||
"@types/pngjs": "^6.0.5",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/uuid": "^10.0.0",
|
||||
"@types/web-push": "^3.6.4",
|
||||
"@types/ws": "^8.18.1",
|
||||
"@vitest/coverage-v8": "^4.1.8",
|
||||
@@ -3966,13 +3965,6 @@
|
||||
"csstype": "^3.2.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/uuid": {
|
||||
"version": "10.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz",
|
||||
"integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/web-push": {
|
||||
"version": "3.6.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/web-push/-/web-push-3.6.4.tgz",
|
||||
@@ -13371,7 +13363,7 @@
|
||||
}
|
||||
},
|
||||
"packages/xterm-zerolag-input": {
|
||||
"version": "0.4.2",
|
||||
"version": "0.4.3",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@xterm/headless": "^6.0.0",
|
||||
|
||||
+3
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "aicodeman",
|
||||
"version": "1.51.0",
|
||||
"version": "1.52.0",
|
||||
"description": "Self-hosted mission control for AI coding agents: run Claude Code, Codex, OpenCode, Gemini, DeepSeek, Grok and more 24/7 in tmux, from any device.",
|
||||
"mcpName": "io.github.Ark0N/codeman",
|
||||
"type": "module",
|
||||
@@ -23,12 +23,14 @@
|
||||
"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",
|
||||
"pretest:mobile": "node scripts/prepare-test-vendor.mjs",
|
||||
"test:mobile": "vitest run --config test/mobile/vitest.config.ts",
|
||||
"check:frontend-syntax": "node scripts/check-frontend-syntax.mjs",
|
||||
"check:frontend-dead": "node scripts/check-frontend-dead-code.mjs",
|
||||
"check:browser-excludes": "node scripts/check-browser-test-excludes.mjs",
|
||||
"check:local-model-catalog": "tsx scripts/check-local-model-catalog.mjs",
|
||||
"fix:node-pty": "node scripts/fix-node-pty.mjs",
|
||||
@@ -123,7 +125,6 @@
|
||||
"@types/pngjs": "^6.0.5",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/uuid": "^10.0.0",
|
||||
"@types/web-push": "^3.6.4",
|
||||
"@types/ws": "^8.18.1",
|
||||
"@vitest/coverage-v8": "^4.1.8",
|
||||
|
||||
@@ -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,604 @@
|
||||
<!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;
|
||||
var to = 0;
|
||||
for (var i = 0; i < rects.length; i++) {
|
||||
if (i !== drag.from && centre > rects[i].left + rects[i].width / 2) 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.0",
|
||||
"version": "1.52.0",
|
||||
"author": {
|
||||
"name": "Ark0N",
|
||||
"url": "https://github.com/Ark0N"
|
||||
|
||||
+2
-1
@@ -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',
|
||||
@@ -157,7 +159,6 @@ console.log('\n[build] content-hash cache busting');
|
||||
'settings-ui.js',
|
||||
'panels-ui.js',
|
||||
'session-ui.js',
|
||||
'ralph-wizard.js',
|
||||
'api-client.js',
|
||||
'subagent-windows.js',
|
||||
'image-input.js',
|
||||
|
||||
@@ -1,482 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* capture-readme-gifs.mjs
|
||||
*
|
||||
* Deterministic README GIFs — no real server, Claude CLI, or tmux. Reuses the
|
||||
* mock-injection pipeline from capture-readme-screenshots.mjs (static file
|
||||
* server + page.route mocks), drives a scripted timeline in the page, records
|
||||
* it with Playwright video, and converts to GIF via ffmpeg palette encoding.
|
||||
*
|
||||
* Scenes:
|
||||
* 1. subagent-demo.gif — terminal spawns 3 parallel agents; floating agent
|
||||
* windows open one by one and stream tool-call activity live (driven
|
||||
* through the real _onSubagentDiscovered/_onSubagentToolCall handlers).
|
||||
* 2. zerolag-demo.gif — side-by-side typing: instant local echo (zerolag)
|
||||
* vs bursty ~350 ms server echo, rendered with the vendored xterm.
|
||||
*
|
||||
* Usage: node scripts/capture-readme-gifs.mjs
|
||||
* SCREENSHOT_OUT_DIR=/path/to/review node scripts/capture-readme-gifs.mjs
|
||||
* Output: docs/images/ (or flat into SCREENSHOT_OUT_DIR)
|
||||
* Requires: ffmpeg
|
||||
*/
|
||||
|
||||
import { chromium } from 'playwright';
|
||||
import { execSync } from 'child_process';
|
||||
import { mkdtempSync, rmSync } from 'fs';
|
||||
import { tmpdir } from 'os';
|
||||
import { join } from 'path';
|
||||
import {
|
||||
PORT,
|
||||
SESSION_IDS,
|
||||
STANDARD_SESSIONS,
|
||||
buildInitPayload,
|
||||
startStaticServer,
|
||||
setupRoutes,
|
||||
injectState,
|
||||
outPath,
|
||||
RST, GRN, YEL, MAG, CYN, GRY, BOLD,
|
||||
} from './capture-readme-screenshots.mjs';
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
const GIF_COLORS = 192;
|
||||
|
||||
// ─── ffmpeg conversion (palette recipe from capture-subagent-gif.mjs) ────────
|
||||
|
||||
function webmToGif(videoPath, gifPath, { ss, duration, width, fps }) {
|
||||
// One GLOBAL palette (default stats_mode=full) + ordered dither: per-frame
|
||||
// palettes (stats_mode=single:new=1) make dirty rectangles visibly mismatch
|
||||
// on flat dark UI, and error-diffusion dither shimmers between frames.
|
||||
const filters = `fps=${fps},scale=${width}:-1:flags=lanczos`;
|
||||
execSync(
|
||||
`ffmpeg -y -loglevel error -ss ${ss.toFixed(2)} -t ${duration} -i "${videoPath}" ` +
|
||||
`-vf "${filters},split[s0][s1];[s0]palettegen=max_colors=${GIF_COLORS}:reserve_transparent=0[p];` +
|
||||
`[s1][p]paletteuse=dither=bayer:bayer_scale=5:diff_mode=rectangle" "${gifPath}"`,
|
||||
{ stdio: 'inherit' }
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Scene 1: subagent demo ──────────────────────────────────────────────────
|
||||
|
||||
const SUBAGENT_VIEWPORT = { width: 1440, height: 810 };
|
||||
|
||||
// Terminal content visible before the agents spawn
|
||||
const TERMINAL_PRESPAWN = [
|
||||
'',
|
||||
`${GRN}●${RST} Working on ${CYN}/home/arkon/codeman-cases/testcase${RST} - I'll use the ${BOLD}Task tool${RST} to spawn parallel agents.`,
|
||||
'',
|
||||
`${GRN}●${RST} ${BOLD}Read${RST}(/home/arkon/codeman-cases/testcase/CLAUDE.md)`,
|
||||
` ${GRY}░${RST} Read ${BOLD}127${RST} lines ${GRY}│${RST} ${CYN}1.2KB${RST}`,
|
||||
'',
|
||||
`${GRN}●${RST} ${BOLD}Bash${RST}(find . -name "*.ts" -not -path "*/node_modules/*" | head -20)`,
|
||||
` ${GRY}░${RST} ./src/index.ts`,
|
||||
` ${GRY}░${RST} ./src/session.ts`,
|
||||
` ${GRY}░${RST} ./src/web/server.ts`,
|
||||
` ${GRY}░${RST} ${GRY}... (17 more)${RST}`,
|
||||
'',
|
||||
`${GRN}●${RST} I'll spawn 3 parallel research agents to analyze different parts of the codebase simultaneously.`,
|
||||
'',
|
||||
].join('\r\n');
|
||||
|
||||
function makeAgent(agentId, description, startedOffsetMs) {
|
||||
return {
|
||||
agentId,
|
||||
sessionId: 'claude-sess-w1-0001',
|
||||
projectHash: 'abc123',
|
||||
filePath: `/tmp/${agentId}.jsonl`,
|
||||
startedAt: new Date(Date.now() - startedOffsetMs).toISOString(),
|
||||
lastActivityAt: Date.now(),
|
||||
status: 'active',
|
||||
toolCallCount: 0,
|
||||
entryCount: 0,
|
||||
fileSize: 4000,
|
||||
description,
|
||||
model: 'claude-haiku-4-5-20251001',
|
||||
modelShort: 'haiku',
|
||||
totalInputTokens: 0,
|
||||
totalOutputTokens: 0,
|
||||
parentSessionId: SESSION_IDS.w1,
|
||||
};
|
||||
}
|
||||
|
||||
// Timeline events: t (ms from scene start) + kind
|
||||
// term — write raw data to the session terminal
|
||||
// discover — register subagent + open + position its floating window
|
||||
// tool — stream a tool call into an agent window
|
||||
// msg — stream an assistant message into an agent window
|
||||
// complete — flip an agent to completed
|
||||
function buildSubagentTimeline() {
|
||||
const T = (lines) => lines.join('\r\n') + '\r\n';
|
||||
const tool = (t, agentId, name, input) => ({ t, kind: 'tool', agentId, tool: name, input });
|
||||
const msg = (t, agentId, text) => ({ t, kind: 'msg', agentId, text });
|
||||
|
||||
return [
|
||||
{
|
||||
t: 600,
|
||||
kind: 'term',
|
||||
data: T([
|
||||
`${GRN}●${RST} ${BOLD}Task${RST}(Find and document all API endpoints in src/)`,
|
||||
` ${GRY}░${RST} Spawned ${CYN}agent-001${RST} ${GRY}(haiku)${RST}`,
|
||||
'',
|
||||
]),
|
||||
},
|
||||
{
|
||||
t: 1000,
|
||||
kind: 'discover',
|
||||
agent: makeAgent('agent-001', 'Find and document all API endpoints in src/', 2000),
|
||||
x: 440, y: 45,
|
||||
},
|
||||
tool(1500, 'agent-001', 'Glob', { pattern: 'src/**/*.ts' }),
|
||||
{
|
||||
t: 2000,
|
||||
kind: 'term',
|
||||
data: T([
|
||||
`${GRN}●${RST} ${BOLD}Task${RST}(Explore and understand test structure in test/)`,
|
||||
` ${GRY}░${RST} Spawned ${CYN}agent-002${RST} ${GRY}(haiku)${RST}`,
|
||||
'',
|
||||
]),
|
||||
},
|
||||
tool(2200, 'agent-001', 'Read', { file_path: '/home/arkon/codeman/src/web/server.ts' }),
|
||||
{
|
||||
t: 2500,
|
||||
kind: 'discover',
|
||||
agent: makeAgent('agent-002', 'Explore and understand test structure in test/', 1200),
|
||||
x: 880, y: 45,
|
||||
},
|
||||
tool(3000, 'agent-002', 'Glob', { pattern: 'test/**/*.test.ts' }),
|
||||
{
|
||||
t: 3300,
|
||||
kind: 'term',
|
||||
data: T([
|
||||
`${GRN}●${RST} ${BOLD}Task${RST}(Analyze TypeScript type definitions in src/types.ts)`,
|
||||
` ${GRY}░${RST} Spawned ${CYN}agent-003${RST} ${GRY}(haiku)${RST}`,
|
||||
'',
|
||||
]),
|
||||
},
|
||||
tool(3500, 'agent-001', 'Grep', { pattern: 'app\\.get|app\\.post|app\\.delete', path: 'src/' }),
|
||||
{
|
||||
t: 3800,
|
||||
kind: 'discover',
|
||||
agent: makeAgent('agent-003', 'Analyze TypeScript type definitions in src/types.ts', 400),
|
||||
x: 660, y: 400,
|
||||
},
|
||||
tool(4100, 'agent-002', 'Read', { file_path: '/home/arkon/codeman/test/respawn-test-utils.ts' }),
|
||||
{
|
||||
t: 4500,
|
||||
kind: 'term',
|
||||
data: T([
|
||||
`${MAG}✻${RST} ${YEL}Waiting for agents...${RST} ${GRY}(${BOLD}esc${RST}${GRY} to interrupt · 32s · ↓ 1.7k tokens · thinking)${RST}`,
|
||||
'',
|
||||
]),
|
||||
},
|
||||
tool(4700, 'agent-003', 'Read', { file_path: '/home/arkon/codeman/src/types.ts' }),
|
||||
tool(5200, 'agent-001', 'Read', { file_path: '/home/arkon/codeman/src/web/schemas.ts' }),
|
||||
tool(5600, 'agent-002', 'Read', { file_path: '/home/arkon/codeman/config/vitest.config.ts' }),
|
||||
tool(6100, 'agent-003', 'Grep', { pattern: 'export (interface|type)', path: 'src/types/' }),
|
||||
msg(6700, 'agent-001', 'Found 47 API endpoints across server.ts. Documenting REST paths...'),
|
||||
tool(7100, 'agent-002', 'Grep', { pattern: 'const PORT =', path: 'test/' }),
|
||||
msg(7700, 'agent-002', 'Analyzing test patterns: MockSession, unique ports, fileParallelism: false...'),
|
||||
tool(8100, 'agent-003', 'Read', { file_path: '/home/arkon/codeman/src/types/index.ts' }),
|
||||
msg(8700, 'agent-003', 'Mapped 38 exported interfaces across 15 domain files. Building summary...'),
|
||||
{
|
||||
t: 9300,
|
||||
kind: 'term',
|
||||
data: T([
|
||||
`${GRN}●${RST} ${CYN}agent-001${RST}: ${GRY}12 tool calls — Glob, Read(server.ts), Grep(endpoints)...${RST}`,
|
||||
`${GRN}●${RST} ${CYN}agent-002${RST}: ${GRY}8 tool calls — Glob, Read(test-utils), Read(vitest.config)...${RST}`,
|
||||
`${GRN}●${RST} ${CYN}agent-003${RST}: ${GRY}7 tool calls — Read(types.ts), Grep(interface)...${RST}`,
|
||||
'',
|
||||
]),
|
||||
},
|
||||
tool(10100, 'agent-001', 'Glob', { pattern: 'src/web/routes/*.ts' }),
|
||||
tool(10600, 'agent-002', 'Read', { file_path: '/home/arkon/codeman/test/setup.ts' }),
|
||||
tool(11100, 'agent-003', 'Grep', { pattern: 'assertNever', path: 'src/' }),
|
||||
{
|
||||
t: 11600,
|
||||
kind: 'term',
|
||||
data: T([`${GRN}●${RST} ${GRY}171.8k, 13s${RST} ${GRY}│${RST} ${GRY}1.7k tokens${RST} ${GRY}│${RST} ${GRY}thinking${RST}`, '']),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const SUBAGENT_TAIL_HOLD = 2500; // hold the final frame
|
||||
|
||||
async function recordSubagentScene(browser, videoDir) {
|
||||
console.log('\n1/2 Recording subagent-demo...');
|
||||
|
||||
const context = await browser.newContext({
|
||||
viewport: SUBAGENT_VIEWPORT,
|
||||
deviceScaleFactor: 1,
|
||||
recordVideo: { dir: videoDir, size: SUBAGENT_VIEWPORT },
|
||||
});
|
||||
const recStart = Date.now();
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
|
||||
// Start with NO subagents — they appear during the recording
|
||||
const initPayload = buildInitPayload(STANDARD_SESSIONS);
|
||||
await setupRoutes(page, initPayload, TERMINAL_PRESPAWN);
|
||||
await page.goto(`http://localhost:${PORT}`, { waitUntil: 'domcontentloaded' });
|
||||
await injectState(page, initPayload, TERMINAL_PRESPAWN, SESSION_IDS.w1);
|
||||
|
||||
await page.evaluate(() => {
|
||||
try { window.app?.fitAddon?.fit(); } catch {}
|
||||
window.app?.terminal?.scrollToBottom();
|
||||
});
|
||||
await sleep(500);
|
||||
|
||||
const timeline = buildSubagentTimeline();
|
||||
const totalMs = Math.max(...timeline.map((e) => e.t)) + SUBAGENT_TAIL_HOLD;
|
||||
const sceneStart = Date.now();
|
||||
|
||||
// Run the whole timeline inside the page so events interleave naturally
|
||||
await page.evaluate((events) => {
|
||||
const app = window.app;
|
||||
for (const ev of events) {
|
||||
setTimeout(() => {
|
||||
try {
|
||||
if (ev.kind === 'term') {
|
||||
app.terminal.write(ev.data);
|
||||
app.terminal.scrollToBottom();
|
||||
} else if (ev.kind === 'discover') {
|
||||
app._onSubagentDiscovered(ev.agent);
|
||||
app.openSubagentWindow(ev.agent.agentId);
|
||||
// The spawn animation (400ms) lands on the auto-grid; glide to our tile after it
|
||||
setTimeout(() => {
|
||||
const win = app.subagentWindows.get(ev.agent.agentId);
|
||||
if (win?.element) {
|
||||
win.element.style.transition = 'left 0.25s ease, top 0.25s ease';
|
||||
win.element.style.left = `${ev.x}px`;
|
||||
win.element.style.top = `${ev.y}px`;
|
||||
}
|
||||
}, 520);
|
||||
setTimeout(() => {
|
||||
const win = app.subagentWindows.get(ev.agent.agentId);
|
||||
if (win?.element) win.element.style.transition = '';
|
||||
app.updateConnectionLines();
|
||||
}, 850);
|
||||
} else if (ev.kind === 'tool') {
|
||||
app._onSubagentToolCall({
|
||||
agentId: ev.agentId,
|
||||
tool: ev.tool,
|
||||
input: ev.input,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
} else if (ev.kind === 'msg') {
|
||||
app._onSubagentMessage({
|
||||
agentId: ev.agentId,
|
||||
role: 'assistant',
|
||||
text: ev.text,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
} else if (ev.kind === 'complete') {
|
||||
app._onSubagentCompleted({ agentId: ev.agentId, timestamp: new Date().toISOString() });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('timeline event failed', ev, err);
|
||||
}
|
||||
}, ev.t);
|
||||
}
|
||||
}, timeline);
|
||||
|
||||
await sleep(totalMs + 500);
|
||||
|
||||
await page.close();
|
||||
const videoPath = await page.video().path();
|
||||
await context.close();
|
||||
|
||||
return {
|
||||
videoPath,
|
||||
ss: (sceneStart - recStart) / 1000 - 0.4,
|
||||
duration: (totalMs + 400) / 1000,
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Scene 2: zerolag typing comparison ──────────────────────────────────────
|
||||
|
||||
const ZEROLAG_VIEWPORT = { width: 1280, height: 470 };
|
||||
const TYPED_TEXT = 'echo "zero lag typing from anywhere"';
|
||||
const TYPE_INTERVAL_MS = 110;
|
||||
const REMOTE_FLUSH_MS = 350; // server-echo pane flushes queued chars in bursts
|
||||
const ZEROLAG_TAIL_HOLD = 1800;
|
||||
|
||||
const ZEROLAG_HTML = `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<link rel="stylesheet" href="http://localhost:${PORT}/vendor/xterm.css">
|
||||
<script src="http://localhost:${PORT}/vendor/xterm.min.js"></script>
|
||||
<style>
|
||||
* { margin: 0; box-sizing: border-box; }
|
||||
body {
|
||||
width: 1280px; height: 470px; background: #0a0a0c;
|
||||
display: flex; align-items: center; justify-content: center; gap: 48px;
|
||||
font-family: -apple-system, 'Segoe UI', Roboto, sans-serif;
|
||||
}
|
||||
.pane { width: 560px; }
|
||||
.card {
|
||||
background: #131316; border: 1px solid rgba(255,255,255,0.08);
|
||||
border-radius: 10px; overflow: hidden;
|
||||
box-shadow: 0 8px 32px rgba(0,0,0,0.45);
|
||||
}
|
||||
.card-head {
|
||||
display: flex; align-items: baseline; gap: 10px;
|
||||
padding: 12px 16px; border-bottom: 1px solid rgba(255,255,255,0.06);
|
||||
}
|
||||
.dot { width: 9px; height: 9px; border-radius: 50%; align-self: center; }
|
||||
.title { font-size: 15px; font-weight: 600; color: #e8e8ea; }
|
||||
.sub { font-size: 12.5px; color: #8b8b92; }
|
||||
.term { padding: 16px 8px 12px 16px; height: 165px; }
|
||||
.good .dot { background: #22c55e; box-shadow: 0 0 8px rgba(34,197,94,0.7); }
|
||||
.bad .dot { background: #ef4444; box-shadow: 0 0 8px rgba(239,68,68,0.7); }
|
||||
.tag {
|
||||
margin-top: 14px; text-align: center; font-size: 14.5px; color: #7e7e86;
|
||||
}
|
||||
.tag b { color: #22c55e; font-weight: 600; }
|
||||
.bad-tag b { color: #ef4444; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="pane">
|
||||
<div class="card good">
|
||||
<div class="card-head">
|
||||
<span class="dot"></span>
|
||||
<span class="title">With zerolag-input</span>
|
||||
<span class="sub">instant local echo</span>
|
||||
</div>
|
||||
<div class="term" id="termLeft"></div>
|
||||
</div>
|
||||
<div class="tag">keystrokes echo in <b>0 ms</b></div>
|
||||
</div>
|
||||
<div class="pane">
|
||||
<div class="card bad">
|
||||
<div class="card-head">
|
||||
<span class="dot"></span>
|
||||
<span class="title">Without</span>
|
||||
<span class="sub">server round-trip echo</span>
|
||||
</div>
|
||||
<div class="term" id="termRight"></div>
|
||||
</div>
|
||||
<div class="tag bad-tag">keystrokes echo after <b>~350 ms</b></div>
|
||||
</div>
|
||||
</body>
|
||||
</html>`;
|
||||
|
||||
async function recordZerolagScene(browser, videoDir) {
|
||||
console.log('\n2/2 Recording zerolag-demo...');
|
||||
|
||||
const context = await browser.newContext({
|
||||
viewport: ZEROLAG_VIEWPORT,
|
||||
deviceScaleFactor: 1,
|
||||
recordVideo: { dir: videoDir, size: ZEROLAG_VIEWPORT },
|
||||
});
|
||||
const recStart = Date.now();
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
|
||||
await page.setContent(ZEROLAG_HTML, { waitUntil: 'load' });
|
||||
await page.waitForFunction(() => typeof Terminal !== 'undefined');
|
||||
|
||||
await page.evaluate(() => {
|
||||
const theme = {
|
||||
background: '#131316',
|
||||
foreground: '#e8e8ea',
|
||||
cursor: '#22c55e',
|
||||
cursorAccent: '#131316',
|
||||
};
|
||||
const mk = (id) => {
|
||||
const term = new Terminal({
|
||||
cols: 44,
|
||||
rows: 5,
|
||||
fontSize: 20,
|
||||
fontFamily: "'SF Mono', 'Cascadia Code', Menlo, monospace",
|
||||
cursorBlink: true,
|
||||
cursorStyle: 'block',
|
||||
theme,
|
||||
});
|
||||
term.open(document.getElementById(id));
|
||||
term.write('\x1b[32m❯\x1b[0m ');
|
||||
return term;
|
||||
};
|
||||
window.termLeft = mk('termLeft');
|
||||
window.termRight = mk('termRight');
|
||||
});
|
||||
await sleep(600);
|
||||
|
||||
const sceneStart = Date.now();
|
||||
const typingMs = TYPED_TEXT.length * TYPE_INTERVAL_MS;
|
||||
const totalMs = typingMs + REMOTE_FLUSH_MS + ZEROLAG_TAIL_HOLD;
|
||||
|
||||
await page.evaluate(
|
||||
({ text, interval, flushEvery }) => {
|
||||
let i = 0;
|
||||
const remoteQueue = [];
|
||||
const typer = setInterval(() => {
|
||||
if (i >= text.length) { clearInterval(typer); return; }
|
||||
const ch = text[i++];
|
||||
window.termLeft.write(ch); // local echo: instant
|
||||
remoteQueue.push(ch); // server echo: waits for the round-trip
|
||||
}, interval);
|
||||
const flusher = setInterval(() => {
|
||||
if (remoteQueue.length) window.termRight.write(remoteQueue.splice(0).join(''));
|
||||
if (i >= text.length && remoteQueue.length === 0) clearInterval(flusher);
|
||||
}, flushEvery);
|
||||
},
|
||||
{ text: TYPED_TEXT, interval: TYPE_INTERVAL_MS, flushEvery: REMOTE_FLUSH_MS }
|
||||
);
|
||||
|
||||
await sleep(totalMs + 400);
|
||||
|
||||
await page.close();
|
||||
const videoPath = await page.video().path();
|
||||
await context.close();
|
||||
|
||||
return {
|
||||
videoPath,
|
||||
ss: (sceneStart - recStart) / 1000 - 0.6, // small lead-in with idle cursors
|
||||
duration: (totalMs + 600) / 1000,
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Main ────────────────────────────────────────────────────────────────────
|
||||
|
||||
async function main() {
|
||||
console.log('='.repeat(60));
|
||||
console.log('Codeman README GIF Capture');
|
||||
console.log('='.repeat(60));
|
||||
|
||||
const server = await startStaticServer();
|
||||
const videoDir = mkdtempSync(join(tmpdir(), 'codeman-gifs-'));
|
||||
let browser;
|
||||
|
||||
try {
|
||||
browser = await chromium.launch({
|
||||
headless: true,
|
||||
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],
|
||||
});
|
||||
|
||||
const sub = await recordSubagentScene(browser, videoDir);
|
||||
const subGif = outPath('images', 'subagent-demo.gif');
|
||||
webmToGif(sub.videoPath, subGif, { ss: Math.max(0, sub.ss), duration: sub.duration, width: 960, fps: 8 });
|
||||
console.log(` Saved: ${subGif}`);
|
||||
|
||||
const zl = await recordZerolagScene(browser, videoDir);
|
||||
const zlGif = outPath('images', 'zerolag-demo.gif');
|
||||
webmToGif(zl.videoPath, zlGif, { ss: Math.max(0, zl.ss), duration: zl.duration, width: 900, fps: 10 });
|
||||
console.log(` Saved: ${zlGif}`);
|
||||
|
||||
console.log('\nDone.');
|
||||
} catch (err) {
|
||||
console.error('\nFatal error:', err.message);
|
||||
console.error(err.stack);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
if (browser) await browser.close().catch(() => {});
|
||||
server.close();
|
||||
rmSync(videoDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
process.on('SIGINT', () => process.exit(1));
|
||||
|
||||
main();
|
||||
@@ -1,253 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* capture-readme-real.mjs
|
||||
*
|
||||
* Captures README desktop scenes (multi-session dashboard, monitor, subagent
|
||||
* windows) from a REAL Codeman instance — intended to run against an ISOLATED
|
||||
* dev/beta instance (CODEMAN_INSTANCE=beta on :5000) seeded from prod's settings,
|
||||
* NOT prod itself (never touch prod's live sessions).
|
||||
*
|
||||
* Reuses the high-quality capture recipe proven in capture-real-overview.mjs:
|
||||
* - DSF=2 + ?nowebgl → crisp retina at the TRUE font size (WebGL doubles
|
||||
* glyphs under DSF=2; the DOM renderer respects devicePixelRatio).
|
||||
* - per-device localStorage seeding so the capture matches a real device.
|
||||
*
|
||||
* SCENE=dashboard|monitor|subagent|all BASE=http://localhost:5000 \
|
||||
* OUT=screenshots-readme-real/desktop node scripts/capture-readme-real.mjs
|
||||
*/
|
||||
import { chromium } from 'playwright';
|
||||
import { mkdirSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
const BASE = process.env.BASE || 'http://localhost:5000';
|
||||
const OUT = process.env.OUT || 'screenshots-readme-real/desktop';
|
||||
const SKIN = process.env.SKIN || 'daylight-blue';
|
||||
const SCENE = process.env.SCENE || 'all';
|
||||
const FONT = Math.max(10, Math.min(24, Number(process.env.FONT || 13)));
|
||||
const VIEWPORT = { width: Number(process.env.VW || 1280), height: Number(process.env.VH || 720) };
|
||||
const DSF = Number(process.env.DSF || 2);
|
||||
const PLAN_USAGE = process.env.PLAN_USAGE !== '0';
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
const url = (extra = '') => {
|
||||
const sep = BASE.includes('?') ? '&' : '?';
|
||||
const params = [];
|
||||
if (DSF > 1) params.push('nowebgl'); // DOM renderer → correct font size at DSF>1
|
||||
if (extra) params.push(extra);
|
||||
return params.length ? `${BASE}${sep}${params.join('&')}` : BASE;
|
||||
};
|
||||
|
||||
async function newCtx(browser) {
|
||||
const context = await browser.newContext({
|
||||
viewport: VIEWPORT,
|
||||
deviceScaleFactor: DSF,
|
||||
ignoreHTTPSErrors: BASE.startsWith('https'),
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
await page.addInitScript(
|
||||
([skin, planUsage, font]) => {
|
||||
try {
|
||||
localStorage.setItem('codeman:skin', skin);
|
||||
localStorage.setItem('codeman-font-size', String(font));
|
||||
const blob = { skin, showFileBrowser: false, showProjectInsights: false, showTokenCount: false };
|
||||
// Don't auto-hide subagent windows that belong to a non-active tab — the
|
||||
// subagent scene re-homes agents and needs both windows visible at once.
|
||||
blob.subagentActiveTabOnly = false;
|
||||
if (planUsage) blob.showPlanUsageLimits = true;
|
||||
localStorage.setItem('codeman-app-settings', JSON.stringify(blob));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
},
|
||||
[SKIN, PLAN_USAGE, FONT]
|
||||
);
|
||||
return { context, page };
|
||||
}
|
||||
|
||||
async function bootstrap(page) {
|
||||
await page.waitForFunction(() => window.app && window.app.terminal, { timeout: 20000 });
|
||||
await sleep(1200);
|
||||
}
|
||||
|
||||
async function listSessions(page) {
|
||||
return page.evaluate(() =>
|
||||
Array.from(window.app.sessions.values()).map((s) => ({ id: s.id, name: s.name, mode: s.mode }))
|
||||
);
|
||||
}
|
||||
|
||||
async function shoot(page, name) {
|
||||
const out = join(OUT, name);
|
||||
await page.evaluate((f) => {
|
||||
try {
|
||||
if (window.app.setFontSize) window.app.setFontSize(f);
|
||||
} catch {}
|
||||
try {
|
||||
window.app.fitAddon && window.app.fitAddon.fit();
|
||||
} catch {}
|
||||
try {
|
||||
window.app.applyHeaderVisibilitySettings && window.app.applyHeaderVisibilitySettings();
|
||||
} catch {}
|
||||
}, FONT);
|
||||
await sleep(1500);
|
||||
await page.screenshot({ path: out, fullPage: false });
|
||||
console.log(' Saved: ' + out);
|
||||
}
|
||||
|
||||
async function sceneDashboard(browser) {
|
||||
console.log('Scene: dashboard');
|
||||
const { context, page } = await newCtx(browser);
|
||||
await page.goto(url(), { waitUntil: 'domcontentloaded' });
|
||||
await bootstrap(page);
|
||||
const sessions = await listSessions(page);
|
||||
// Select a claude session so the active terminal shows rich content; all tabs render.
|
||||
const target = sessions.find((s) => s.mode === 'claude') || sessions[0];
|
||||
if (target) await page.evaluate((id) => window.app.selectSession(id), target.id);
|
||||
await sleep(4000);
|
||||
await shoot(page, 'multi-session-dashboard.png');
|
||||
await context.close();
|
||||
}
|
||||
|
||||
async function sceneMonitor(browser) {
|
||||
console.log('Scene: monitor');
|
||||
const { context, page } = await newCtx(browser);
|
||||
await page.goto(url(), { waitUntil: 'domcontentloaded' });
|
||||
await bootstrap(page);
|
||||
const sessions = await listSessions(page);
|
||||
const target = sessions.find((s) => s.mode === 'claude') || sessions[0];
|
||||
if (target) await page.evaluate((id) => window.app.selectSession(id), target.id);
|
||||
await sleep(2500);
|
||||
// toggleMonitorPanel() opens the panel, clears the hidden state, loads REAL
|
||||
// mux sessions (/api/mux), starts stats, and renders the task panel.
|
||||
await page.evaluate(async () => {
|
||||
try {
|
||||
await window.app.toggleMonitorPanel();
|
||||
} catch {}
|
||||
});
|
||||
await sleep(3000);
|
||||
await shoot(page, 'multi-session-monitor.png');
|
||||
await context.close();
|
||||
}
|
||||
|
||||
async function sceneSubagent(browser) {
|
||||
console.log('Scene: subagent');
|
||||
const { context, page } = await newCtx(browser);
|
||||
await page.goto(url(), { waitUntil: 'domcontentloaded' });
|
||||
await bootstrap(page);
|
||||
// Select the session whose subagents we want (subagentActiveTabOnly means
|
||||
// app.subagents only fills for the active tab). Prefer SUBAGENT_SID env.
|
||||
const sessions = await listSessions(page);
|
||||
const targetId = process.env.SUBAGENT_SID || (sessions.find((s) => s.mode === 'claude') || sessions[0])?.id;
|
||||
if (targetId) await page.evaluate((id) => window.app.selectSession(id), targetId);
|
||||
// Wait (up to ~45s) for live subagents to arrive via SSE into app.subagents.
|
||||
let agents = [];
|
||||
for (let i = 0; i < 45; i++) {
|
||||
agents = await page.evaluate(() =>
|
||||
Array.from(window.app.subagents?.entries?.() || []).map(([id, a]) => ({ id, name: a.name ?? a.agentType ?? '' }))
|
||||
);
|
||||
if (agents.length >= 1) break;
|
||||
await sleep(1000);
|
||||
}
|
||||
console.log(' live in-browser subagents:', JSON.stringify(agents));
|
||||
if (agents.length === 0) {
|
||||
console.log(' NO live subagents — skipping (stage a longer subagent task and run this while it runs).');
|
||||
await context.close();
|
||||
return;
|
||||
}
|
||||
// The window body renders from app.subagentActivity, which fills ONLY from live
|
||||
// SSE tool-call/progress events — a fresh client never gets past activity replayed.
|
||||
// So sit connected and wait for live activity to accumulate, then open the two
|
||||
// agents that actually have content (otherwise the windows read "No activity yet").
|
||||
let active = [];
|
||||
for (let i = 0; i < 100; i++) {
|
||||
active = await page.evaluate(() =>
|
||||
Array.from(window.app.subagentActivity?.entries?.() || [])
|
||||
.filter(([, arr]) => Array.isArray(arr) && arr.length >= 1)
|
||||
.map(([id, arr]) => ({ id, n: arr.length }))
|
||||
.sort((a, b) => b.n - a.n)
|
||||
);
|
||||
if (active.length >= 2) break;
|
||||
// xhigh-effort agents churn in bursts between long thinking pauses, so be
|
||||
// patient (~150s); accept a single populated window after ~45s if that's all.
|
||||
if (i >= 30 && active.length >= 1) break;
|
||||
await sleep(1500);
|
||||
}
|
||||
console.log(' agents with live activity:', JSON.stringify(active));
|
||||
const openIds = (active.length ? active : agents).map((a) => a.id);
|
||||
// Capture-only DOM nudge: on fresh dev sessions, a tab's claudeSessionId stays the
|
||||
// Codeman id and never becomes the real Claude conversation UUID, so the window
|
||||
// open-gate (claudeSessionId === agent.sessionId) + the activeTabOnly hide rule both
|
||||
// fail. Re-home the chosen agents onto the active tab and align its claudeSessionId
|
||||
// to the agents' (shared) sessionId so the windows open AND show their live activity.
|
||||
await page.evaluate(
|
||||
(ids) => {
|
||||
const activeId = window.app.activeSessionId;
|
||||
const tab = window.app.sessions.get(activeId);
|
||||
ids.slice(0, 2).forEach((id) => {
|
||||
const a = window.app.subagents.get(id);
|
||||
if (!a) return;
|
||||
a.parentSessionId = activeId;
|
||||
if (tab && a.sessionId) tab.claudeSessionId = a.sessionId;
|
||||
});
|
||||
},
|
||||
openIds
|
||||
);
|
||||
await page.evaluate(
|
||||
(ids) => {
|
||||
ids.slice(0, 2).forEach((id) => {
|
||||
try {
|
||||
window.app.openSubagentWindow(id);
|
||||
} catch {}
|
||||
});
|
||||
},
|
||||
openIds
|
||||
);
|
||||
await sleep(2000);
|
||||
await page.evaluate(() => {
|
||||
// Viewport-relative tiling: center two subagent windows over the terminal so
|
||||
// the layout adapts to whatever VW/VH the capture uses (e.g. the HQ 1100×650
|
||||
// recipe) instead of overflowing at narrower widths.
|
||||
const wins = Array.from(window.app.subagentWindows.values());
|
||||
const W = window.innerWidth;
|
||||
const H = window.innerHeight;
|
||||
const winW = Math.min(440, Math.floor((W - 60) / 2 - 10));
|
||||
const winH = Math.min(360, Math.floor(H * 0.56));
|
||||
const top = Math.floor(H * 0.16);
|
||||
const gap = 16;
|
||||
const totalW = winW * 2 + gap;
|
||||
const startLeft = Math.max(16, Math.floor((W - totalW) / 2));
|
||||
wins.slice(0, 2).forEach((win, i) => {
|
||||
const el = win.element;
|
||||
// Force visible: a freshly opened window may be hidden by the activeTabOnly
|
||||
// rule before we override it (we also seed subagentActiveTabOnly:false).
|
||||
win.hidden = false;
|
||||
win.minimized = false;
|
||||
el.style.display = 'flex';
|
||||
el.style.left = startLeft + i * (winW + gap) + 'px';
|
||||
el.style.top = top + 'px';
|
||||
el.style.width = winW + 'px';
|
||||
el.style.height = winH + 'px';
|
||||
});
|
||||
});
|
||||
await sleep(1500);
|
||||
await shoot(page, 'subagent-spawn.png');
|
||||
await context.close();
|
||||
}
|
||||
|
||||
async function main() {
|
||||
mkdirSync(OUT, { recursive: true });
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],
|
||||
});
|
||||
console.log(`BASE=${BASE} SKIN=${SKIN} DSF=${DSF} VIEWPORT=${VIEWPORT.width}x${VIEWPORT.height} SCENE=${SCENE}`);
|
||||
if (SCENE === 'dashboard' || SCENE === 'all') await sceneDashboard(browser);
|
||||
if (SCENE === 'monitor' || SCENE === 'all') await sceneMonitor(browser);
|
||||
if (SCENE === 'subagent' || SCENE === 'all') await sceneSubagent(browser);
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error('FATAL', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,731 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* capture-video-screenshots.mjs
|
||||
*
|
||||
* Captures real Codeman UI screenshots for the Remotion demo video.
|
||||
* Uses Playwright + page.route() mock injection (same pattern as capture-readme-screenshots.mjs).
|
||||
* No real Claude CLI or server needed — all API responses are mocked.
|
||||
*
|
||||
* Usage: node scripts/capture-video-screenshots.mjs
|
||||
* Port: 3198 (static file server)
|
||||
* Output: scripts/scripts/remotion/public/ (6 PNGs)
|
||||
*/
|
||||
|
||||
import { chromium } from 'playwright';
|
||||
import { createServer } from 'http';
|
||||
import { readFileSync, existsSync } from 'fs';
|
||||
import { join, extname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = fileURLToPath(new URL('.', import.meta.url));
|
||||
const PROJECT_ROOT = join(__dirname, '..');
|
||||
const PUBLIC_DIR = join(PROJECT_ROOT, 'src', 'web', 'public');
|
||||
const OUTPUT_DIR = join(PROJECT_ROOT, 'scripts', 'remotion', 'public');
|
||||
const PORT = 3198;
|
||||
|
||||
const DESKTOP_VIEWPORT = { width: 1920, height: 1080 };
|
||||
const MOBILE_VIEWPORT = { width: 390, height: 844 };
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
// ─── MIME Types ──────────────────────────────────────────────────────────────
|
||||
|
||||
const MIME_TYPES = {
|
||||
'.html': 'text/html',
|
||||
'.js': 'text/javascript',
|
||||
'.css': 'text/css',
|
||||
'.json': 'application/json',
|
||||
'.png': 'image/png',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.ico': 'image/x-icon',
|
||||
'.woff2': 'font/woff2',
|
||||
'.woff': 'font/woff',
|
||||
'.ttf': 'font/ttf',
|
||||
};
|
||||
|
||||
// ─── Static File Server ──────────────────────────────────────────────────────
|
||||
|
||||
function startStaticServer() {
|
||||
return new Promise((resolve) => {
|
||||
const server = createServer((req, res) => {
|
||||
let urlPath = req.url.split('?')[0];
|
||||
if (urlPath === '/') urlPath = '/index.html';
|
||||
|
||||
const filePath = join(PUBLIC_DIR, urlPath);
|
||||
|
||||
if (!existsSync(filePath)) {
|
||||
res.writeHead(404);
|
||||
res.end('Not Found');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const data = readFileSync(filePath);
|
||||
const ext = extname(filePath);
|
||||
res.writeHead(200, {
|
||||
'Content-Type': MIME_TYPES[ext] || 'application/octet-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
});
|
||||
res.end(data);
|
||||
} catch {
|
||||
res.writeHead(500);
|
||||
res.end('Internal Server Error');
|
||||
}
|
||||
});
|
||||
|
||||
server.listen(PORT, () => {
|
||||
console.log(`Static server on http://localhost:${PORT}`);
|
||||
resolve(server);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Mock Data ───────────────────────────────────────────────────────────────
|
||||
|
||||
function makeSession(id, name, mode, status, extra = {}) {
|
||||
return {
|
||||
id,
|
||||
pid: status === 'idle' ? null : 12345 + Math.floor(Math.random() * 10000),
|
||||
status,
|
||||
workingDir: '/home/user/my-project',
|
||||
currentTaskId: null,
|
||||
createdAt: Date.now() - 3600000,
|
||||
lastActivityAt: Date.now() - (status === 'idle' ? 60000 : 5000),
|
||||
name,
|
||||
mode,
|
||||
autoClearEnabled: false,
|
||||
autoClearThreshold: 140000,
|
||||
autoCompactEnabled: false,
|
||||
autoCompactThreshold: 110000,
|
||||
autoCompactPrompt: '',
|
||||
imageWatcherEnabled: false,
|
||||
totalCost: mode === 'claude' ? 0.12 : 0,
|
||||
inputTokens: mode === 'claude' ? 18000 : 0,
|
||||
outputTokens: mode === 'claude' ? 11500 : 0,
|
||||
ralphEnabled: false,
|
||||
niceEnabled: false,
|
||||
niceValue: 10,
|
||||
color: 'default',
|
||||
flickerFilterEnabled: false,
|
||||
cliVersion: '2.1.61',
|
||||
cliModel: mode === 'claude' ? 'Opus 4.6' : 'GPT-4o',
|
||||
cliAccountType: mode === 'claude' ? 'Claude Max' : 'API Key',
|
||||
cliLatestVersion: '2.1.61',
|
||||
messageCount: 15,
|
||||
isWorking: status === 'busy',
|
||||
lastPromptTime: Date.now() - 30000,
|
||||
bufferStats: {
|
||||
terminalBufferSize: 4096,
|
||||
textOutputSize: 2048,
|
||||
messageCount: 15,
|
||||
maxTerminalBuffer: 2097152,
|
||||
maxTextOutput: 1048576,
|
||||
maxMessages: 1000,
|
||||
},
|
||||
taskStats: { total: 0, running: 0, completed: 0, failed: 0 },
|
||||
taskTree: [],
|
||||
tokens: {
|
||||
input: mode === 'claude' ? 18000 : 0,
|
||||
output: mode === 'claude' ? 11500 : 0,
|
||||
total: mode === 'claude' ? 29500 : 0,
|
||||
},
|
||||
autoClear: { enabled: false, threshold: 140000 },
|
||||
nice: { enabled: false, niceValue: 10 },
|
||||
ralphLoop: null,
|
||||
ralphTodos: [],
|
||||
ralphTodoStats: { total: 0, completed: 0, percentComplete: 0 },
|
||||
respawnEnabled: false,
|
||||
respawnConfig: null,
|
||||
respawn: null,
|
||||
claudeSessionId: `claude-${id}`,
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
function buildInitPayload(sessions) {
|
||||
const respawnStatus = {};
|
||||
for (const s of sessions) {
|
||||
respawnStatus[s.id] = {
|
||||
state: 'idle',
|
||||
cycleCount: 0,
|
||||
lastActivityTime: Date.now(),
|
||||
timeSinceActivity: 0,
|
||||
promptDetected: false,
|
||||
workingDetected: false,
|
||||
detection: {},
|
||||
config: null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
version: '0.1651',
|
||||
sessions,
|
||||
scheduledRuns: [],
|
||||
respawnStatus,
|
||||
globalStats: {
|
||||
totalInputTokens: 145000,
|
||||
totalOutputTokens: 87000,
|
||||
totalCost: 1.82,
|
||||
totalSessionsCreated: 12,
|
||||
firstRecordedAt: Date.now() - 86400000,
|
||||
lastUpdatedAt: Date.now(),
|
||||
},
|
||||
subagents: [],
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Terminal Content (ANSI) ─────────────────────────────────────────────────
|
||||
|
||||
const RST = '\x1b[0m';
|
||||
const RED = '\x1b[31m';
|
||||
const GRN = '\x1b[32m';
|
||||
const YEL = '\x1b[33m';
|
||||
const MAG = '\x1b[35m';
|
||||
const GRY = '\x1b[90m';
|
||||
const BOLD = '\x1b[1m';
|
||||
const DIM = '\x1b[2m';
|
||||
|
||||
// Claude Code init banner
|
||||
const TERMINAL_CLAUDE = [
|
||||
'',
|
||||
` ${RED}████${RST} ${BOLD}Claude Code${RST} v2.1.61`,
|
||||
` ${RED}████${RST} ${GRY}Opus 4.6${RST} ${DIM}·${RST} ${GRY}Claude Max${RST}`,
|
||||
` ${RED}██${RST} ${RED}██${RST} ${GRY}~/my-project${RST}`,
|
||||
'',
|
||||
'',
|
||||
`${GRY}❯ Try "how do I log an error?"${RST}`,
|
||||
'',
|
||||
'',
|
||||
`${YEL}»»${RST} ${BOLD}bypass permissions on${RST} ${GRY}(shift+tab to cycle)${RST}`,
|
||||
` ${BOLD}0 tokens${RST}`,
|
||||
` ${GRY}current: 2.1.61${RST} ${DIM}·${RST} ${GRY}latest: 2.1.61${RST}`,
|
||||
].join('\r\n');
|
||||
|
||||
// OpenCode init banner
|
||||
const TERMINAL_OPENCODE = [
|
||||
'',
|
||||
` ${GRN}████${RST} ${BOLD}OpenCode${RST} v0.3.12`,
|
||||
` ${GRN}████${RST} ${GRY}GPT-4o${RST} ${DIM}·${RST} ${GRY}API Key${RST}`,
|
||||
` ${GRN}██${RST} ${GRN}██${RST} ${GRY}~/my-project${RST}`,
|
||||
'',
|
||||
'',
|
||||
`${GRY}❯ Try "explain this codebase"${RST}`,
|
||||
'',
|
||||
'',
|
||||
`${YEL}»»${RST} ${BOLD}bypass permissions on${RST}`,
|
||||
` ${BOLD}0 tokens${RST}`,
|
||||
].join('\r\n');
|
||||
|
||||
// ─── Route Interceptors ──────────────────────────────────────────────────────
|
||||
|
||||
async function setupRoutes(page, initPayload, terminalContent) {
|
||||
// Block SSE to prevent reconnection loops
|
||||
await page.route('**/api/events', async (route) => {
|
||||
await route.abort();
|
||||
});
|
||||
|
||||
// Terminal buffer endpoint
|
||||
await page.route('**/api/sessions/*/terminal**', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
terminalBuffer: terminalContent,
|
||||
status: 'busy',
|
||||
fullSize: terminalContent.length,
|
||||
truncated: false,
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
// Mux sessions
|
||||
await page.route('**/api/mux-sessions/**', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ success: true }),
|
||||
});
|
||||
});
|
||||
|
||||
await page.route('**/api/mux-sessions', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ sessions: [], muxAvailable: true }),
|
||||
});
|
||||
});
|
||||
|
||||
// Settings
|
||||
await page.route('**/api/settings', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
showSubagents: false,
|
||||
subagentTrackingEnabled: false,
|
||||
subagentActiveTabOnly: false,
|
||||
showMonitor: false,
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
// Subagent window states
|
||||
await page.route('**/api/subagent-window-states', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
});
|
||||
|
||||
// Subagent parents
|
||||
await page.route('**/api/subagent-parents', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
});
|
||||
|
||||
// Session-specific subagents
|
||||
await page.route('**/api/sessions/*/subagents', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ success: true, data: [] }),
|
||||
});
|
||||
});
|
||||
|
||||
// Interactive attach
|
||||
await page.route('**/api/sessions/*/interactive', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ success: true }),
|
||||
});
|
||||
});
|
||||
|
||||
// Resize
|
||||
await page.route('**/api/sessions/*/resize', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ success: true }),
|
||||
});
|
||||
});
|
||||
|
||||
// Catch-all API
|
||||
await page.route('**/api/**', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ success: true }),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Inject mock state and render the app.
|
||||
*/
|
||||
async function injectState(page, initPayload, terminalContent, activeSessionId) {
|
||||
await page.waitForFunction(() => window.app && window.app.terminal, { timeout: 15000 });
|
||||
await sleep(2000);
|
||||
|
||||
// Cancel SSE fallback timer and inject state
|
||||
await page.evaluate((payload) => {
|
||||
const app = window.app;
|
||||
if (app._initFallbackTimer) {
|
||||
clearTimeout(app._initFallbackTimer);
|
||||
app._initFallbackTimer = null;
|
||||
}
|
||||
app.handleInit(payload);
|
||||
}, initPayload);
|
||||
|
||||
await sleep(3000);
|
||||
|
||||
// Select the target session
|
||||
if (activeSessionId) {
|
||||
await page.evaluate((sid) => {
|
||||
window.app.activeSessionId = null;
|
||||
window.app.selectSession(sid);
|
||||
}, activeSessionId);
|
||||
await sleep(4000);
|
||||
}
|
||||
|
||||
// Write terminal content directly as backup
|
||||
if (terminalContent && activeSessionId) {
|
||||
await page.evaluate((content) => {
|
||||
const app = window.app;
|
||||
if (app.terminal) {
|
||||
const buf = app.terminal.buffer?.active;
|
||||
const hasContent = buf && buf.length > 2 && buf.getLine(1)?.translateToString().trim();
|
||||
if (!hasContent) {
|
||||
app.terminal.clear();
|
||||
app.terminal.reset();
|
||||
app.terminal.write(content);
|
||||
app.terminal.scrollToBottom();
|
||||
}
|
||||
}
|
||||
}, terminalContent);
|
||||
await sleep(3000);
|
||||
}
|
||||
|
||||
// Clean up UI artifacts
|
||||
await page.evaluate(() => {
|
||||
const app = window.app;
|
||||
if (app) {
|
||||
if (app.sseReconnectTimeout) clearTimeout(app.sseReconnectTimeout);
|
||||
if (app.eventSource) { app.eventSource.close(); app.eventSource = null; }
|
||||
app._connectionStatus = 'connected';
|
||||
app._updateConnectionIndicator = () => {};
|
||||
app.connectSSE = () => {};
|
||||
app.setConnectionStatus = () => {};
|
||||
}
|
||||
|
||||
// Remove connection indicator
|
||||
const indicator = document.getElementById('connectionIndicator');
|
||||
if (indicator) indicator.remove();
|
||||
|
||||
// Hide respawn banner
|
||||
const respawnBanner = document.getElementById('respawnBanner');
|
||||
if (respawnBanner) respawnBanner.style.display = 'none';
|
||||
|
||||
// Mock CPU/MEM stats
|
||||
const statsEl = document.getElementById('headerSystemStats');
|
||||
if (statsEl) {
|
||||
statsEl.innerHTML = `
|
||||
<span class="stat-label">CPU</span>
|
||||
<div class="stat-bar"><div class="stat-bar-fill cpu-bar" style="width: 18%"></div></div>
|
||||
<span class="stat-value">18%</span>
|
||||
<span class="stat-label">MEM</span>
|
||||
<div class="stat-bar"><div class="stat-bar-fill mem-bar" style="width: 42%"></div></div>
|
||||
<span class="stat-value">13.7G</span>
|
||||
`;
|
||||
}
|
||||
|
||||
// Hide subagents panel entirely
|
||||
const subagentsPanel = document.getElementById('subagentsPanel');
|
||||
if (subagentsPanel) subagentsPanel.style.display = 'none';
|
||||
|
||||
// Close and hide monitor panel
|
||||
const monitorPanel = document.getElementById('monitorPanel');
|
||||
if (monitorPanel) {
|
||||
monitorPanel.classList.remove('open');
|
||||
monitorPanel.style.display = 'none';
|
||||
}
|
||||
|
||||
// Hide monitor toggle button in toolbar
|
||||
const monitorBtn = document.getElementById('monitorToggle');
|
||||
if (monitorBtn) monitorBtn.style.display = 'none';
|
||||
|
||||
// Update token display
|
||||
if (app && app.activeSessionId) {
|
||||
const session = app.sessions.get(app.activeSessionId);
|
||||
if (session) {
|
||||
const tokens = (session.tokens?.total || 0);
|
||||
const tokenEl = document.getElementById('headerTokens');
|
||||
if (tokenEl) {
|
||||
const formatted = tokens >= 1000 ? `${(tokens / 1000).toFixed(1)}k` : String(tokens);
|
||||
tokenEl.innerHTML = `<span class="token-icon">⊙</span> <span class="token-count">${formatted} tokens</span>`;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Final settle — let xterm.js WebGL renderer, fonts, and layout fully stabilize
|
||||
await sleep(4000);
|
||||
}
|
||||
|
||||
// ─── Screenshot Scenarios ────────────────────────────────────────────────────
|
||||
|
||||
// 1. Desktop welcome — no sessions, welcome overlay visible
|
||||
async function captureDesktopWelcome(browser) {
|
||||
console.log('\n1/6 Capturing desktop-welcome.png...');
|
||||
|
||||
const context = await browser.newContext({
|
||||
viewport: DESKTOP_VIEWPORT,
|
||||
deviceScaleFactor: 1,
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
|
||||
try {
|
||||
const initPayload = buildInitPayload([]);
|
||||
await setupRoutes(page, initPayload, '');
|
||||
|
||||
await page.goto(`http://localhost:${PORT}`, { waitUntil: 'domcontentloaded' });
|
||||
await page.waitForFunction(() => window.app && window.app.terminal, { timeout: 15000 });
|
||||
await sleep(2000);
|
||||
|
||||
// Inject empty state — welcome overlay should show automatically
|
||||
await page.evaluate((payload) => {
|
||||
const app = window.app;
|
||||
if (app._initFallbackTimer) {
|
||||
clearTimeout(app._initFallbackTimer);
|
||||
app._initFallbackTimer = null;
|
||||
}
|
||||
app.handleInit(payload);
|
||||
}, initPayload);
|
||||
await sleep(3000);
|
||||
|
||||
// Clean up UI
|
||||
await page.evaluate(() => {
|
||||
const app = window.app;
|
||||
if (app) {
|
||||
if (app.sseReconnectTimeout) clearTimeout(app.sseReconnectTimeout);
|
||||
if (app.eventSource) { app.eventSource.close(); app.eventSource = null; }
|
||||
app._connectionStatus = 'connected';
|
||||
app._updateConnectionIndicator = () => {};
|
||||
app.connectSSE = () => {};
|
||||
app.setConnectionStatus = () => {};
|
||||
}
|
||||
const indicator = document.getElementById('connectionIndicator');
|
||||
if (indicator) indicator.remove();
|
||||
const respawnBanner = document.getElementById('respawnBanner');
|
||||
if (respawnBanner) respawnBanner.style.display = 'none';
|
||||
|
||||
// Mock stats
|
||||
const statsEl = document.getElementById('headerSystemStats');
|
||||
if (statsEl) {
|
||||
statsEl.innerHTML = `
|
||||
<span class="stat-label">CPU</span>
|
||||
<div class="stat-bar"><div class="stat-bar-fill cpu-bar" style="width: 18%"></div></div>
|
||||
<span class="stat-value">18%</span>
|
||||
<span class="stat-label">MEM</span>
|
||||
<div class="stat-bar"><div class="stat-bar-fill mem-bar" style="width: 42%"></div></div>
|
||||
<span class="stat-value">13.7G</span>
|
||||
`;
|
||||
}
|
||||
|
||||
// Hide monitor and subagent panels
|
||||
const subagentsPanel = document.getElementById('subagentsPanel');
|
||||
if (subagentsPanel) subagentsPanel.style.display = 'none';
|
||||
const monitorPanel = document.getElementById('monitorPanel');
|
||||
if (monitorPanel) {
|
||||
monitorPanel.classList.remove('open');
|
||||
monitorPanel.style.display = 'none';
|
||||
}
|
||||
const monitorBtn = document.getElementById('monitorToggle');
|
||||
if (monitorBtn) monitorBtn.style.display = 'none';
|
||||
});
|
||||
await sleep(3000);
|
||||
|
||||
await page.screenshot({
|
||||
path: join(OUTPUT_DIR, 'desktop-welcome.png'),
|
||||
fullPage: false,
|
||||
});
|
||||
console.log(' Saved: scripts/remotion/public/desktop-welcome.png');
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Desktop with single Claude tab active
|
||||
async function captureDesktopClaude(browser) {
|
||||
console.log('\n2/6 Capturing desktop-claude.png...');
|
||||
|
||||
const claudeSession = makeSession('sess-claude-1', 'w1-my-project', 'claude', 'busy');
|
||||
const initPayload = buildInitPayload([claudeSession]);
|
||||
|
||||
const context = await browser.newContext({
|
||||
viewport: DESKTOP_VIEWPORT,
|
||||
deviceScaleFactor: 1,
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
|
||||
try {
|
||||
await setupRoutes(page, initPayload, TERMINAL_CLAUDE);
|
||||
await page.goto(`http://localhost:${PORT}`, { waitUntil: 'domcontentloaded' });
|
||||
await injectState(page, initPayload, TERMINAL_CLAUDE, 'sess-claude-1');
|
||||
|
||||
await page.screenshot({
|
||||
path: join(OUTPUT_DIR, 'desktop-claude.png'),
|
||||
fullPage: false,
|
||||
});
|
||||
console.log(' Saved: scripts/remotion/public/desktop-claude.png');
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Desktop with 2 tabs (Claude + OpenCode), Claude active
|
||||
async function captureDesktopBothClaude(browser) {
|
||||
console.log('\n3/6 Capturing desktop-both-claude.png...');
|
||||
|
||||
const claudeSession = makeSession('sess-claude-2', 'w1-my-project', 'claude', 'busy');
|
||||
const opencodeSession = makeSession('sess-opencode-2', 'w2-my-project', 'opencode', 'busy');
|
||||
const initPayload = buildInitPayload([claudeSession, opencodeSession]);
|
||||
|
||||
const context = await browser.newContext({
|
||||
viewport: DESKTOP_VIEWPORT,
|
||||
deviceScaleFactor: 1,
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
|
||||
try {
|
||||
await setupRoutes(page, initPayload, TERMINAL_CLAUDE);
|
||||
await page.goto(`http://localhost:${PORT}`, { waitUntil: 'domcontentloaded' });
|
||||
await injectState(page, initPayload, TERMINAL_CLAUDE, 'sess-claude-2');
|
||||
|
||||
await page.screenshot({
|
||||
path: join(OUTPUT_DIR, 'desktop-both-claude.png'),
|
||||
fullPage: false,
|
||||
});
|
||||
console.log(' Saved: scripts/remotion/public/desktop-both-claude.png');
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Desktop with 2 tabs (Claude + OpenCode), OpenCode active
|
||||
async function captureDesktopBothOpencode(browser) {
|
||||
console.log('\n4/6 Capturing desktop-both-opencode.png...');
|
||||
|
||||
const claudeSession = makeSession('sess-claude-3', 'w1-my-project', 'claude', 'busy');
|
||||
const opencodeSession = makeSession('sess-opencode-3', 'w2-my-project', 'opencode', 'busy');
|
||||
const initPayload = buildInitPayload([claudeSession, opencodeSession]);
|
||||
|
||||
const context = await browser.newContext({
|
||||
viewport: DESKTOP_VIEWPORT,
|
||||
deviceScaleFactor: 1,
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
|
||||
try {
|
||||
await setupRoutes(page, initPayload, TERMINAL_OPENCODE);
|
||||
await page.goto(`http://localhost:${PORT}`, { waitUntil: 'domcontentloaded' });
|
||||
await injectState(page, initPayload, TERMINAL_OPENCODE, 'sess-opencode-3');
|
||||
|
||||
await page.screenshot({
|
||||
path: join(OUTPUT_DIR, 'desktop-both-opencode.png'),
|
||||
fullPage: false,
|
||||
});
|
||||
console.log(' Saved: scripts/remotion/public/desktop-both-opencode.png');
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Mobile with Claude tab
|
||||
async function captureMobileClaude(browser) {
|
||||
console.log('\n5/6 Capturing mobile-claude.png...');
|
||||
|
||||
const claudeSession = makeSession('sess-claude-m1', 'w1-my-project', 'claude', 'busy');
|
||||
const initPayload = buildInitPayload([claudeSession]);
|
||||
|
||||
const context = await browser.newContext({
|
||||
viewport: MOBILE_VIEWPORT,
|
||||
deviceScaleFactor: 2,
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
|
||||
try {
|
||||
await setupRoutes(page, initPayload, TERMINAL_CLAUDE);
|
||||
await page.goto(`http://localhost:${PORT}`, { waitUntil: 'domcontentloaded' });
|
||||
await injectState(page, initPayload, TERMINAL_CLAUDE, 'sess-claude-m1');
|
||||
|
||||
await page.screenshot({
|
||||
path: join(OUTPUT_DIR, 'mobile-claude.png'),
|
||||
fullPage: false,
|
||||
});
|
||||
console.log(' Saved: scripts/remotion/public/mobile-claude.png');
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Mobile with OpenCode tab
|
||||
async function captureMobileOpencode(browser) {
|
||||
console.log('\n6/6 Capturing mobile-opencode.png...');
|
||||
|
||||
const opencodeSession = makeSession('sess-opencode-m1', 'w1-my-project', 'opencode', 'busy');
|
||||
const initPayload = buildInitPayload([opencodeSession]);
|
||||
|
||||
const context = await browser.newContext({
|
||||
viewport: MOBILE_VIEWPORT,
|
||||
deviceScaleFactor: 2,
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
|
||||
try {
|
||||
await setupRoutes(page, initPayload, TERMINAL_OPENCODE);
|
||||
await page.goto(`http://localhost:${PORT}`, { waitUntil: 'domcontentloaded' });
|
||||
await injectState(page, initPayload, TERMINAL_OPENCODE, 'sess-opencode-m1');
|
||||
|
||||
await page.screenshot({
|
||||
path: join(OUTPUT_DIR, 'mobile-opencode.png'),
|
||||
fullPage: false,
|
||||
});
|
||||
console.log(' Saved: scripts/remotion/public/mobile-opencode.png');
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Main ────────────────────────────────────────────────────────────────────
|
||||
|
||||
async function main() {
|
||||
console.log('='.repeat(60));
|
||||
console.log('Codeman Video Screenshot Capture');
|
||||
console.log('='.repeat(60));
|
||||
console.log(`Port: ${PORT}`);
|
||||
console.log(`Desktop: ${DESKTOP_VIEWPORT.width}x${DESKTOP_VIEWPORT.height}`);
|
||||
console.log(`Mobile: ${MOBILE_VIEWPORT.width}x${MOBILE_VIEWPORT.height} @2x`);
|
||||
console.log(`Output: ${OUTPUT_DIR}`);
|
||||
console.log('');
|
||||
|
||||
const server = await startStaticServer();
|
||||
let browser;
|
||||
|
||||
try {
|
||||
browser = await chromium.launch({
|
||||
headless: true,
|
||||
args: [
|
||||
'--no-sandbox',
|
||||
'--disable-setuid-sandbox',
|
||||
'--disable-dev-shm-usage',
|
||||
'--disable-gpu',
|
||||
],
|
||||
});
|
||||
|
||||
await captureDesktopWelcome(browser);
|
||||
await captureDesktopClaude(browser);
|
||||
await captureDesktopBothClaude(browser);
|
||||
await captureDesktopBothOpencode(browser);
|
||||
await captureMobileClaude(browser);
|
||||
await captureMobileOpencode(browser);
|
||||
|
||||
console.log('\n' + '='.repeat(60));
|
||||
console.log('All 6 screenshots captured!');
|
||||
console.log('='.repeat(60));
|
||||
console.log('\nOutput files:');
|
||||
console.log(' scripts/remotion/public/desktop-welcome.png');
|
||||
console.log(' scripts/remotion/public/desktop-claude.png');
|
||||
console.log(' scripts/remotion/public/desktop-both-claude.png');
|
||||
console.log(' scripts/remotion/public/desktop-both-opencode.png');
|
||||
console.log(' scripts/remotion/public/mobile-claude.png');
|
||||
console.log(' scripts/remotion/public/mobile-opencode.png');
|
||||
} catch (err) {
|
||||
console.error('\nFatal error:', err.message);
|
||||
console.error(err.stack);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
if (browser) await browser.close().catch(() => {});
|
||||
server.close();
|
||||
console.log('\nDone.');
|
||||
}
|
||||
}
|
||||
|
||||
process.on('SIGINT', () => {
|
||||
console.log('\nInterrupted.');
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,270 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Frontend dead-code check.
|
||||
*
|
||||
* `src/web/public/*.js` is loaded as plain <script> files: no imports, so knip cannot
|
||||
* follow it, and it is outside ESLint. A method that lost its last caller therefore
|
||||
* stays in the tree unnoticed (the November 2026 cleanup removed about 2,000 such
|
||||
* lines of JS and 1,500 lines of CSS). This script finds them.
|
||||
*
|
||||
* JavaScript: every function, method and top-level binding the frontend files
|
||||
* define, checked against every identifier and every string or template literal in
|
||||
* those files, `index.html` (inline handlers), the gesture overlay's source and the
|
||||
* tests. A name that appears nowhere but at its own definition is reported.
|
||||
*
|
||||
* CSS: every class and id selector in `styles.css` and `mobile.css`, checked against
|
||||
* the same text. A class built at runtime (`tab-state-${state}`) is recognised by its
|
||||
* prefix and skipped, so the report holds only names no code can produce.
|
||||
*
|
||||
* Text matching is deliberately conservative: a mention in a comment does not count,
|
||||
* a mention in any string does. So a clean run does not prove everything is used,
|
||||
* but a reported name really has no reference. To keep one on purpose, add it to
|
||||
* ALLOW below with the reason.
|
||||
*
|
||||
* Usage: node scripts/check-frontend-dead-code.mjs [--production]
|
||||
* --production also report what only tests reference (informational, exit 0)
|
||||
*
|
||||
* Parsed with the TypeScript compiler (already a dev dependency), so this needs no
|
||||
* package of its own.
|
||||
*/
|
||||
import { readFileSync, readdirSync, statSync, existsSync } from 'node:fs';
|
||||
import { join, dirname, relative } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { createRequire } from 'node:module';
|
||||
|
||||
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const PUBLIC_DIR = join(ROOT, 'src', 'web', 'public');
|
||||
const require = createRequire(join(ROOT, 'package.json'));
|
||||
const ts = require('typescript');
|
||||
const postcss = require('postcss');
|
||||
|
||||
/**
|
||||
* Names kept on purpose although nothing references them. Key: the name as reported
|
||||
* (a JS name, or a selector with its `.` or `#`). Value: why it stays.
|
||||
*/
|
||||
const ALLOW = new Map([
|
||||
// ['exampleMethod', 'called from the browser console when debugging X'],
|
||||
]);
|
||||
|
||||
/** Class prefixes that belong to vendored code, which the scan does not read. */
|
||||
const EXTERNAL_CLASS_PREFIXES = ['xterm'];
|
||||
|
||||
const productionMode = process.argv.includes('--production');
|
||||
|
||||
function walk(dir, filter, skipDirs = []) {
|
||||
const out = [];
|
||||
if (!existsSync(dir)) return out;
|
||||
for (const entry of readdirSync(dir)) {
|
||||
if (entry === 'node_modules' || skipDirs.includes(entry)) continue;
|
||||
const path = join(dir, entry);
|
||||
if (statSync(path).isDirectory()) out.push(...walk(path, filter, skipDirs));
|
||||
else if (filter.test(entry)) out.push(path);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const rel = (path) => relative(ROOT, path);
|
||||
const read = (path) => readFileSync(path, 'utf8');
|
||||
|
||||
// ── What counts as a reference ────────────────────────────────────────────────
|
||||
|
||||
// Shipped scripts. The vendored bundles and the generated gesture bundle are not ours
|
||||
// to judge; the gesture overlay is read from its source instead.
|
||||
const frontendFiles = walk(PUBLIC_DIR, /\.js$/, ['vendor', 'gesture', 'fonts']);
|
||||
const htmlText = walk(PUBLIC_DIR, /\.html$/, ['vendor', 'gesture']).map(read).join('\n');
|
||||
const gestureText = walk(join(ROOT, 'packages', 'gesture-control', 'src'), /\.(ts|js)$/)
|
||||
.map(read)
|
||||
.join('\n');
|
||||
const serverText = walk(join(ROOT, 'src'), /\.ts$/, ['public']).map(read).join('\n');
|
||||
const overlayText = walk(join(ROOT, 'packages', 'xterm-zerolag-input', 'src'), /\.(ts|js)$/)
|
||||
.map(read)
|
||||
.join('\n');
|
||||
const testText = walk(join(ROOT, 'test'), /\.(ts|mjs|js)$/).map(read).join('\n');
|
||||
|
||||
const identifierCount = new Map();
|
||||
const literalParts = [];
|
||||
const definitions = [];
|
||||
|
||||
function bump(name) {
|
||||
identifierCount.set(name, (identifierCount.get(name) ?? 0) + 1);
|
||||
}
|
||||
|
||||
function isFunctionLike(node) {
|
||||
return !!node && (ts.isFunctionExpression(node) || ts.isArrowFunction(node));
|
||||
}
|
||||
|
||||
function propertyName(name) {
|
||||
if (!name) return null;
|
||||
if (ts.isIdentifier(name) || ts.isStringLiteral(name)) return name.text;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Top-level statements, looking one level into an IIFE wrapper. */
|
||||
function topLevelStatements(sourceFile) {
|
||||
const out = [...sourceFile.statements];
|
||||
for (const statement of sourceFile.statements) {
|
||||
if (!ts.isExpressionStatement(statement)) continue;
|
||||
let expr = statement.expression;
|
||||
while (ts.isParenthesizedExpression(expr) || ts.isPrefixUnaryExpression(expr)) {
|
||||
expr = ts.isParenthesizedExpression(expr) ? expr.expression : expr.operand;
|
||||
}
|
||||
if (!ts.isCallExpression(expr)) continue;
|
||||
let callee = expr.expression;
|
||||
while (ts.isParenthesizedExpression(callee)) callee = callee.expression;
|
||||
if (ts.isPropertyAccessExpression(callee)) callee = callee.expression;
|
||||
while (ts.isParenthesizedExpression(callee)) callee = callee.expression;
|
||||
if ((ts.isFunctionExpression(callee) || ts.isArrowFunction(callee)) && ts.isBlock(callee.body)) {
|
||||
out.push(...callee.body.statements);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
for (const file of frontendFiles) {
|
||||
const text = read(file);
|
||||
const sourceFile = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
|
||||
const lineOf = (node) => sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
|
||||
const define = (name, node, kind) => {
|
||||
if (name) definitions.push({ name, file: rel(file), line: lineOf(node), kind });
|
||||
};
|
||||
|
||||
for (const statement of topLevelStatements(sourceFile)) {
|
||||
if (ts.isVariableStatement(statement)) {
|
||||
for (const decl of statement.declarationList.declarations) {
|
||||
if (ts.isIdentifier(decl.name)) define(decl.name.text, decl, 'binding');
|
||||
}
|
||||
} else if (ts.isClassDeclaration(statement) && statement.name) {
|
||||
define(statement.name.text, statement, 'binding');
|
||||
}
|
||||
}
|
||||
|
||||
const visit = (node) => {
|
||||
if (ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) bump(node.text);
|
||||
else if (
|
||||
ts.isStringLiteral(node) ||
|
||||
ts.isNoSubstitutionTemplateLiteral(node) ||
|
||||
node.kind === ts.SyntaxKind.TemplateHead ||
|
||||
node.kind === ts.SyntaxKind.TemplateMiddle ||
|
||||
node.kind === ts.SyntaxKind.TemplateTail
|
||||
) {
|
||||
literalParts.push(node.text);
|
||||
}
|
||||
|
||||
if (ts.isFunctionDeclaration(node) && node.name) define(node.name.text, node, 'function');
|
||||
else if (ts.isMethodDeclaration(node) || ts.isGetAccessor(node) || ts.isSetAccessor(node)) {
|
||||
define(propertyName(node.name), node, 'method');
|
||||
} else if (ts.isPropertyAssignment(node) && isFunctionLike(node.initializer)) {
|
||||
define(propertyName(node.name), node, 'method');
|
||||
} else if (ts.isPropertyDeclaration(node) && isFunctionLike(node.initializer)) {
|
||||
define(propertyName(node.name), node, 'method');
|
||||
} else if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && isFunctionLike(node.initializer)) {
|
||||
define(node.name.text, node, 'function');
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
};
|
||||
visit(sourceFile);
|
||||
}
|
||||
|
||||
const literalText = literalParts.join('\n');
|
||||
const wordPattern = (name) => new RegExp(`(?<![\\w$])${name.replace(/[$]/g, '\\$&')}(?![\\w$])`, 'g');
|
||||
const count = (text, pattern) => (text.match(pattern) ?? []).length;
|
||||
|
||||
// ── JavaScript ────────────────────────────────────────────────────────────────
|
||||
|
||||
const byName = new Map();
|
||||
for (const def of definitions) {
|
||||
// A binding and a function for the same declaration are one definition.
|
||||
const list = byName.get(def.name) ?? [];
|
||||
if (!list.some((d) => d.file === def.file && d.line === def.line)) list.push(def);
|
||||
byName.set(def.name, list);
|
||||
}
|
||||
|
||||
const deadJs = [];
|
||||
const testOnlyJs = [];
|
||||
for (const [name, defs] of byName) {
|
||||
if (name.length < 3 || name === 'constructor' || ALLOW.has(name)) continue;
|
||||
const pattern = wordPattern(name);
|
||||
const shipped =
|
||||
(identifierCount.get(name) ?? 0) -
|
||||
defs.length +
|
||||
count(literalText, pattern) +
|
||||
count(htmlText, pattern) +
|
||||
count(gestureText, pattern);
|
||||
if (shipped > 0) continue;
|
||||
const inTests = count(testText, pattern);
|
||||
(inTests > 0 ? testOnlyJs : deadJs).push({ name, defs, inTests });
|
||||
}
|
||||
|
||||
// ── CSS ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
const cssCorpus = [
|
||||
...frontendFiles.map(read),
|
||||
htmlText,
|
||||
gestureText,
|
||||
overlayText,
|
||||
serverText,
|
||||
...walk(PUBLIC_DIR, /\.json$/, ['vendor', 'gesture']).map(read),
|
||||
].join('\n');
|
||||
const corpusWords = new Set(cssCorpus.match(/[A-Za-z_][\w-]*/g) ?? []);
|
||||
// `foo-${x}` and 'foo-' + x build a class at runtime: everything with that prefix may exist.
|
||||
const dynamicPrefixes = new Set();
|
||||
for (const m of cssCorpus.matchAll(/([A-Za-z_][\w-]*-)(?:\$\{|['"`]\s*\+)/g)) dynamicPrefixes.add(m[1]);
|
||||
// `${x}-suffix` and x + '-suffix' likewise, when the stem itself is a known word.
|
||||
const dynamicSuffixes = new Set();
|
||||
for (const m of cssCorpus.matchAll(/(?:\}|\+\s*['"`])(-[\w-]+)/g)) dynamicSuffixes.add(m[1]);
|
||||
|
||||
const deadCss = [];
|
||||
for (const cssFile of [join(PUBLIC_DIR, 'styles.css'), join(PUBLIC_DIR, 'mobile.css')]) {
|
||||
const seen = new Map();
|
||||
postcss.parse(read(cssFile), { from: cssFile }).walkRules((rule) => {
|
||||
const selector = rule.selector.replace(/\[[^\]]*\]/g, ' ').replace(/"[^"]*"|'[^']*'/g, ' ');
|
||||
for (const m of selector.matchAll(/([.#])(-?[A-Za-z_][\w-]*)/g)) {
|
||||
const key = m[1] + m[2];
|
||||
if (!seen.has(key)) seen.set(key, rule.source.start.line);
|
||||
}
|
||||
});
|
||||
for (const [key, line] of seen) {
|
||||
const name = key.slice(1);
|
||||
if (ALLOW.has(key) || corpusWords.has(name)) continue;
|
||||
if (EXTERNAL_CLASS_PREFIXES.some((prefix) => name === prefix || name.startsWith(prefix + '-'))) continue;
|
||||
if ([...dynamicPrefixes].some((prefix) => name.startsWith(prefix))) continue;
|
||||
if ([...dynamicSuffixes].some((suffix) => name.endsWith(suffix) && corpusWords.has(name.slice(0, -suffix.length)))) {
|
||||
continue;
|
||||
}
|
||||
if (deadCss.some((d) => d.key === key)) continue;
|
||||
deadCss.push({ key, file: rel(cssFile), line });
|
||||
}
|
||||
}
|
||||
|
||||
// ── Report ────────────────────────────────────────────────────────────────────
|
||||
|
||||
const where = (defs) => defs.map((d) => `${d.file}:${d.line}`).join(', ');
|
||||
const sortByPlace = (a, b) => where(a.defs).localeCompare(where(b.defs), undefined, { numeric: true });
|
||||
|
||||
if (productionMode && testOnlyJs.length > 0) {
|
||||
console.log(`Referenced by tests only (${testOnlyJs.length}):`);
|
||||
for (const item of testOnlyJs.sort(sortByPlace)) {
|
||||
console.log(` ${item.name} ${where(item.defs)} (${item.inTests} mention${item.inTests === 1 ? '' : 's'} in test/)`);
|
||||
}
|
||||
console.log('');
|
||||
}
|
||||
|
||||
if (deadJs.length === 0 && deadCss.length === 0) {
|
||||
console.log(
|
||||
`✓ no unreferenced frontend code: ${byName.size} names in ${frontendFiles.length} scripts and the selectors of 2 stylesheets checked`
|
||||
);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (deadJs.length > 0) {
|
||||
console.error(`Unreferenced frontend functions and bindings (${deadJs.length}):`);
|
||||
for (const item of deadJs.sort(sortByPlace)) console.error(` ${item.name} ${where(item.defs)}`);
|
||||
}
|
||||
if (deadCss.length > 0) {
|
||||
console.error(`${deadJs.length > 0 ? '\n' : ''}CSS selectors nothing can produce (${deadCss.length}):`);
|
||||
for (const item of deadCss) console.error(` ${item.key} ${item.file}:${item.line}`);
|
||||
}
|
||||
console.error(
|
||||
'\nRemove each one, or add it to ALLOW in scripts/check-frontend-dead-code.mjs with the reason it stays.'
|
||||
);
|
||||
process.exit(1);
|
||||
@@ -1,17 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Generates timestamped data to a file for testing
|
||||
# Usage: ./scripts/data-generator.sh [output_file] [interval_seconds]
|
||||
# Then: tail -f /tmp/test-data.log
|
||||
|
||||
OUTPUT="${1:-/tmp/test-data.log}"
|
||||
INTERVAL="${2:-1}"
|
||||
|
||||
echo "Writing to $OUTPUT every ${INTERVAL}s (Ctrl+C to stop)"
|
||||
echo "Run: tail -f $OUTPUT"
|
||||
|
||||
i=0
|
||||
while true; do
|
||||
((i++))
|
||||
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Line $i - Random: $RANDOM" >> "$OUTPUT"
|
||||
sleep "$INTERVAL"
|
||||
done
|
||||
@@ -1,187 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Take mobile screenshots of Codeman using Playwright
|
||||
* Emulates iPhone 15 Pro (closest to iPhone 17 Pro)
|
||||
* Includes keyboard simulation
|
||||
*/
|
||||
|
||||
import { chromium, devices } from 'playwright';
|
||||
import { join, dirname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { mkdirSync } from 'fs';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const BASE_URL = 'http://localhost:3000';
|
||||
const OUTPUT_DIR = join(__dirname, '..', 'docs', 'screenshots');
|
||||
|
||||
// Ensure output directory exists
|
||||
try { mkdirSync(OUTPUT_DIR, { recursive: true }); } catch {}
|
||||
|
||||
// iPhone 15 Pro specs (closest to requested iPhone 17 Pro)
|
||||
// Screen: 393 x 852 at 3x = 1179 x 2556 physical pixels
|
||||
const VIEWPORT_WIDTH = 393;
|
||||
const VIEWPORT_HEIGHT = 852;
|
||||
const KEYBOARD_HEIGHT = 336; // Typical iOS keyboard height
|
||||
|
||||
const iPhone15Pro = {
|
||||
...devices['iPhone 14 Pro'],
|
||||
viewport: { width: VIEWPORT_WIDTH, height: VIEWPORT_HEIGHT },
|
||||
deviceScaleFactor: 3,
|
||||
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1',
|
||||
};
|
||||
|
||||
async function takeScreenshots() {
|
||||
console.log('Launching browser with iPhone 15 Pro emulation...');
|
||||
console.log('Output directory:', OUTPUT_DIR);
|
||||
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
const context = await browser.newContext({
|
||||
...iPhone15Pro,
|
||||
hasTouch: true,
|
||||
isMobile: true,
|
||||
});
|
||||
|
||||
const page = await context.newPage();
|
||||
|
||||
try {
|
||||
// Screenshot 1: Main view (no keyboard)
|
||||
console.log('Loading main page...');
|
||||
await page.goto(BASE_URL, { waitUntil: 'domcontentloaded', timeout: 10000 });
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
await page.screenshot({
|
||||
path: join(OUTPUT_DIR, 'mobile-no-keyboard.png'),
|
||||
fullPage: false
|
||||
});
|
||||
console.log('✓ Saved: mobile-no-keyboard.png');
|
||||
|
||||
// Screenshot 2: Simulate keyboard appearing
|
||||
console.log('Simulating virtual keyboard...');
|
||||
|
||||
// Trigger the keyboard handler manually - simulate what happens when keyboard shows
|
||||
await page.evaluate((keyboardHeight) => {
|
||||
// Add keyboard-visible class
|
||||
document.body.classList.add('keyboard-visible');
|
||||
|
||||
// Move toolbar up by keyboard height
|
||||
const toolbar = document.querySelector('.toolbar');
|
||||
if (toolbar) {
|
||||
toolbar.style.transform = `translateY(${-keyboardHeight}px)`;
|
||||
}
|
||||
|
||||
// Show and move accessory bar
|
||||
const accessoryBar = document.querySelector('.keyboard-accessory-bar');
|
||||
if (accessoryBar) {
|
||||
accessoryBar.classList.add('visible');
|
||||
accessoryBar.style.transform = `translateY(${-keyboardHeight}px)`;
|
||||
}
|
||||
|
||||
// Shrink main content area so terminal doesn't extend behind keyboard
|
||||
// Account for toolbar (40px) + accessory bar (44px)
|
||||
const main = document.querySelector('.main');
|
||||
if (main) {
|
||||
main.style.paddingBottom = `${keyboardHeight + 94}px`;
|
||||
}
|
||||
}, KEYBOARD_HEIGHT);
|
||||
|
||||
await page.waitForTimeout(300);
|
||||
|
||||
// Take screenshot of the reduced viewport (simulating keyboard up)
|
||||
await page.screenshot({
|
||||
path: join(OUTPUT_DIR, 'mobile-keyboard-visible.png'),
|
||||
fullPage: false
|
||||
});
|
||||
console.log('✓ Saved: mobile-keyboard-visible.png');
|
||||
|
||||
// Screenshot 3: Full view with keyboard overlay visualization
|
||||
// Reset viewport but keep toolbar position to show the effect
|
||||
await page.setViewportSize({
|
||||
width: VIEWPORT_WIDTH,
|
||||
height: VIEWPORT_HEIGHT
|
||||
});
|
||||
|
||||
// Add a visual keyboard overlay
|
||||
await page.evaluate((keyboardHeight) => {
|
||||
const overlay = document.createElement('div');
|
||||
overlay.id = 'keyboard-overlay';
|
||||
overlay.style.cssText = `
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: ${keyboardHeight}px;
|
||||
background: linear-gradient(to bottom, #2a2a2a 0%, #1a1a1a 100%);
|
||||
border-top: 1px solid #444;
|
||||
z-index: 9999;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-content: flex-start;
|
||||
padding: 8px 4px;
|
||||
gap: 4px;
|
||||
`;
|
||||
|
||||
// Add fake keyboard keys
|
||||
const rows = [
|
||||
'Q W E R T Y U I O P',
|
||||
'A S D F G H J K L',
|
||||
'⇧ Z X C V B N M ⌫',
|
||||
'123 🌐 space return'
|
||||
];
|
||||
|
||||
rows.forEach((row, rowIndex) => {
|
||||
const rowDiv = document.createElement('div');
|
||||
rowDiv.style.cssText = 'display: flex; width: 100%; justify-content: center; gap: 4px;';
|
||||
|
||||
row.split(' ').forEach(key => {
|
||||
const keyEl = document.createElement('div');
|
||||
const isSpecial = ['⇧', '⌫', '123', '🌐', 'space', 'return'].includes(key);
|
||||
const isSpace = key === 'space';
|
||||
const isReturn = key === 'return';
|
||||
|
||||
keyEl.style.cssText = `
|
||||
background: ${isSpecial ? '#3a3a3a' : '#505050'};
|
||||
color: #fff;
|
||||
border-radius: 5px;
|
||||
padding: ${isSpace ? '10px 60px' : isReturn ? '10px 20px' : '10px 8px'};
|
||||
font-size: ${rowIndex === 3 ? '12px' : '14px'};
|
||||
min-width: ${isSpace ? '120px' : isReturn ? '60px' : '28px'};
|
||||
text-align: center;
|
||||
box-shadow: 0 1px 0 #222;
|
||||
`;
|
||||
keyEl.textContent = isSpace ? '' : key;
|
||||
rowDiv.appendChild(keyEl);
|
||||
});
|
||||
|
||||
overlay.appendChild(rowDiv);
|
||||
});
|
||||
|
||||
document.body.appendChild(overlay);
|
||||
}, KEYBOARD_HEIGHT);
|
||||
|
||||
await page.waitForTimeout(200);
|
||||
|
||||
await page.screenshot({
|
||||
path: join(OUTPUT_DIR, 'mobile-with-keyboard.png'),
|
||||
fullPage: false
|
||||
});
|
||||
console.log('✓ Saved: mobile-with-keyboard.png');
|
||||
|
||||
// Screenshot 4: Toolbar close-up with keyboard
|
||||
const toolbar = page.locator('.toolbar');
|
||||
if (await toolbar.count() > 0) {
|
||||
await toolbar.screenshot({
|
||||
path: join(OUTPUT_DIR, 'mobile-toolbar-above-keyboard.png')
|
||||
});
|
||||
console.log('✓ Saved: mobile-toolbar-above-keyboard.png');
|
||||
}
|
||||
|
||||
console.log('\n✅ All screenshots saved to:', OUTPUT_DIR);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error taking screenshots:', error.message);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
}
|
||||
|
||||
takeScreenshots();
|
||||
@@ -1,124 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Respawn Controller Monitor - 12 hour monitoring script
|
||||
# Usage: ./scripts/monitor-respawn.sh <session_id> [duration_hours]
|
||||
|
||||
SESSION_ID="${1:-5ecdf859-3605-42d8-b0a2-f8f0a1b5ff98}"
|
||||
DURATION_HOURS="${2:-12}"
|
||||
ISSUES_FILE="/home/arkon/default/codeman/respawn-monitor-issues.md"
|
||||
FIXES_FILE="/home/arkon/default/codeman/respawn-monitor-fixes.md"
|
||||
API_URL="https://localhost:3000"
|
||||
POLL_INTERVAL=60 # seconds
|
||||
|
||||
# Calculate end time
|
||||
END_TIME=$(($(date +%s) + DURATION_HOURS * 3600))
|
||||
|
||||
log_issue() {
|
||||
local severity="$1"
|
||||
local message="$2"
|
||||
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
echo "" >> "$ISSUES_FILE"
|
||||
echo "### [$severity] $timestamp" >> "$ISSUES_FILE"
|
||||
echo "$message" >> "$ISSUES_FILE"
|
||||
echo "" >> "$ISSUES_FILE"
|
||||
}
|
||||
|
||||
add_fix() {
|
||||
local issue="$1"
|
||||
local fix="$2"
|
||||
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
echo "" >> "$FIXES_FILE"
|
||||
echo "### Issue: $issue" >> "$FIXES_FILE"
|
||||
echo "**Detected:** $timestamp" >> "$FIXES_FILE"
|
||||
echo "" >> "$FIXES_FILE"
|
||||
echo "**Proposed Fix:**" >> "$FIXES_FILE"
|
||||
echo "$fix" >> "$FIXES_FILE"
|
||||
echo "" >> "$FIXES_FILE"
|
||||
echo "---" >> "$FIXES_FILE"
|
||||
}
|
||||
|
||||
# State tracking
|
||||
PREV_STATE=""
|
||||
STATE_STUCK_COUNT=0
|
||||
PREV_CYCLE=0
|
||||
LAST_ACTIVITY=0
|
||||
AI_CHECK_ERRORS=0
|
||||
|
||||
echo "Starting respawn monitoring for session $SESSION_ID"
|
||||
echo "Duration: $DURATION_HOURS hours"
|
||||
echo "Issues logged to: $ISSUES_FILE"
|
||||
echo "Fixes logged to: $FIXES_FILE"
|
||||
|
||||
while [ $(date +%s) -lt $END_TIME ]; do
|
||||
# Get respawn status
|
||||
RESP=$(curl -sk "$API_URL/api/sessions/$SESSION_ID" 2>/dev/null)
|
||||
|
||||
if [ -z "$RESP" ]; then
|
||||
log_issue "ERROR" "API not responding - server may be down"
|
||||
add_fix "API not responding" "Check if codeman-web service is running:\n\`\`\`bash\nsystemctl --user status codeman-web\nsystemctl --user restart codeman-web\n\`\`\`"
|
||||
sleep $POLL_INTERVAL
|
||||
continue
|
||||
fi
|
||||
|
||||
# Parse response
|
||||
STATE=$(echo "$RESP" | jq -r '.respawn.state // "null"')
|
||||
CYCLE=$(echo "$RESP" | jq -r '.respawn.cycleCount // 0')
|
||||
ENABLED=$(echo "$RESP" | jq -r '.respawnEnabled // false')
|
||||
TOKENS=$(echo "$RESP" | jq -r '.respawn.config.lastTokenCount // 0')
|
||||
AI_STATUS=$(echo "$RESP" | jq -r '.respawn.detection.aiCheck.status // "unknown"')
|
||||
AI_ERRORS=$(echo "$RESP" | jq -r '.respawn.detection.aiCheck.consecutiveErrors // 0')
|
||||
TIME_SINCE_ACTIVITY=$(echo "$RESP" | jq -r '.respawn.timeSinceActivity // 0')
|
||||
CONFIDENCE=$(echo "$RESP" | jq -r '.respawn.detection.confidenceLevel // 0')
|
||||
SESSION_STATUS=$(echo "$RESP" | jq -r '.status // "unknown"')
|
||||
|
||||
# Check for issues
|
||||
|
||||
# 1. Session not running
|
||||
if [ "$SESSION_STATUS" = "stopped" ] || [ "$SESSION_STATUS" = "error" ]; then
|
||||
log_issue "CRITICAL" "Session status is '$SESSION_STATUS' - respawn may not function correctly"
|
||||
add_fix "Session stopped/error" "Check session health and restart if needed:\n\`\`\`bash\ncurl -sk $API_URL/api/sessions/$SESSION_ID\n# If needed, create new session or restart\n\`\`\`"
|
||||
fi
|
||||
|
||||
# 2. Respawn disabled unexpectedly
|
||||
if [ "$ENABLED" = "false" ] && [ "$PREV_STATE" != "" ] && [ "$PREV_STATE" != "null" ]; then
|
||||
log_issue "WARNING" "Respawn appears to have been disabled (was in state: $PREV_STATE)"
|
||||
add_fix "Respawn disabled" "Re-enable respawn controller:\n\`\`\`bash\ncurl -sk -X POST $API_URL/api/sessions/$SESSION_ID/respawn/enable\n\`\`\`"
|
||||
fi
|
||||
|
||||
# 3. State stuck for too long (>30 minutes in same state)
|
||||
if [ "$STATE" = "$PREV_STATE" ] && [ "$STATE" != "watching" ]; then
|
||||
STATE_STUCK_COUNT=$((STATE_STUCK_COUNT + 1))
|
||||
if [ $STATE_STUCK_COUNT -ge 30 ]; then # 30 minutes
|
||||
log_issue "WARNING" "State stuck in '$STATE' for $STATE_STUCK_COUNT minutes. Detection: confidence=$CONFIDENCE, timeSinceActivity=${TIME_SINCE_ACTIVITY}ms"
|
||||
add_fix "State stuck in $STATE" "The respawn controller may be stuck. Options:\n1. Check terminal for blocking prompts\n2. Send input to unstick:\n\`\`\`bash\ncurl -sk -X POST $API_URL/api/sessions/$SESSION_ID/input -d '{\"input\": \"\\\\r\"}'\n\`\`\`\n3. Restart respawn:\n\`\`\`bash\ncurl -sk -X POST $API_URL/api/sessions/$SESSION_ID/respawn/stop\ncurl -sk -X POST $API_URL/api/sessions/$SESSION_ID/respawn/start\n\`\`\`"
|
||||
STATE_STUCK_COUNT=0 # Reset to avoid spam
|
||||
fi
|
||||
else
|
||||
STATE_STUCK_COUNT=0
|
||||
fi
|
||||
|
||||
# 4. AI check errors
|
||||
if [ "$AI_ERRORS" -gt 2 ] && [ "$AI_ERRORS" -gt "$AI_CHECK_ERRORS" ]; then
|
||||
log_issue "WARNING" "AI idle check has $AI_ERRORS consecutive errors (status: $AI_STATUS)"
|
||||
add_fix "AI check errors" "AI idle checker is failing. Check:\n1. Claude CLI is working\n2. Sufficient context available\n3. Consider disabling AI check temporarily:\n\`\`\`bash\ncurl -sk -X POST $API_URL/api/sessions/$SESSION_ID/respawn/config -H 'Content-Type: application/json' -d '{\"aiIdleCheckEnabled\": false}'\n\`\`\`"
|
||||
AI_CHECK_ERRORS=$AI_ERRORS
|
||||
fi
|
||||
|
||||
# 5. Cycle completed - log success
|
||||
if [ "$CYCLE" -gt "$PREV_CYCLE" ] && [ "$PREV_CYCLE" -gt 0 ]; then
|
||||
log_issue "INFO" "Respawn cycle $CYCLE completed successfully (tokens: $TOKENS)"
|
||||
fi
|
||||
|
||||
# 6. Very high time since activity (>10 minutes) while not in watching state
|
||||
if [ "$TIME_SINCE_ACTIVITY" -gt 600000 ] && [ "$STATE" != "watching" ]; then
|
||||
log_issue "WARNING" "No activity for ${TIME_SINCE_ACTIVITY}ms while in state '$STATE' - may be stuck"
|
||||
fi
|
||||
|
||||
# Update tracking vars
|
||||
PREV_STATE="$STATE"
|
||||
PREV_CYCLE="$CYCLE"
|
||||
|
||||
sleep $POLL_INTERVAL
|
||||
done
|
||||
|
||||
log_issue "INFO" "Monitoring completed after $DURATION_HOURS hours"
|
||||
echo "Monitoring complete. Check $ISSUES_FILE and $FIXES_FILE"
|
||||
@@ -17,7 +17,7 @@
|
||||
* this script adds is FRESHNESS and independence from install time: a checkout
|
||||
* installed with `--ignore-scripts`, or one borrowing another tree's
|
||||
* `node_modules`, never ran postinstall, and an edit to the zerolag package after
|
||||
* install leaves the bundle stale. It runs as `pretest:mobile`.
|
||||
* install leaves the bundle stale. It runs as `pretest:mobile` and `pretest:browser`.
|
||||
*
|
||||
* Mirrors the vendor steps in scripts/build.mjs, targeting the source tree. Same
|
||||
* inputs and output names, so the page markup needs no test-only branch. That
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Ralph Loop Wizard Demo - runs through browser, leaves session running
|
||||
*/
|
||||
import { chromium } from 'playwright';
|
||||
import { readFileSync, existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
|
||||
const BASE_URL = 'https://localhost:3000';
|
||||
const CASE_NAME = 'codeman-ios';
|
||||
|
||||
async function main() {
|
||||
console.log('🎬 Starting Ralph Loop Wizard demo...\n');
|
||||
|
||||
// Launch browser (visible)
|
||||
const browser = await chromium.launch({
|
||||
headless: false,
|
||||
args: ['--no-sandbox', '--disable-setuid-sandbox', '--ignore-certificate-errors'],
|
||||
slowMo: 500, // Slow down so you can see what's happening
|
||||
});
|
||||
|
||||
const context = await browser.newContext({
|
||||
ignoreHTTPSErrors: true,
|
||||
});
|
||||
const page = await context.newPage();
|
||||
|
||||
console.log('📱 Opening Codeman web UI...');
|
||||
await page.goto(BASE_URL);
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
console.log('🔄 Clicking Ralph Loop button...');
|
||||
await page.waitForSelector('.btn-ralph', { timeout: 10000 });
|
||||
await page.click('.btn-ralph');
|
||||
|
||||
console.log('📋 Waiting for wizard modal...');
|
||||
await page.waitForSelector('#ralphWizardModal.active', { timeout: 10000 });
|
||||
|
||||
// Select case
|
||||
console.log(`📁 Selecting case: ${CASE_NAME}`);
|
||||
await page.selectOption('#ralphCaseSelect', CASE_NAME);
|
||||
|
||||
// Load initprompt.md if it exists
|
||||
const initPromptPath = join(homedir(), 'codeman-cases', CASE_NAME, 'initprompt.md');
|
||||
let taskDescription = 'Build an awesome iOS app for Codeman!';
|
||||
if (existsSync(initPromptPath)) {
|
||||
taskDescription = readFileSync(initPromptPath, 'utf-8').trim();
|
||||
console.log(`📝 Loaded initprompt.md (${taskDescription.length} chars)`);
|
||||
}
|
||||
|
||||
// Enter task description
|
||||
await page.fill('#ralphTaskDescription', taskDescription);
|
||||
|
||||
// Set completion phrase
|
||||
await page.evaluate(() => {
|
||||
const input = document.getElementById('ralphCompletionPhrase');
|
||||
if (input) input.value = 'IOS_APP_COMPLETE';
|
||||
});
|
||||
|
||||
console.log('➡️ Clicking Next (Step 1 → Step 2)...');
|
||||
await page.click('#ralphNextBtn');
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
// Check for existing plan
|
||||
const existingPlan = await page.$('#existingPlanSection:not(.hidden)');
|
||||
if (existingPlan) {
|
||||
console.log('📋 Existing plan detected, using it...');
|
||||
await page.evaluate(() => {
|
||||
const btns = Array.from(document.querySelectorAll('button'));
|
||||
const useBtn = btns.find(b => b.textContent?.includes('Use Existing'));
|
||||
if (useBtn) useBtn.click();
|
||||
});
|
||||
await page.waitForTimeout(500);
|
||||
}
|
||||
|
||||
console.log('➡️ Clicking Next (Step 2 → Step 3)...');
|
||||
await page.click('#ralphNextBtn');
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
console.log('🚀 Clicking Start Loop...');
|
||||
await page.click('#ralphStartBtn');
|
||||
|
||||
// Wait for session to be created
|
||||
console.log('⏳ Waiting for session to start...');
|
||||
await page.waitForSelector('.session-tab', { timeout: 30000 });
|
||||
|
||||
console.log('\n✅ Ralph Loop started! Session is running.');
|
||||
console.log('👀 Browser will stay open so you can observe.');
|
||||
console.log(' Press Ctrl+C in terminal when done.\n');
|
||||
|
||||
// Keep the script running
|
||||
await new Promise(() => {});
|
||||
}
|
||||
|
||||
main().catch(err => {
|
||||
console.error('Error:', err.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,171 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Start Ralph Loop on PRODUCTION server (port 3000) using E2E fixtures
|
||||
* Uses initprompt.md and @fix_plan.md from the case directory
|
||||
* Does NOT clean up - leaves session running for user verification
|
||||
*/
|
||||
import { chromium } from 'playwright';
|
||||
import { readFileSync, existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
|
||||
const BASE_URL = 'https://localhost:3000';
|
||||
const CASE_NAME = 'codeman-ios';
|
||||
const CASE_PATH = join(homedir(), 'codeman-cases', CASE_NAME);
|
||||
|
||||
async function main() {
|
||||
// Read initprompt.md
|
||||
const initPromptPath = join(CASE_PATH, 'initprompt.md');
|
||||
const fixPlanPath = join(CASE_PATH, '@fix_plan.md');
|
||||
|
||||
if (!existsSync(initPromptPath)) {
|
||||
console.error(`Missing: ${initPromptPath}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const taskDescription = readFileSync(initPromptPath, 'utf-8').trim();
|
||||
const hasFixPlan = existsSync(fixPlanPath);
|
||||
|
||||
console.log('=== Ralph Loop Wizard E2E (Production) ===');
|
||||
console.log(`Case: ${CASE_NAME}`);
|
||||
console.log(`initprompt.md: ${taskDescription.length} chars`);
|
||||
console.log(`@fix_plan.md exists: ${hasFixPlan}`);
|
||||
console.log('');
|
||||
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
args: ['--no-sandbox', '--disable-setuid-sandbox'],
|
||||
});
|
||||
|
||||
const context = await browser.newContext({ ignoreHTTPSErrors: true });
|
||||
const page = await context.newPage();
|
||||
|
||||
// Capture browser console logs
|
||||
page.on('console', msg => {
|
||||
if (msg.type() === 'error' || msg.text().includes('RalphWizard')) {
|
||||
console.log(`[Browser ${msg.type()}] ${msg.text()}`);
|
||||
}
|
||||
});
|
||||
page.on('pageerror', err => console.log(`[Browser Error] ${err.message}`));
|
||||
|
||||
try {
|
||||
console.log('[1/10] Navigating to Codeman...');
|
||||
await page.goto(BASE_URL, { timeout: 10000 });
|
||||
|
||||
console.log('[2/10] Clicking Ralph Loop button (.btn-ralph)...');
|
||||
await page.waitForSelector('.btn-ralph', { timeout: 5000 });
|
||||
await page.click('.btn-ralph');
|
||||
|
||||
console.log('[3/10] Waiting for wizard modal (#ralphWizardModal.active)...');
|
||||
await page.waitForSelector('#ralphWizardModal.active', { timeout: 5000 });
|
||||
|
||||
console.log(`[4/10] Selecting case: ${CASE_NAME}...`);
|
||||
await page.selectOption('#ralphCaseSelect', CASE_NAME);
|
||||
|
||||
console.log('[5/10] Filling task description from initprompt.md...');
|
||||
await page.fill('#ralphTaskDescription', taskDescription);
|
||||
|
||||
console.log('[6/10] Setting completion phrase: IOS_APP_COMPLETE...');
|
||||
await page.evaluate(() => {
|
||||
const input = document.getElementById('ralphCompletionPhrase');
|
||||
if (input) input.value = 'IOS_APP_COMPLETE';
|
||||
});
|
||||
|
||||
console.log('[7/10] Clicking Next -> Step 2...');
|
||||
await page.evaluate(() => {
|
||||
document.getElementById('ralphNextBtn')?.click();
|
||||
});
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
// Check for existing @fix_plan.md detection
|
||||
const existingPlanSection = await page.$('#existingPlanSection:not(.hidden)');
|
||||
if (existingPlanSection) {
|
||||
console.log('[8/10] Existing @fix_plan.md detected, clicking "Use Existing"...');
|
||||
await page.evaluate(() => {
|
||||
const btns = Array.from(document.querySelectorAll('button'));
|
||||
const useBtn = btns.find(b => b.textContent?.includes('Use Existing'));
|
||||
if (useBtn) useBtn.click();
|
||||
});
|
||||
await page.waitForTimeout(500);
|
||||
} else {
|
||||
console.log('[8/10] No existing plan section visible...');
|
||||
}
|
||||
|
||||
console.log('[9/10] Clicking Next -> Step 3 (Launch)...');
|
||||
await page.evaluate(() => {
|
||||
document.getElementById('ralphNextBtn')?.click();
|
||||
});
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
console.log('[10/10] Clicking Start Loop...');
|
||||
await page.evaluate(() => {
|
||||
document.getElementById('ralphStartBtn')?.click();
|
||||
});
|
||||
|
||||
console.log('Waiting for session tab to appear...');
|
||||
await page.waitForSelector('.session-tab', { timeout: 30000 });
|
||||
|
||||
// IMPORTANT: Wait for the wizard's async startRalphLoop() to complete
|
||||
// The wizard needs time to: wait for session ready, then send the prompt
|
||||
console.log('Waiting for wizard to send prompt (checking for busy status)...');
|
||||
|
||||
let session = null;
|
||||
let attempts = 0;
|
||||
const maxAttempts = 30; // 30 seconds max
|
||||
|
||||
while (attempts < maxAttempts) {
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
const sessions = await page.evaluate(async () => {
|
||||
const res = await fetch('/api/sessions');
|
||||
return res.json();
|
||||
});
|
||||
|
||||
session = sessions
|
||||
.filter(s => s.workingDir?.includes('codeman-ios'))
|
||||
.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))[0];
|
||||
|
||||
if (session) {
|
||||
// Check if session is working (prompt was sent)
|
||||
const detail = await page.evaluate(async (id) => {
|
||||
const res = await fetch(`/api/sessions/${id}`);
|
||||
return res.json();
|
||||
}, session.id);
|
||||
|
||||
if (detail.isWorking || detail.tokens?.total > 0) {
|
||||
console.log(`Session is working! Tokens: ${detail.tokens?.total}`);
|
||||
break;
|
||||
}
|
||||
console.log(` Attempt ${attempts + 1}: status=${detail.status}, tokens=${detail.tokens?.total || 0}`);
|
||||
}
|
||||
|
||||
attempts++;
|
||||
}
|
||||
|
||||
if (!session || attempts >= maxAttempts) {
|
||||
console.error('WARNING: Session may not have received the prompt!');
|
||||
}
|
||||
|
||||
console.log('');
|
||||
console.log('========================================');
|
||||
console.log('SUCCESS! Ralph Loop started.');
|
||||
console.log('========================================');
|
||||
console.log(`Session ID: ${session?.id}`);
|
||||
console.log(`Screen: codeman-${session?.id?.slice(0, 8)}`);
|
||||
console.log(`Status: ${session?.status}`);
|
||||
console.log('');
|
||||
console.log('Session is now running. View at: https://localhost:3000');
|
||||
console.log('');
|
||||
console.log('To delete when done:');
|
||||
console.log(` curl -sk -X DELETE "https://localhost:3000/api/sessions/${session?.id}"`);
|
||||
console.log('========================================');
|
||||
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(err => {
|
||||
console.error('FAILED:', err.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,109 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Start Ralph Loop via wizard on production server, leave it running
|
||||
*/
|
||||
import { chromium } from 'playwright';
|
||||
import { readFileSync, existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
|
||||
const BASE_URL = 'https://localhost:3000';
|
||||
const CASE_NAME = 'codeman-ios';
|
||||
|
||||
async function main() {
|
||||
console.log('Starting Ralph Loop via wizard on production server...\n');
|
||||
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
args: ['--no-sandbox', '--disable-setuid-sandbox', '--ignore-certificate-errors'],
|
||||
});
|
||||
|
||||
const context = await browser.newContext({ ignoreHTTPSErrors: true });
|
||||
const page = await context.newPage();
|
||||
|
||||
console.log('1. Opening Codeman web UI...');
|
||||
await page.goto(BASE_URL);
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
console.log('2. Clicking Ralph Loop button...');
|
||||
await page.waitForSelector('.btn-ralph', { timeout: 10000 });
|
||||
await page.click('.btn-ralph');
|
||||
|
||||
console.log('3. Waiting for wizard modal...');
|
||||
await page.waitForSelector('#ralphWizardModal.active', { timeout: 10000 });
|
||||
|
||||
console.log(`4. Selecting case: ${CASE_NAME}`);
|
||||
await page.selectOption('#ralphCaseSelect', CASE_NAME);
|
||||
|
||||
// Load initprompt.md
|
||||
const initPromptPath = join(homedir(), 'codeman-cases', CASE_NAME, 'initprompt.md');
|
||||
let taskDescription = 'Build an awesome iOS app for Codeman!';
|
||||
if (existsSync(initPromptPath)) {
|
||||
taskDescription = readFileSync(initPromptPath, 'utf-8').trim();
|
||||
console.log(`5. Loaded initprompt.md (${taskDescription.length} chars)`);
|
||||
} else {
|
||||
console.log('5. Using default task description');
|
||||
}
|
||||
|
||||
await page.fill('#ralphTaskDescription', taskDescription);
|
||||
|
||||
// Set completion phrase
|
||||
await page.evaluate(() => {
|
||||
const input = document.getElementById('ralphCompletionPhrase');
|
||||
if (input) input.value = 'IOS_APP_COMPLETE';
|
||||
});
|
||||
|
||||
console.log('6. Clicking Next (Step 1 -> Step 2)...');
|
||||
await page.click('#ralphNextBtn');
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
// Check for existing plan
|
||||
const existingPlan = await page.$('#existingPlanSection:not(.hidden)');
|
||||
if (existingPlan) {
|
||||
console.log('7. Existing plan detected, using it...');
|
||||
await page.evaluate(() => {
|
||||
const btns = Array.from(document.querySelectorAll('button'));
|
||||
const useBtn = btns.find(b => b.textContent?.includes('Use Existing'));
|
||||
if (useBtn) useBtn.click();
|
||||
});
|
||||
await page.waitForTimeout(500);
|
||||
} else {
|
||||
console.log('7. No existing plan, proceeding...');
|
||||
}
|
||||
|
||||
console.log('8. Clicking Next (Step 2 -> Step 3)...');
|
||||
await page.click('#ralphNextBtn');
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
console.log('9. Clicking Start Loop...');
|
||||
await page.click('#ralphStartBtn');
|
||||
|
||||
console.log('10. Waiting for session to be created...');
|
||||
await page.waitForSelector('.session-tab', { timeout: 30000 });
|
||||
|
||||
// Get session info from the API
|
||||
const sessions = await page.evaluate(async () => {
|
||||
const res = await fetch('/api/sessions');
|
||||
return res.json();
|
||||
});
|
||||
|
||||
const iosSession = sessions.find(s => s.workingDir?.includes('codeman-ios'));
|
||||
|
||||
console.log('\n========================================');
|
||||
console.log('SUCCESS! Ralph Loop started.');
|
||||
console.log('========================================');
|
||||
console.log(`Session ID: ${iosSession?.id}`);
|
||||
console.log(`Screen: codeman-${iosSession?.id?.slice(0, 8)}`);
|
||||
console.log(`Working Dir: ${iosSession?.workingDir}`);
|
||||
console.log('\nThe session is now running on your production server.');
|
||||
console.log('View it at: https://localhost:3000');
|
||||
console.log('Kill it when done via the web UI or: curl -X DELETE https://localhost:3000/api/sessions/' + iosSession?.id);
|
||||
console.log('========================================\n');
|
||||
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
main().catch(err => {
|
||||
console.error('Error:', err.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,166 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Browser test for clickable file links in Codeman terminal
|
||||
* Uses Playwright directly to ignore HTTPS errors
|
||||
*/
|
||||
|
||||
import { chromium } from 'playwright';
|
||||
|
||||
const BASE_URL = 'https://localhost:3000';
|
||||
const TEST_LOG_FILE = '/tmp/test-link-click.log';
|
||||
|
||||
async function main() {
|
||||
console.log('Starting browser test for clickable links...\n');
|
||||
|
||||
// Create test log file
|
||||
const { writeFileSync, appendFileSync } = await import('fs');
|
||||
writeFileSync(TEST_LOG_FILE, `=== Test started at ${new Date().toISOString()} ===\n`);
|
||||
for (let i = 1; i <= 10; i++) {
|
||||
appendFileSync(TEST_LOG_FILE, `Entry #${i} - ${Date.now()}\n`);
|
||||
}
|
||||
console.log(`Created test file: ${TEST_LOG_FILE}\n`);
|
||||
|
||||
// Launch browser ignoring HTTPS errors
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
args: ['--ignore-certificate-errors', '--ignore-ssl-errors']
|
||||
});
|
||||
|
||||
const context = await browser.newContext({
|
||||
ignoreHTTPSErrors: true
|
||||
});
|
||||
|
||||
const page = await context.newPage();
|
||||
|
||||
try {
|
||||
// Navigate to Codeman
|
||||
console.log('Navigating to Codeman...');
|
||||
await page.goto(BASE_URL, { waitUntil: 'networkidle', timeout: 30000 });
|
||||
console.log('Page loaded: ' + await page.title());
|
||||
|
||||
// Wait for terminal to be ready
|
||||
await page.waitForSelector('.xterm-screen', { timeout: 10000 });
|
||||
console.log('Terminal found\n');
|
||||
|
||||
// Get list of sessions
|
||||
const sessions = await page.evaluate(async () => {
|
||||
const res = await fetch('/api/sessions');
|
||||
return res.json();
|
||||
});
|
||||
console.log(`Found ${sessions.length} session(s)`);
|
||||
|
||||
if (sessions.length === 0) {
|
||||
console.log('No sessions found. Creating a shell session...');
|
||||
const newSession = await page.evaluate(async () => {
|
||||
const res = await fetch('/api/quick-start', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ caseName: 'link-test', mode: 'shell' })
|
||||
});
|
||||
return res.json();
|
||||
});
|
||||
console.log('Created session:', newSession.session?.id);
|
||||
await page.waitForTimeout(2000);
|
||||
}
|
||||
|
||||
// Get active session (use codeman session if exists)
|
||||
const codemanSession = sessions.find(s => s.workingDir?.includes('codeman'));
|
||||
const sessionId = codemanSession?.id || sessions[0]?.id;
|
||||
console.log(`Using session: ${sessionId}\n`);
|
||||
|
||||
// Send a command that outputs file paths
|
||||
console.log('Sending command with file path...');
|
||||
await page.evaluate(async (sid, logFile) => {
|
||||
await fetch(`/api/sessions/${sid}/input`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ input: `echo "Monitor: tail -f ${logFile}"\r` })
|
||||
});
|
||||
}, sessionId, TEST_LOG_FILE);
|
||||
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
// Take screenshot
|
||||
await page.screenshot({ path: '/tmp/codeman-link-test-1.png' });
|
||||
console.log('Screenshot saved: /tmp/codeman-link-test-1.png\n');
|
||||
|
||||
// Check if terminal contains our file path
|
||||
const terminalContent = await page.evaluate(() => {
|
||||
const screen = document.querySelector('.xterm-screen');
|
||||
return screen?.textContent || '';
|
||||
});
|
||||
|
||||
if (terminalContent.includes(TEST_LOG_FILE)) {
|
||||
console.log('File path appears in terminal output');
|
||||
} else {
|
||||
console.log('WARNING: File path not found in terminal. Content preview:');
|
||||
console.log(terminalContent.substring(0, 500));
|
||||
}
|
||||
|
||||
// Try to find clickable links in xterm
|
||||
const linkCount = await page.evaluate(() => {
|
||||
// xterm link detection happens on mouse move, so we need to trigger it
|
||||
const links = document.querySelectorAll('.xterm-link');
|
||||
return links.length;
|
||||
});
|
||||
console.log(`\nClickable links found: ${linkCount}`);
|
||||
|
||||
// Try hovering over the terminal to trigger link detection
|
||||
console.log('\nHovering over terminal to trigger link detection...');
|
||||
const termRect = await page.locator('.xterm-screen').boundingBox();
|
||||
if (termRect) {
|
||||
// Move mouse across the terminal
|
||||
for (let y = termRect.y + 50; y < termRect.y + termRect.height - 50; y += 20) {
|
||||
for (let x = termRect.x + 50; x < termRect.x + termRect.width - 50; x += 50) {
|
||||
await page.mouse.move(x, y);
|
||||
await page.waitForTimeout(50);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check for tooltip (shows when hovering over link)
|
||||
const tooltipVisible = await page.evaluate(() => {
|
||||
const tooltip = document.getElementById('file-link-tooltip');
|
||||
return tooltip?.style.display !== 'none' && tooltip?.style.display !== '';
|
||||
});
|
||||
console.log('Tooltip visible:', tooltipVisible);
|
||||
|
||||
// Check for log viewer windows
|
||||
const logViewerCount = await page.evaluate(() => {
|
||||
return document.querySelectorAll('.log-viewer-window').length;
|
||||
});
|
||||
console.log('Log viewer windows:', logViewerCount);
|
||||
|
||||
// Take final screenshot
|
||||
await page.screenshot({ path: '/tmp/codeman-link-test-2.png' });
|
||||
console.log('\nFinal screenshot: /tmp/codeman-link-test-2.png');
|
||||
|
||||
// Test the link provider registration
|
||||
console.log('\n--- Link Provider Debug ---');
|
||||
const debugInfo = await page.evaluate(() => {
|
||||
// Check if app has link provider registered
|
||||
const app = window.app;
|
||||
if (!app) return { error: 'No app object found' };
|
||||
|
||||
const terminal = app.terminals?.get(app.activeSessionId);
|
||||
if (!terminal) return { error: 'No active terminal', activeSessionId: app.activeSessionId };
|
||||
|
||||
return {
|
||||
hasTerminal: true,
|
||||
activeSessionId: app.activeSessionId,
|
||||
terminalBuffer: terminal.buffer?.active?.length || 0
|
||||
};
|
||||
});
|
||||
console.log('Debug info:', debugInfo);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error:', error.message);
|
||||
await page.screenshot({ path: '/tmp/codeman-link-test-error.png' });
|
||||
console.log('Error screenshot saved to /tmp/codeman-link-test-error.png');
|
||||
} finally {
|
||||
await browser.close();
|
||||
console.log('\nBrowser closed');
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -72,7 +72,7 @@ import { mkdtempSync, rmSync, readFileSync, existsSync } from 'node:fs';
|
||||
import { tmpdir, homedir } from 'node:os';
|
||||
import { join, delimiter, dirname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { enabledClis } from '../src/config/cli-registry/index.js';
|
||||
import { enabledClis } from '../src/config/cli-registry/registry.js';
|
||||
import type { CliEntry } from '../src/config/cli-registry/types.js';
|
||||
import {
|
||||
buildCustomModelInjection,
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Test script for link detection patterns
|
||||
*/
|
||||
|
||||
const patterns = {
|
||||
cmdPattern: /(tail|cat|head|less|grep|watch|multitail)\s+(?:[^\/\n]+?\s+)?(\/[^\s"'<>|;&\n\)]+)/g,
|
||||
bashPathPattern: /Bash\([^)]*?(\/(?:var|tmp|home|usr|etc|opt|log|logs)[^\s"'<>|;&\)\n]+)/g,
|
||||
generalPathPattern: /(\/(?:home|tmp|var|etc|usr|opt)[^\s"'<>|;&\n\)\]]+\.(?:log|txt|json|md|ts|js|sh|py|yaml|yml|csv|xml|html|css))/g,
|
||||
logPathPattern: /(\/var\/log\/[^\s"'<>|;&\n\)\]]+)/g,
|
||||
claudeOutputPattern: /(?:Created|Writing|Saved|File|Output|Streaming|Monitoring|Log)(?:\s+(?:file|to|at))?[:\s]+([\/~][^\s"'<>|;&\n\)]+)/gi
|
||||
};
|
||||
|
||||
const tests = [
|
||||
'tail -f /tmp/test.log',
|
||||
'tail -n 100 /var/log/syslog',
|
||||
'cat /home/user/file.txt',
|
||||
'head -n 10 /etc/passwd',
|
||||
'Bash(tail -f /tmp/test.log)',
|
||||
'Created file: /tmp/newfile.log',
|
||||
'Writing to /home/user/output.txt',
|
||||
'Monitoring file: /var/log/syslog',
|
||||
'Streaming /home/user/logs/app.log',
|
||||
'/home/arkon/project/file.log',
|
||||
'/tmp/test-output.txt',
|
||||
'echo "tail -f /tmp/test.log"',
|
||||
'The output is in /home/user/results.csv',
|
||||
'plain text without paths'
|
||||
];
|
||||
|
||||
console.log('Link Pattern Test Results\n');
|
||||
|
||||
for (const [name, pattern] of Object.entries(patterns)) {
|
||||
console.log(`\n=== ${name} ===`);
|
||||
console.log(`Pattern: ${pattern.source}\n`);
|
||||
|
||||
for (const test of tests) {
|
||||
pattern.lastIndex = 0;
|
||||
const matches = [];
|
||||
let m;
|
||||
while ((m = pattern.exec(test)) !== null) {
|
||||
// Get the captured group (varies by pattern)
|
||||
matches.push(m[1] || m[2]);
|
||||
}
|
||||
if (matches.length > 0) {
|
||||
console.log(` ✓ "${test}"`);
|
||||
console.log(` → Found: ${matches.join(', ')}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log('\n\n=== Combined Test ===');
|
||||
console.log('Testing all patterns on each input:\n');
|
||||
|
||||
for (const test of tests) {
|
||||
const allMatches = [];
|
||||
for (const [name, pattern] of Object.entries(patterns)) {
|
||||
pattern.lastIndex = 0;
|
||||
let m;
|
||||
while ((m = pattern.exec(test)) !== null) {
|
||||
const path = m[1] || m[2];
|
||||
if (path && !allMatches.includes(path)) {
|
||||
allMatches.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (allMatches.length > 0) {
|
||||
console.log(`✓ "${test}"`);
|
||||
console.log(` → ${allMatches.join(', ')}`);
|
||||
} else {
|
||||
console.log(`✗ "${test}" - no match`);
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Test script for clickable file links in Codeman terminal
|
||||
# Creates a log file and continuously writes timestamped data
|
||||
|
||||
LOGFILE="/tmp/codeman-test-$(date +%s).log"
|
||||
|
||||
echo "Created log file: $LOGFILE"
|
||||
echo ""
|
||||
echo "You can monitor this file with:"
|
||||
echo " tail -f $LOGFILE"
|
||||
echo ""
|
||||
echo "Starting to write data every 2 seconds..."
|
||||
echo ""
|
||||
|
||||
# Write initial content
|
||||
echo "=== Test Log Started at $(date) ===" > "$LOGFILE"
|
||||
|
||||
# Write data continuously
|
||||
count=0
|
||||
while true; do
|
||||
count=$((count + 1))
|
||||
echo "[$(date '+%H:%M:%S')] Entry #$count - Random: $RANDOM" >> "$LOGFILE"
|
||||
|
||||
# Print status every 5 entries
|
||||
if [ $((count % 5)) -eq 0 ]; then
|
||||
echo "Wrote $count entries to $LOGFILE"
|
||||
fi
|
||||
|
||||
sleep 2
|
||||
done
|
||||
@@ -1,179 +0,0 @@
|
||||
/**
|
||||
* Manual verification harness for the session-sidebar feature.
|
||||
*
|
||||
* Renders the real UI in headless Chromium against a testMode WebServer,
|
||||
* injects a synthetic 25-session fleet, and screenshots every layout state.
|
||||
* Not part of the automated suite — run it by hand:
|
||||
*
|
||||
* npx tsx scripts/verify-session-sidebar.mts
|
||||
*
|
||||
* SAFETY: uses the repo's own test harness (temp HOME, testMode server) on a
|
||||
* dedicated port. It never touches a real Codeman instance or tmux socket.
|
||||
*/
|
||||
import { chromium } from 'playwright';
|
||||
import { WebServer } from '../src/web/server.js';
|
||||
import { mkdirSync } from 'node:fs';
|
||||
import { mkdtempSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
|
||||
// Mirror test/setup.ts: isolate HOME before the app modules touch state.
|
||||
process.env.HOME = mkdtempSync(join(tmpdir(), 'codeman-sidebar-verify-'));
|
||||
process.env.VITEST = 'true';
|
||||
|
||||
const PORT = 3299;
|
||||
const OUT = process.env.SIDEBAR_SHOTS_DIR ?? join(tmpdir(), 'codeman-sidebar-shots');
|
||||
mkdirSync(OUT, { recursive: true });
|
||||
|
||||
// Generic on purpose: these names end up in the harness screenshots, so they
|
||||
// should not carry one contributor's project list into everyone else's review.
|
||||
// The mix of CLI modes matters (each renders a different badge); the names do not.
|
||||
const PROJECTS = [
|
||||
['api-server', 'claude'],
|
||||
['web-client', 'claude'],
|
||||
['mobile-app', 'codex'],
|
||||
['data-pipeline', 'claude'],
|
||||
['shared-lib', 'gemini'],
|
||||
['codeman', 'claude'],
|
||||
['docs-site', 'claude'],
|
||||
['batch-jobs', 'opencode'],
|
||||
['search-index', 'claude'],
|
||||
];
|
||||
const STATUSES = ['idle', 'busy', 'idle', 'busy', 'error', 'idle'];
|
||||
|
||||
function fleet(n: number) {
|
||||
const out: any[] = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
const [proj, mode] = PROJECTS[i % PROJECTS.length];
|
||||
const status = STATUSES[i % STATUSES.length];
|
||||
out.push({
|
||||
id: `sess-${String(i).padStart(4, '0')}-aaaa-bbbb-cccc-dddddddddddd`,
|
||||
pid: 10000 + i,
|
||||
status,
|
||||
workingDir: `${tmpdir()}/projects/${proj}`,
|
||||
name: `${proj}${i > 8 ? '-' + Math.floor(i / 9) : ''}`,
|
||||
mode,
|
||||
currentTaskId: null,
|
||||
createdAt: Date.now() - i * 60000,
|
||||
lastActivityAt: Date.now() - i * 1000,
|
||||
isWorking: status === 'busy',
|
||||
messageCount: i * 3,
|
||||
totalCost: 0,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
color: 'default',
|
||||
taskStats: { total: i % 4, running: i % 3 === 0 ? 2 : 0, completed: 0, failed: 0 },
|
||||
taskTree: [],
|
||||
tokens: { input: 0, output: 0, total: 0 },
|
||||
bufferStats: { terminalBufferSize: 0, textOutputSize: 0, messageCount: 0 },
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const SESSIONS = fleet(25);
|
||||
|
||||
async function main() {
|
||||
const server = new WebServer(PORT, false, true);
|
||||
await server.start();
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
const results: string[] = [];
|
||||
|
||||
async function shot(
|
||||
name: string,
|
||||
opts: { layout: 'header' | 'sidebar'; collapsed?: boolean; width: number; height: number; touch?: boolean }
|
||||
) {
|
||||
const ctx = await browser.newContext({
|
||||
viewport: { width: opts.width, height: opts.height },
|
||||
hasTouch: !!opts.touch,
|
||||
isMobile: !!opts.touch,
|
||||
deviceScaleFactor: 2,
|
||||
});
|
||||
const page = await ctx.newPage();
|
||||
const settings = JSON.stringify({ sessionListLayout: opts.layout });
|
||||
const collapsed = opts.collapsed === undefined ? null : opts.collapsed ? '1' : '0';
|
||||
await page.addInitScript(
|
||||
([s, c]) => {
|
||||
localStorage.setItem('codeman-app-settings', s as string);
|
||||
localStorage.setItem('codeman-app-settings-mobile', s as string);
|
||||
if (c !== null) localStorage.setItem('codeman-sidebar-collapsed', c as string);
|
||||
else localStorage.removeItem('codeman-sidebar-collapsed');
|
||||
},
|
||||
[settings, collapsed]
|
||||
);
|
||||
await page.goto(`http://localhost:${PORT}`, { waitUntil: 'domcontentloaded' });
|
||||
await page.waitForTimeout(1500);
|
||||
|
||||
await page.evaluate((list) => {
|
||||
const app = (window as any).app;
|
||||
if (!app) throw new Error('no window.app');
|
||||
app.sessions.clear();
|
||||
for (const s of list as any[]) app.sessions.set(s.id, s);
|
||||
// The renderer iterates sessionOrder, not the map.
|
||||
app.sessionOrder = (list as any[]).map((s) => s.id);
|
||||
app.activeSessionId = (list as any[])[3].id;
|
||||
// renderSessionTabs() is debounced; drive the immediate path directly.
|
||||
(app._fullRenderSessionTabs ?? app._renderSessionTabsImmediate)?.call(app);
|
||||
app.applySessionListLayout?.();
|
||||
}, SESSIONS as any);
|
||||
await page.waitForTimeout(600);
|
||||
|
||||
const info = await page.evaluate(() => {
|
||||
const root = document.documentElement;
|
||||
const aside = document.getElementById('sessionSidebar');
|
||||
const tabsEl = document.getElementById('sessionTabs');
|
||||
const asideBox = aside?.getBoundingClientRect();
|
||||
const cs = aside ? getComputedStyle(aside) : null;
|
||||
return {
|
||||
dataSessionList: root.dataset.sessionList ?? null,
|
||||
dataSidebar: root.dataset.sidebar ?? null,
|
||||
rows: document.querySelectorAll('.session-tab').length,
|
||||
tabsParent: tabsEl?.parentElement?.id || tabsEl?.parentElement?.className || null,
|
||||
asideWidth: asideBox ? Math.round(asideBox.width) : null,
|
||||
asideVisible: cs ? cs.display !== 'none' && cs.visibility !== 'hidden' : null,
|
||||
asideInert: aside?.hasAttribute('inert') ?? null,
|
||||
ariaHidden: aside?.getAttribute('aria-hidden') ?? null,
|
||||
toggleAriaExpanded: document.getElementById('sidebarToggleBtn')?.getAttribute('aria-expanded') ?? null,
|
||||
firstRowText:
|
||||
(document.querySelector('.session-tab') as HTMLElement | null)?.innerText
|
||||
?.trim()
|
||||
.replace(/\s+/g, ' ')
|
||||
.slice(0, 40) ?? null,
|
||||
listScrollable: (() => {
|
||||
const el = document.getElementById('sessionTabs');
|
||||
return el ? el.scrollHeight > el.clientHeight + 2 : null;
|
||||
})(),
|
||||
};
|
||||
});
|
||||
|
||||
await page.waitForTimeout(400);
|
||||
const file = join(OUT, `${name}.png`);
|
||||
await page.screenshot({ path: file });
|
||||
results.push(`${name.padEnd(28)} ${JSON.stringify(info)}`);
|
||||
await ctx.close();
|
||||
return info;
|
||||
}
|
||||
|
||||
await shot('01-header-desktop', { layout: 'header', width: 1600, height: 900 });
|
||||
await shot('02-sidebar-expanded', { layout: 'sidebar', collapsed: false, width: 1600, height: 900 });
|
||||
await shot('03-sidebar-collapsed-rail', { layout: 'sidebar', collapsed: true, width: 1600, height: 900 });
|
||||
await shot('04-sidebar-narrow-1000', { layout: 'sidebar', collapsed: true, width: 1000, height: 800 });
|
||||
await shot('05-sidebar-drawer-open-1000', { layout: 'sidebar', collapsed: false, width: 1000, height: 800 });
|
||||
await shot('06-sidebar-phone-closed', { layout: 'sidebar', collapsed: true, width: 393, height: 852, touch: true });
|
||||
await shot('07-sidebar-phone-open', { layout: 'sidebar', collapsed: false, width: 393, height: 852, touch: true });
|
||||
|
||||
console.log('\n=== RESULTS ===');
|
||||
for (const r of results) console.log(r);
|
||||
console.log(`\nScreenshots in ${OUT}`);
|
||||
|
||||
await browser.close();
|
||||
await server.stop();
|
||||
}
|
||||
|
||||
main().then(
|
||||
() => process.exit(0),
|
||||
(e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
}
|
||||
);
|
||||
@@ -190,11 +190,6 @@ export abstract class AiCheckerBase<
|
||||
*/
|
||||
protected abstract getNegativeVerdict(): V;
|
||||
|
||||
/**
|
||||
* Get the error verdict value.
|
||||
*/
|
||||
protected abstract getErrorVerdict(): V;
|
||||
|
||||
/**
|
||||
* Create an error result.
|
||||
*/
|
||||
|
||||
@@ -165,10 +165,6 @@ export class AiIdleChecker extends AiCheckerBase<AiCheckVerdict, AiIdleCheckConf
|
||||
return 'WORKING';
|
||||
}
|
||||
|
||||
protected getErrorVerdict(): AiCheckVerdict {
|
||||
return 'ERROR';
|
||||
}
|
||||
|
||||
protected createErrorResult(reasoning: string, durationMs: number): AiCheckResult {
|
||||
return { verdict: 'ERROR', reasoning, durationMs };
|
||||
}
|
||||
|
||||
@@ -139,10 +139,6 @@ export class AiPlanChecker extends AiCheckerBase<
|
||||
return 'NOT_PLAN_MODE';
|
||||
}
|
||||
|
||||
protected getErrorVerdict(): AiPlanCheckVerdict {
|
||||
return 'ERROR';
|
||||
}
|
||||
|
||||
protected createErrorResult(reasoning: string, durationMs: number): AiPlanCheckResult {
|
||||
return { verdict: 'ERROR', reasoning, durationMs };
|
||||
}
|
||||
|
||||
+11
-1
@@ -927,7 +927,7 @@ program
|
||||
|
||||
program
|
||||
.command('tui')
|
||||
.argument('[n]', 'attach straight to the nth session of `codeman tui --list`')
|
||||
.argument('[session]', 'attach straight to a session: its number in `codeman tui --list`, or its exact session name')
|
||||
.description('Terminal dashboard for your sessions (the web UI remains the primary surface)')
|
||||
.option('-l, --list', 'Print the numbered session list and exit, instead of opening the dashboard')
|
||||
.action(async (position: string | undefined, options: { list?: boolean }) => {
|
||||
@@ -940,6 +940,16 @@ program
|
||||
return;
|
||||
}
|
||||
if (position !== undefined) {
|
||||
// Digits only is a list number, as it always was; anything else is a session name.
|
||||
if (!/^\d+$/.test(position)) {
|
||||
if (position.trim() === '') {
|
||||
console.error(palette.err('An empty session name matches nothing.'));
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
process.exitCode = await runTuiAttach(position);
|
||||
return;
|
||||
}
|
||||
const n = Number.parseInt(position, 10);
|
||||
if (!Number.isSafeInteger(n) || n < 1) {
|
||||
console.error(palette.err(`"${position}" is not a session number.`));
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
* @module config/cli-registry/argv
|
||||
*/
|
||||
|
||||
import type { ArgSpec, CliEntry, CliLaunch, Cond, EngineValue, ParamSpec, QuoteStyle } from './types.js';
|
||||
import type { ArgSpec, CliLaunch, Cond, EngineValue, ParamSpec, QuoteStyle } from './types.js';
|
||||
import { matchesPattern } from './patterns.js';
|
||||
import { SAFE_BARE_TOKEN } from './patterns.js';
|
||||
|
||||
@@ -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;
|
||||
@@ -178,13 +189,3 @@ export function renderLaunch(
|
||||
|
||||
return rendered.join(' || ');
|
||||
}
|
||||
|
||||
/** Convenience: render an entry's launch command straight from a `CliEntry`. */
|
||||
export function renderCliCommand(
|
||||
entry: CliEntry,
|
||||
params: ParamValues,
|
||||
engineValues: EngineValues,
|
||||
gatesPassed?: ReadonlySet<string>
|
||||
): string {
|
||||
return renderLaunch(entry.launch, params, engineValues, gatesPassed);
|
||||
}
|
||||
@@ -3,59 +3,4 @@
|
||||
* @module config/cli-registry
|
||||
*/
|
||||
|
||||
export type {
|
||||
ArgSpec,
|
||||
CliCapabilities,
|
||||
CliCredStore,
|
||||
CliDiscovery,
|
||||
CliEntry,
|
||||
CliEnv,
|
||||
CliId,
|
||||
CliIdentityProbe,
|
||||
CliLaunch,
|
||||
CliOverlays,
|
||||
CliRegistryFile,
|
||||
CliVariant,
|
||||
CliVersionProbe,
|
||||
Cond,
|
||||
EngineValue,
|
||||
ParamSpec,
|
||||
QuoteStyle,
|
||||
} from './types.js';
|
||||
export {
|
||||
matchesPattern,
|
||||
TOKEN_PATTERNS,
|
||||
SAFE_BARE_TOKEN,
|
||||
compileVersionRegex,
|
||||
MAX_VERSION_OUTPUT,
|
||||
} from './patterns.js';
|
||||
export type { TokenPattern } from './patterns.js';
|
||||
export { renderLaunch, renderCliCommand } from './argv.js';
|
||||
export type { EngineValues, ParamValues } from './argv.js';
|
||||
export { CliEntrySchema } from './schema.js';
|
||||
export type { ValidatedCliEntry } from './schema.js';
|
||||
export { STOCK_CLIS } from './stock.js';
|
||||
export {
|
||||
asCliId,
|
||||
cliIds,
|
||||
enabledCliIds,
|
||||
enabledClis,
|
||||
getCli,
|
||||
listClis,
|
||||
loadCliRegistry,
|
||||
reloadCliRegistry,
|
||||
resolveInstallCommandForPlatform,
|
||||
resolveRegistry,
|
||||
} from './registry.js';
|
||||
export type { LoadResult } from './registry.js';
|
||||
export {
|
||||
COMPOSER_ANCHOR_KINDS,
|
||||
isKnownLauncherProfile,
|
||||
isKnownPredictProfile,
|
||||
isKnownSetenvProfile,
|
||||
LAUNCHER_PROFILE_NAMES,
|
||||
PREDICT_PROFILES,
|
||||
SETENV_PROFILE_NAMES,
|
||||
TRANSCRIPT_READER_NAMES,
|
||||
} from './profiles.js';
|
||||
export type { LauncherProfileName, SetenvProfileName } from './profiles.js';
|
||||
export { enabledCliIds, getCli } from './registry.js';
|
||||
@@ -77,16 +77,10 @@ export type LauncherProfileName = (typeof LAUNCHER_PROFILE_NAMES)[number];
|
||||
export type SetenvProfileName = (typeof SETENV_PROFILE_NAMES)[number];
|
||||
|
||||
/**
|
||||
* Transcript readers, selected via `capabilities.transcript`. Unlike the profile registries
|
||||
* above this one is closed over the schema enum itself rather than an open string, since
|
||||
* transcript format is a small, genuinely fixed set — see CliCapabilities['transcript'].
|
||||
* True when `name` is a predictive-echo profile this build actually implements.
|
||||
* Nothing calls it yet; it stays beside the registry it reads.
|
||||
* @knipignore
|
||||
*/
|
||||
export const TRANSCRIPT_READER_NAMES = ['claude-jsonl', 'codex-rollout', 'deepseek-zstd', 'none'] as const;
|
||||
|
||||
/** Composer-row finders, selected via `capabilities.echo.anchor.kind`. Also schema-closed. */
|
||||
export const COMPOSER_ANCHOR_KINDS = ['glyph', 'cursor', 'none'] as const;
|
||||
|
||||
/** True when `name` is a predictive-echo profile this build actually implements. */
|
||||
export function isKnownPredictProfile(name: string | undefined): boolean {
|
||||
return name !== undefined && Object.prototype.hasOwnProperty.call(PREDICT_PROFILES, name);
|
||||
}
|
||||
|
||||
@@ -32,18 +32,10 @@
|
||||
|
||||
import { existsSync, readFileSync, renameSync, statSync } from 'node:fs';
|
||||
import { dataPath } from '../instance.js';
|
||||
import type { CliEntry, CliId, CliRegistryFile } from './types.js';
|
||||
import type { CliEntry, CliRegistryFile } from './types.js';
|
||||
import { CliEntrySchema } from './schema.js';
|
||||
import { STOCK_CLIS } from './stock.js';
|
||||
|
||||
/** Construct a validated CliId. Throws if `raw` is not a well-formed id — call at API boundaries. */
|
||||
export function asCliId(raw: string): CliId {
|
||||
if (!/^[a-z][a-z0-9-]{0,23}$/.test(raw)) {
|
||||
throw new Error(`invalid CLI id: ${JSON.stringify(raw)}`);
|
||||
}
|
||||
return raw as CliId;
|
||||
}
|
||||
|
||||
function filePath(): string {
|
||||
return dataPath('clis.json');
|
||||
}
|
||||
@@ -227,10 +219,6 @@ export function getCli(id: string): CliEntry | undefined {
|
||||
return listClis().find((e) => (e.id as string) === id);
|
||||
}
|
||||
|
||||
export function cliIds(): string[] {
|
||||
return listClis().map((e) => e.id as string);
|
||||
}
|
||||
|
||||
/** Every enabled entry's id, in registry order. */
|
||||
export function enabledCliIds(): string[] {
|
||||
return enabledClis().map((e) => e.id as string);
|
||||
|
||||
@@ -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)) {
|
||||
@@ -817,5 +846,3 @@ export const CliEntrySchema = z
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export type ValidatedCliEntry = z.infer<typeof CliEntrySchema>;
|
||||
@@ -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' },
|
||||
@@ -303,8 +310,8 @@ const CLAUDE: CliEntry = {
|
||||
transcript: 'claude-jsonl',
|
||||
altScreen: 'strip-full',
|
||||
echo: { policy: 'buffer', anchor: { kind: 'glyph', glyph: '❯', offset: 2 } },
|
||||
// Declared-for-later: the live rule (`_shouldForwardWheelToApp`, terminal-ui.js) is this version
|
||||
// AND the server-published `cliMouseTracking` flag (#498), so wiring this field up needs both.
|
||||
// Read by `_shouldForwardWheelToApp` (terminal-ui.js) through `window.__codemanWheelForward`;
|
||||
// forwarding also needs the server-published `cliMouseTracking` flag (#498).
|
||||
wheelForward: { mode: 'version-gated', minVersion: '2.1.187' },
|
||||
// A repaint-mode Claude pane keeps no local history, so when the wheel is not
|
||||
// forwarded (older CLI, inline renderer, the local-scrollback opt-out) a scroll is
|
||||
@@ -1926,8 +1933,8 @@ const COPILOT: CliEntry = {
|
||||
// (`cliMouseTracking`). Same shape and reason as opencode. The wheel keeps working because
|
||||
// `_shouldForwardWheelToApp` forwards it as SGR reports while the CLI is tracking.
|
||||
altScreen: 'strip-mux-and-mouse',
|
||||
// Forwards the wheel as SGR reports while the CLI is tracking the mouse, at any version
|
||||
// (`_shouldForwardWheelToApp` in terminal-ui.js has no version check for copilot).
|
||||
// Forwards the wheel as SGR reports while the CLI is tracking the mouse, at any version:
|
||||
// `always` is what keeps `_shouldForwardWheelToApp` (terminal-ui.js) from checking one.
|
||||
wheelForward: { mode: 'always' },
|
||||
// Pages its own transcript on PageUp/PageDown (1.0.95, measured in tmux: three PageUp moved
|
||||
// lines 109-140 to 010-042 and PageDown returned). This is the fallback when the
|
||||
|
||||
@@ -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 };
|
||||
@@ -596,10 +614,18 @@ export interface CliCapabilities {
|
||||
* Forwarding the wheel to the CLI's own transcript. 'never' keeps local scrollback;
|
||||
* 'version-gated' forwards from `minVersion` on; 'always' forwards at any version. Either
|
||||
* forwarding mode applies only while the CLI has mouse tracking on (`cliMouseTracking`).
|
||||
* Read by the browser's gate (`_shouldForwardWheelToApp` in terminal-ui.js) through
|
||||
* `window.__codemanWheelForward`, which the server builds from this field for every CLI
|
||||
* whose mode is not `never`, disabled ones included (their running sessions stay open).
|
||||
*
|
||||
* ⚠️ Declared only: nothing reads this field yet (see DECLARED-FOR-LATER below). The browser's
|
||||
* gate is `_shouldForwardWheelToApp` in terminal-ui.js, which keeps its own hand-written
|
||||
* per-CLI rules, so changing a value here changes nothing until that gate is changed too.
|
||||
* ⚠️ 'version-gated' needs the session's `cliVersion`, and the server probes a version only
|
||||
* for an entry that declares `capabilities.gates` (`cliNeedsVersionProbe`, session.ts). An
|
||||
* entry without gates never forwards under 'version-gated', silently, so it uses 'always'.
|
||||
*
|
||||
* ⚠️ `cliMouseTracking` is only ever set for a CLI whose mouse DECSETs the server strips
|
||||
* (`altScreen: 'strip-full'` or `'strip-mux-and-mouse'`), so a forwarding mode on any other
|
||||
* `altScreen` never forwards: xterm keeps the DECSETs and encodes the wheel itself, until a
|
||||
* replay drops its mouse mode.
|
||||
*/
|
||||
wheelForward: { mode: 'never' | 'version-gated' | 'always'; minVersion?: string };
|
||||
/**
|
||||
@@ -1009,14 +1035,15 @@ export interface CliOverlays {
|
||||
/**
|
||||
* ⚠️ DECLARED-FOR-LATER: fields no code reads yet.
|
||||
*
|
||||
* `accent`, `overlays.credStore`, `capabilities.echo`, `capabilities.wheelForward`,
|
||||
* `capabilities.keyboardAccessory` and `capabilities.maxFrameBytes` all describe FRONTEND
|
||||
* `accent`, `overlays.credStore`, `capabilities.echo`, `capabilities.keyboardAccessory` and
|
||||
* `capabilities.maxFrameBytes` all describe FRONTEND
|
||||
* behaviour, and most of the frontend is deliberately untouched by the change that introduced
|
||||
* this registry — `app.js`, `terminal-ui.js`, `styles.css` and friends keep their own
|
||||
* hand-authored per-CLI rules, and moving them is its own piece of work with its own way of
|
||||
* being verified (a mobile/browser suite the CI gate cannot see). `shortBadge` graduated out of
|
||||
* this list (docs/cli-enable-disable-plan.md, Phase 2): `GET /api/clis` reads it for the
|
||||
* CLI-management Settings list.
|
||||
* CLI-management Settings list, and so did `capabilities.wheelForward`, which the browser's wheel
|
||||
* gate reads through `window.__codemanWheelForward`.
|
||||
*
|
||||
* They are declared now because each entry should describe its CLI completely, and because
|
||||
* transcribing them while the hand-written source is still on screen is when the values are
|
||||
|
||||
@@ -26,7 +26,8 @@
|
||||
* so a bad row fails the gate and never reaches the route.
|
||||
*
|
||||
* Where each figure of the stock rows comes from, and what was checked (2026-11-08; the two rows
|
||||
* added on 2026-11-10, `ornith:9b-q4_k_m` and `muse-glimmer:30b-q4_k_m`, were read that day).
|
||||
* added on 2026-11-10, `ornith:9b-q4_k_m` and `muse-glimmer:30b-q4_k_m`, were read that day;
|
||||
* `muse-glimmer:30b-mlx` was read and measured on 2026-11-12).
|
||||
* [V] read at the source that day, [M] measured on a Mac, [C] computed from [V] inputs:
|
||||
*
|
||||
* | Figure | Source | Checked |
|
||||
@@ -152,6 +153,26 @@
|
||||
* of many requests, in which the prefix snapshots may add up to 8 GiB. Its figures stay
|
||||
* the measured ones (with 8 GiB on top it would not be offered on the Mac it ran on),
|
||||
* and a 30-request session on it is the first thing to measure next.
|
||||
* Measured again on 2026-11-12 on the same Mac, from the runner's own log line
|
||||
* (`msg=memory peak=... held=...` after every request): 39,600 bytes per token between
|
||||
* prompts of 30,000 and 94,500 tokens, and the session this row owed, twelve separate
|
||||
* prompts of 15,000 tokens, added 0.5 GiB of prefix snapshots each (5.6 GiB after
|
||||
* twelve, still growing): the whole run ended at 33.4 GB of the 40.2 GB that Mac's
|
||||
* runtime measures. The row's figures are unchanged by it.
|
||||
* - `muse-glimmer:30b-mlx`: MEASURED the same way on that Mac (2026-11-12, runtime
|
||||
* 0.40.15). What stayed held grew by 37,900 to 45,100 bytes per token between prompts
|
||||
* of 30,000, 60,000 and 94,600 tokens. The 13 full-attention layers alone compute to
|
||||
* 13,312 in bf16 and all 52 layers at full length to 53,248, so the runner evidently
|
||||
* does not trim the 39 sliding-window layers to their window (an inference from the
|
||||
* figure, not read in its source). The row takes the upper end. It counts the whole
|
||||
* 8 GiB prefix budget, because the same run filled it: twelve separate prompts of
|
||||
* 15,000 tokens added 0.53 GiB each until the runner dropped the oldest. The process
|
||||
* (`footprint`) stood 0.2 GB above the runner's own count at the end. Its lifetime
|
||||
* peak stood 3.0 to 3.3 GB above that, which is a FLOOR for the peak of a long prompt:
|
||||
* a lifetime maximum taken at the end of the run hides a transient of up to 9 GB
|
||||
* during the earlier, longer prompts. So the row takes the first measured row's 5 GB.
|
||||
* The tag carries a draft model; its tensors are inside `bytes`, and what it holds is
|
||||
* inside these figures.
|
||||
* - every other `mlx` row: held = the K/V cache in bf16 + one recurrent snapshot per
|
||||
* 8,192 tokens, computed from the config, x 37,000 / 28,340: the ratio of what the
|
||||
* measured row really held to the same computation for it (same runner, same
|
||||
@@ -204,9 +225,15 @@
|
||||
* open, has it answer with thinking only in a long conversation at 65,536 tokens.
|
||||
* - `qwen3-coder-next` (51.7 GB): the generation before Qwen3.6. Its card shows its results
|
||||
* as pictures only, so there is no figure to rank it by against the rows listed here.
|
||||
* - `muse-glimmer:30b-mlx` and the `-dflash` tags of that model: open runtime issues 17656
|
||||
* and 18269 on the MLX build, and no rule here covers the memory of a separate draft
|
||||
* model. Its GGUF build `muse-glimmer:30b-q4_k_m` is listed.
|
||||
* - The `-dflash` tags of Muse Glimmer (`30b-q4_k_m-dflash`, `30b-nvfp4-dflash`): a separate
|
||||
* draft model whose memory no rule here covers. `muse-glimmer:30b-mlx`, which is built
|
||||
* from the second one's layers, IS listed since 2026-11-12, with measured figures. Its
|
||||
* two open runtime issues were read again that day: 17656 takes its `nvfp4` weights for
|
||||
* a build the MLX engine cannot accelerate (on the Mac it ran on the runtime logged
|
||||
* "MLX engine initialized ... device=gpu" and it wrote twice as fast as the GGUF build),
|
||||
* and 18269 reports it stuck in "Stopping..." and a restart on a 32 GB Mac, a size the
|
||||
* measured figures keep it away from (its maintainer promised a memory fix "in the next
|
||||
* release" in September; whether that predates the pinned 0.40.15 is not known).
|
||||
* - The plain tags `qwen3.5:9b`, `mimo-v2.6:9b` and `qwen3.8:27b`: a Mac pulls their MLX
|
||||
* builds, whose 8 GiB of prefix snapshots do not fit the Macs a 9B or a 27B is for. Their
|
||||
* GGUF builds are listed instead.
|
||||
@@ -407,13 +434,35 @@ const LLAMACPP_DEFAULT_DRAFT_TOKENS = 4;
|
||||
/** The prefix snapshots the MLX runner may keep: `maxPagedOutBytes`, 8 GiB. */
|
||||
const MLX_PREFIX_CACHE_BYTES = 8 * 1024 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* The memory figures measured for `muse-glimmer:30b-mlx` on the same Mac (2026-11-12, runtime
|
||||
* 0.40.15, the MLX runner), in decimal bytes: the runner's own `memory peak / held` log line
|
||||
* after every request, and the process footprint at the end. See the file header (MEMORY).
|
||||
*/
|
||||
const MUSE_MLX_MEASURED_MEMORY = {
|
||||
/** Held grew by 37,900 to 45,100 bytes per token between prompts of 30,000, 60,000 and 94,600 tokens: the upper end. */
|
||||
heldBytesPerToken: 45_000,
|
||||
/**
|
||||
* The prefix snapshots in full (the run filled them: 0.53 GiB per separate prompt of 15,000
|
||||
* tokens until the oldest was dropped), and 0.5 GB for what the process holds beside the
|
||||
* runner's own count (0.2 GB measured).
|
||||
*/
|
||||
overheadBytes: MLX_PREFIX_CACHE_BYTES + 500_000_000,
|
||||
/**
|
||||
* The first measured row's 5 GB. This run only gives a floor: the footprint's lifetime peak
|
||||
* stood 3.0 to 3.3 GB above what was held at the end, and a larger transient during the
|
||||
* earlier, longer prompts would not show in that figure.
|
||||
*/
|
||||
peakExtraBytes: 5_000_000_000,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* The catalogue that ships with Codeman. Never read directly outside this file and its test:
|
||||
* callers use `getLocalModelCatalog()`, which validates it first.
|
||||
*/
|
||||
export const STOCK_LOCAL_MODEL_CATALOG: LocalModelCatalog = {
|
||||
schema: 1,
|
||||
updated: '2026-11-10',
|
||||
updated: '2026-11-12',
|
||||
// The oldest macOS the model runtime supports.
|
||||
minMacosMajor: 14,
|
||||
// Ordered by rank. The higher rank wins among models that fit and whose speed is graded
|
||||
@@ -537,11 +586,43 @@ export const STOCK_LOCAL_MODEL_CATALOG: LocalModelCatalog = {
|
||||
figures: 'estimated',
|
||||
contexts: [131072, 65536],
|
||||
rank: 5,
|
||||
// Not measured: the 2.95 of Qwen3.8 27B, a dense model whose weights are the same size on
|
||||
// llama.cpp (16.8 GB each without the projector).
|
||||
// The 2.95 of Qwen3.8 27B, a dense model whose weights are the same size on llama.cpp
|
||||
// (16.8 GB each without the projector). Left there on purpose after the one run on a Mac
|
||||
// (M5 Pro, 2026-11-12): the runtime alone wrote 14.5 to 15.2 tokens per second, 4.8 per
|
||||
// 100 GB/s, but an OpenCode worker given one line (through the skill's `sendmark`, which
|
||||
// adds its answer-file sentence) showed no answer after 7 minutes, twice.
|
||||
speedPer100Gbps: 2.95,
|
||||
tested: [],
|
||||
},
|
||||
{
|
||||
// The same model as the MLX build: about twice as fast, because the tag carries a draft
|
||||
// model (the runtime logs "Loaded draft model", acceptance 0.34 to 0.62) and its own
|
||||
// renderer and tool parser. On the MacBook Pro (Mac17,13, M5 Pro, 48 GB, 2026-11-12) it
|
||||
// wrote 30.2 tokens per second where the GGUF build wrote 15.2 (the same 300-token
|
||||
// request), answered a tool call in under 3 seconds, and finished an OpenCode turn on
|
||||
// a one-line prompt in 45 seconds. The GGUF build above had shown nothing after 7
|
||||
// minutes on a one-line task (not the same prompt: see that row). The price is
|
||||
// memory: what the MLX runner holds grows six times as fast per token (MEMORY in the
|
||||
// file header), so this build starts at 48 GB and the 32 and 36 GB Macs keep the row
|
||||
// above. Not installed through the window yet, and no agent session beyond that turn:
|
||||
// no `tested` entry.
|
||||
id: 'muse-glimmer:30b-mlx',
|
||||
label: 'Muse Glimmer 30B (MLX)',
|
||||
license: 'Apache-2.0',
|
||||
paramsB: 29.6,
|
||||
runner: 'mlx',
|
||||
// The layers of its manifest, the draft model's included.
|
||||
bytes: 19_053_621_992,
|
||||
...MUSE_MLX_MEASURED_MEMORY,
|
||||
figures: 'measured',
|
||||
contexts: [131072, 65536],
|
||||
rank: 6,
|
||||
// Measured beside Qwen3.6 35B-A3B on MLX, same Mac, same request (a 1,500-token answer):
|
||||
// 32.6 against 101.9 tokens per second, so 0.32 of that row's 16.9. Like that row's, on
|
||||
// the low side: on 307 GB/s it computes to 16.6.
|
||||
speedPer100Gbps: 5.4,
|
||||
tested: [],
|
||||
},
|
||||
{
|
||||
// Macs of 36 GB on a slower chip: the model of the tested pair, as a GGUF build whose
|
||||
// memory does not grow after it loaded. With its multi-token-prediction layer.
|
||||
@@ -562,7 +643,7 @@ export const STOCK_LOCAL_MODEL_CATALOG: LocalModelCatalog = {
|
||||
peakExtraBytes: 0,
|
||||
figures: 'estimated',
|
||||
contexts: [262144, 131072, 65536],
|
||||
rank: 6,
|
||||
rank: 7,
|
||||
// Measured: 54.5 tokens per second on 400 GB/s (llama.cpp, without prediction).
|
||||
speedPer100Gbps: 13.6,
|
||||
tested: [],
|
||||
@@ -580,7 +661,7 @@ export const STOCK_LOCAL_MODEL_CATALOG: LocalModelCatalog = {
|
||||
...MEASURED_MEMORY,
|
||||
figures: 'measured',
|
||||
contexts: [131072, 65536],
|
||||
rank: 7,
|
||||
rank: 8,
|
||||
// Measured: 67.8 tokens per second on 400 GB/s with MLX. The one Mac we tested ran it at
|
||||
// 67.7 on 307 GB/s, so on other chips the estimate is on the low side.
|
||||
speedPer100Gbps: 16.9,
|
||||
@@ -605,7 +686,7 @@ export const STOCK_LOCAL_MODEL_CATALOG: LocalModelCatalog = {
|
||||
peakExtraBytes: 0,
|
||||
figures: 'estimated',
|
||||
contexts: [262144, 131072, 65536],
|
||||
rank: 8,
|
||||
rank: 9,
|
||||
// Not measured: the 2.95 of the row below scaled by file size.
|
||||
speedPer100Gbps: 1.7,
|
||||
tested: [],
|
||||
@@ -629,7 +710,7 @@ export const STOCK_LOCAL_MODEL_CATALOG: LocalModelCatalog = {
|
||||
peakExtraBytes: 0,
|
||||
figures: 'estimated',
|
||||
contexts: [262144, 131072, 65536],
|
||||
rank: 9,
|
||||
rank: 10,
|
||||
// Measured: 11.8 tokens per second on 400 GB/s (llama.cpp, Q4_K_M, without prediction).
|
||||
// This build predicts several tokens at a time, so it is faster than this figure says.
|
||||
speedPer100Gbps: 2.95,
|
||||
@@ -653,7 +734,7 @@ export const STOCK_LOCAL_MODEL_CATALOG: LocalModelCatalog = {
|
||||
peakExtraBytes: MEASURED_MEMORY.peakExtraBytes,
|
||||
figures: 'estimated',
|
||||
contexts: [262144, 131072],
|
||||
rank: 10,
|
||||
rank: 11,
|
||||
// Not measured: the 16.9 of Qwen3.6 35B-A3B on MLX x 3/10, its active parameters
|
||||
// against these, rounded down.
|
||||
speedPer100Gbps: 5,
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* @fileoverview The header CPU reading: CPU use over all cores since the previous reading, from each core's
|
||||
* busy and idle time as `os.cpus()` reports it (the kernel's per-core counters on Linux, macOS and Windows).
|
||||
*
|
||||
* It replaces the 1-minute load average divided by the core count. Load counts runnable tasks, not busy time,
|
||||
* so a host with bursty short-lived processes, or a VM whose vCPU threads count as runnable, read 100% while
|
||||
* most of its cores were idle.
|
||||
*/
|
||||
import type { CpuInfo } from 'node:os';
|
||||
|
||||
/** Readings closer together than this reuse the last value, so several open browsers never shrink the window. */
|
||||
export const CPU_USAGE_MIN_WINDOW_MS = 1000;
|
||||
|
||||
interface CpuTimes {
|
||||
busy: number;
|
||||
total: number;
|
||||
at: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* A meter that answers the CPU use, 0 to 100, between this reading and the previous one. Without usable core
|
||||
* times (none reported, or counters that went backwards, as when a core goes offline) it answers the last
|
||||
* reading, else `fallback()`. The first reading covers the time since the meter was created.
|
||||
*/
|
||||
export function createCpuUsageMeter(
|
||||
readCores: () => Pick<CpuInfo, 'times'>[],
|
||||
clock: () => number,
|
||||
fallback: () => number
|
||||
): () => number {
|
||||
const sample = (): CpuTimes => {
|
||||
let busy = 0;
|
||||
let total = 0;
|
||||
for (const { times } of readCores()) {
|
||||
const all = times.user + times.nice + times.sys + times.idle + times.irq;
|
||||
total += all;
|
||||
busy += all - times.idle;
|
||||
}
|
||||
return { busy, total, at: clock() };
|
||||
};
|
||||
let base = sample();
|
||||
let last: number | undefined;
|
||||
return () => {
|
||||
const now = sample();
|
||||
if (last !== undefined && now.at - base.at < CPU_USAGE_MIN_WINDOW_MS) return last;
|
||||
const busy = now.busy - base.busy;
|
||||
const total = now.total - base.total;
|
||||
base = now;
|
||||
if (!(total > 0) || busy < 0) return last ?? fallback();
|
||||
last = Math.min(100, Math.max(0, Math.round((busy / total) * 100)));
|
||||
return last;
|
||||
};
|
||||
}
|
||||
@@ -7,8 +7,6 @@
|
||||
import type { ConcurrencyPolicy, InputMode, PromptMode, ScheduleType } from '../types/cron.js';
|
||||
import type { SessionMode } from '../types/session.js';
|
||||
|
||||
export type { CronJob, CronJobRun, CronJobRunStatus, TriggerType } from '../types/cron.js';
|
||||
|
||||
export interface CronJobInput {
|
||||
name: string;
|
||||
agentType: SessionMode;
|
||||
|
||||
+263
-10
@@ -27,6 +27,11 @@
|
||||
* - **Failures reported, not swallowed.** The shell tab used to be where the
|
||||
* stack trace landed. With no tab, the spawn's own output is captured and
|
||||
* handed back to the caller instead.
|
||||
* - **The launch token traded, not forwarded.** `dsh web` gates its own index
|
||||
* behind a one-time token it prints on stdout and exchanges for a browser
|
||||
* cookie. The tab stores a clean URL, so nothing on the browser side could
|
||||
* ever present that token and every load answered 401. This module trades it
|
||||
* here, once, and hands the cookie to the proxy (`getDeepSeekWebCookie`).
|
||||
*/
|
||||
|
||||
import { spawn, type ChildProcess } from 'node:child_process';
|
||||
@@ -53,6 +58,23 @@ const READY_POLL_MS = 400;
|
||||
const KILL_GRACE_MS = 3_000;
|
||||
/** Bound on captured child output, so a chatty boot cannot grow without limit. */
|
||||
const OUTPUT_CAP = 16_384;
|
||||
/**
|
||||
* Bound on the boot-output window searched for the launch banner.
|
||||
*
|
||||
* Deliberately larger and separate from {@link OUTPUT_CAP}: that one only has to
|
||||
* keep an error tail, while this one must survive a chatty plugin tree's boot
|
||||
* logs long enough to see a banner printed after them. 256 KB of one-line output
|
||||
* is far beyond anything a real boot prints, and a bound still exists because a
|
||||
* wedged child can print forever.
|
||||
*/
|
||||
const BANNER_SCAN_CAP = 262_144;
|
||||
|
||||
/** How long boot waits for `dsh web` to print the launch URL it gates itself on. */
|
||||
const LAUNCH_URL_WAIT_MS = 4_000;
|
||||
/** Bound on the one-shot token→cookie exchange (loopback, so this is generous). */
|
||||
const TOKEN_EXCHANGE_TIMEOUT_MS = 5_000;
|
||||
/** Cookie name `dsh web` mints for a browser session that presented the token. */
|
||||
const DSH_AUTH_COOKIE_PREFIX = 'dsh-auth-';
|
||||
|
||||
export interface DeepSeekWebStatus {
|
||||
running: boolean;
|
||||
@@ -66,7 +88,33 @@ interface RunningServer {
|
||||
child: ChildProcess;
|
||||
port: number;
|
||||
authority: string;
|
||||
/**
|
||||
* Username of the Codeman user whose request started this server. Undefined in
|
||||
* single-user mode, where no owner exists. The cookie bought with the launch
|
||||
* token belongs to that identity and is presented to nobody else (see
|
||||
* `getDeepSeekWebCookie`).
|
||||
*/
|
||||
starter: string | undefined;
|
||||
output: () => string;
|
||||
/**
|
||||
* Boot output scanned for the launch banner, on its own (larger) budget than
|
||||
* `output`. Read through this rather than `output` so a banner printed after
|
||||
* the error-tail cap filled is still found.
|
||||
*/
|
||||
banner: () => string;
|
||||
/**
|
||||
* The `dsh-auth-*` cookie bought with this process's launch token, once the
|
||||
* exchange succeeded. Null on a dsh old enough to serve its index without a
|
||||
* token, which is why "no cookie" is not a startup failure.
|
||||
*/
|
||||
cookie: string | null;
|
||||
/**
|
||||
* True when a token-bearing banner was found but the exchange produced no
|
||||
* cookie. Such a server cannot authenticate its tab and must not be reused: the
|
||||
* warning tells the user to restart `dsh web`, and the next start request is
|
||||
* what performs that restart.
|
||||
*/
|
||||
cookieFailed: boolean;
|
||||
}
|
||||
|
||||
let current: RunningServer | null = null;
|
||||
@@ -105,6 +153,158 @@ async function answersHttp(port: number): Promise<boolean> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove SGR sequences so a coloured banner still parses.
|
||||
*
|
||||
* A coloured banner would otherwise hide the URL behind escape codes and turn a
|
||||
* perfectly working server into a 401.
|
||||
*/
|
||||
function stripSgr(output: string): string {
|
||||
// Built from the code point rather than written as `\x1b` so the linter's
|
||||
// no-control-regex rule does not read it as an accidental control character.
|
||||
return output.replace(new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, 'g'), '');
|
||||
}
|
||||
|
||||
/**
|
||||
* The first `dsh web:` payload that parses as an absolute http(s) URL.
|
||||
*
|
||||
* Lines whose payload is not a URL are skipped, which is what makes a
|
||||
* `dsh web: loading profiles` diagnostic harmless. `requireToken` skips an
|
||||
* http(s) URL that carries no `token` as well, so a diagnostic that happens to
|
||||
* contain a plain link cannot shadow the real banner. Null when no line qualifies.
|
||||
*/
|
||||
function firstLaunchBannerUrl(output: string, requireToken = false): string | null {
|
||||
// Fresh per call: a module-level /g pattern carries lastIndex between calls.
|
||||
const line = /dsh web:\s*(\S+)/g;
|
||||
for (const match of stripSgr(output).matchAll(line)) {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(match[1]);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
if (url.protocol !== 'http:' && url.protocol !== 'https:') continue;
|
||||
if (requireToken && !url.searchParams.get('token')) continue;
|
||||
return url.href;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The authenticated URL `dsh web` prints once it is up.
|
||||
*
|
||||
* Its browser-auth gate made the index private: boot writes
|
||||
* `dsh web: http://127.0.0.1:<port>/?token=<one-time token>` and only a request
|
||||
* carrying that token is answered with the cookie that authorizes everything
|
||||
* after it. The token is per process, so it can be neither guessed nor carried
|
||||
* across restarts — it has to be read out of the boot output.
|
||||
*
|
||||
* Scans EVERY `dsh web:` line and returns the first one that is a usable URL
|
||||
* carrying a token, because dsh also prints diagnostics under the same prefix
|
||||
* before the banner.
|
||||
*
|
||||
* Null for output without one, which is the older-dsh case and stays working.
|
||||
*
|
||||
* @param output - captured stdout+stderr so far.
|
||||
* @returns absolute http(s) URL carrying a `token`, or null.
|
||||
*/
|
||||
export function parseLaunchUrl(output: string): string | null {
|
||||
return firstLaunchBannerUrl(output, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a launch URL names the loopback port this supervisor just spawned.
|
||||
*
|
||||
* The URL is read from the child's output, but fetching it is a request made by
|
||||
* the SERVER. A banner naming another host, or another local service's port, must
|
||||
* not turn that exchange into an SSRF primitive, so the target is required to be
|
||||
* the exact origin the token was minted for.
|
||||
*/
|
||||
export function launchUrlTargetsServer(launchUrl: string, port: number): boolean {
|
||||
try {
|
||||
const url = new URL(launchUrl);
|
||||
const effectivePort = Number(url.port || (url.protocol === 'https:' ? 443 : 80));
|
||||
return url.hostname === '127.0.0.1' && effectivePort === port;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Trade the launch URL for the `dsh-auth-*` cookie the proxy will present.
|
||||
*
|
||||
* `redirect: 'manual'` is load-bearing: the 303 is the response that carries
|
||||
* `Set-Cookie`, and following it would burn the token on a redirect to `./`
|
||||
* while dropping the only credential the exchange produces.
|
||||
*
|
||||
* @param launchUrl - token-bearing URL from {@link parseLaunchUrl}.
|
||||
* @returns `name=value` pair ready for a Cookie header, or null.
|
||||
*/
|
||||
async function exchangeLaunchToken(launchUrl: string): Promise<string | null> {
|
||||
try {
|
||||
const response = await fetch(launchUrl, {
|
||||
redirect: 'manual',
|
||||
signal: AbortSignal.timeout(TOKEN_EXCHANGE_TIMEOUT_MS),
|
||||
});
|
||||
for (const header of response.headers.getSetCookie()) {
|
||||
const pair = header.split(';', 1)[0]?.trim();
|
||||
if (pair?.startsWith(DSH_AUTH_COOKIE_PREFIX)) return pair;
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for the banner, then exchange it.
|
||||
*
|
||||
* Never fails startup: a dsh without the gate prints a token-less banner, which
|
||||
* is answered as "nothing to exchange" immediately rather than after the whole
|
||||
* wait, and a gate that changes shape must not turn a serving UI into a boot
|
||||
* failure.
|
||||
*
|
||||
* @param running - the just-started server, read for its captured output.
|
||||
* @returns the cookie to hand the proxy (null when there is none) and whether a
|
||||
* token was printed but could not be exchanged.
|
||||
*/
|
||||
async function captureSessionCookie(running: RunningServer): Promise<{ cookie: string | null; failed: boolean }> {
|
||||
const deadline = Date.now() + LAUNCH_URL_WAIT_MS;
|
||||
while (Date.now() < deadline) {
|
||||
// Only COMPLETE lines: a chunk boundary can cut the token in half, and
|
||||
// exchanging a truncated one would burn the token on a request that cannot
|
||||
// authenticate. The next poll picks up the rest of the line.
|
||||
const banner = running.banner();
|
||||
const complete = banner.slice(0, banner.lastIndexOf('\n') + 1);
|
||||
const launchUrl = parseLaunchUrl(complete);
|
||||
if (launchUrl) {
|
||||
if (!launchUrlTargetsServer(launchUrl, running.port)) {
|
||||
console.warn(
|
||||
'[DeepSeek web] the printed launch URL does not name the loopback port this server was started on; ' +
|
||||
'not fetching it'
|
||||
);
|
||||
return { cookie: null, failed: true };
|
||||
}
|
||||
const cookie = await exchangeLaunchToken(launchUrl);
|
||||
// The URL is a credential: never log it, only the fact that it did not work.
|
||||
if (!cookie) {
|
||||
console.warn(
|
||||
'[DeepSeek web] the launch token was printed but could not be exchanged for a session cookie; ' +
|
||||
'the next start request will restart `dsh web` so it can retry'
|
||||
);
|
||||
return { cookie: null, failed: true };
|
||||
}
|
||||
return { cookie, failed: false };
|
||||
}
|
||||
// Only a printed http(s) URL settles this: it is the older dsh, which needs
|
||||
// no cookie. Any other line carrying the prefix (a diagnostic, a truncated
|
||||
// write) is not a banner, so the wait continues instead of giving up early.
|
||||
if (firstLaunchBannerUrl(complete)) return { cookie: null, failed: false };
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
return { cookie: null, failed: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* Signal the whole process group.
|
||||
*
|
||||
@@ -134,6 +334,25 @@ export function getDeepSeekWebStatus(): DeepSeekWebStatus {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The cookie this server's launch token bought, for the proxy to present.
|
||||
*
|
||||
* Keyed by `port` because the cookie is signed for the authority it was minted
|
||||
* under (`127.0.0.1:<port>`): handing it to a web tab pointed at some other
|
||||
* server would neither authenticate nor be that server's to receive. Null also
|
||||
* covers a dsh old enough to need no cookie at all.
|
||||
*
|
||||
* @param port - loopback port the upstream request is bound for.
|
||||
* @param owner - identity asking for it; must be the user who started the server.
|
||||
* Both sides are undefined in single-user mode, where there is no owner.
|
||||
* @returns `name=value` cookie pair, or null.
|
||||
*/
|
||||
export function getDeepSeekWebCookie(port: number, owner?: string): string | null {
|
||||
if (!current || current.port !== port) return null;
|
||||
if (current.starter !== owner) return null;
|
||||
return current.cookie;
|
||||
}
|
||||
|
||||
/** Stop the background server, if one is running. Safe to call when none is. */
|
||||
export async function stopDeepSeekWeb(): Promise<void> {
|
||||
const running = current;
|
||||
@@ -174,11 +393,12 @@ let startLock: Promise<unknown> = Promise.resolve();
|
||||
*
|
||||
* @param dshDir directory holding the resolved `dsh` binary.
|
||||
* @param authority browser authority to pass as `--trusted-host`.
|
||||
* @param starter user whose request is starting it (undefined in single-user).
|
||||
*/
|
||||
export function startDeepSeekWeb(dshDir: string, authority: string): Promise<StartResult> {
|
||||
export function startDeepSeekWeb(dshDir: string, authority: string, starter?: string): Promise<StartResult> {
|
||||
const run = startLock.then(
|
||||
() => startDeepSeekWebLocked(dshDir, authority),
|
||||
() => startDeepSeekWebLocked(dshDir, authority)
|
||||
() => startDeepSeekWebLocked(dshDir, authority, starter),
|
||||
() => startDeepSeekWebLocked(dshDir, authority, starter)
|
||||
);
|
||||
startLock = run.then(
|
||||
() => undefined,
|
||||
@@ -187,13 +407,24 @@ export function startDeepSeekWeb(dshDir: string, authority: string): Promise<Sta
|
||||
return run;
|
||||
}
|
||||
|
||||
async function startDeepSeekWebLocked(dshDir: string, authority: string): Promise<StartResult> {
|
||||
async function startDeepSeekWebLocked(
|
||||
dshDir: string,
|
||||
authority: string,
|
||||
starter: string | undefined
|
||||
): Promise<StartResult> {
|
||||
// Reuse only when the running server is BOTH healthy and fenced for the
|
||||
// authority now asking. A server trusting the other origin renders a page
|
||||
// whose every API call 403s, which looks like a broken dashboard rather than
|
||||
// a misconfigured one.
|
||||
// authority now asking, it was started by this identity, and its credential
|
||||
// works: the launch cookie is per process and per user, so handing a previous
|
||||
// starter's server to another user would leave that user's tab on dsh's 401
|
||||
// page, and a server whose token exchange failed would keep answering 401
|
||||
// forever because reuse never gave anyone a chance to restart it.
|
||||
if (current) {
|
||||
if (current.authority === authority && (await answersHttp(current.port))) {
|
||||
if (
|
||||
!current.cookieFailed &&
|
||||
current.authority === authority &&
|
||||
current.starter === starter &&
|
||||
(await answersHttp(current.port))
|
||||
) {
|
||||
return { ok: true, port: current.port, url: `http://127.0.0.1:${current.port}`, reused: true };
|
||||
}
|
||||
await stopDeepSeekWeb();
|
||||
@@ -223,8 +454,15 @@ async function startDeepSeekWebLocked(dshDir: string, authority: string): Promis
|
||||
// The pipes must be drained whether or not anyone reads them: a full pipe
|
||||
// blocks the child. Storage is capped; draining is not.
|
||||
let output = '';
|
||||
// Scanned for the launch banner separately from `output`. That cap exists to
|
||||
// bound the error tail, and a chatty profile can fill it before the banner is
|
||||
// printed — losing the banner there produces exactly the 401 tab this module
|
||||
// exists to prevent, so the two buffers must not share a limit.
|
||||
let banner = '';
|
||||
const capture = (chunk: Buffer) => {
|
||||
if (output.length < OUTPUT_CAP) output += chunk.toString('utf-8');
|
||||
const text = chunk.toString('utf-8');
|
||||
if (output.length < OUTPUT_CAP) output += text;
|
||||
if (banner.length < BANNER_SCAN_CAP) banner += text;
|
||||
};
|
||||
child.stdout?.on('data', capture);
|
||||
child.stderr?.on('data', capture);
|
||||
@@ -241,7 +479,16 @@ async function startDeepSeekWebLocked(dshDir: string, authority: string): Promis
|
||||
if (current?.child === child) current = null;
|
||||
});
|
||||
|
||||
const running: RunningServer = { child, port, authority, output: () => output };
|
||||
const running: RunningServer = {
|
||||
child,
|
||||
port,
|
||||
authority,
|
||||
starter,
|
||||
output: () => output,
|
||||
banner: () => banner,
|
||||
cookie: null,
|
||||
cookieFailed: false,
|
||||
};
|
||||
current = running;
|
||||
|
||||
const deadline = Date.now() + READY_TIMEOUT_MS;
|
||||
@@ -255,6 +502,12 @@ async function startDeepSeekWebLocked(dshDir: string, authority: string): Promis
|
||||
return { ok: false, error: tail ? `dsh web exited during startup: ${tail}` : 'dsh web exited during startup' };
|
||||
}
|
||||
if (await answersHttp(port)) {
|
||||
// Bought before this call resolves, so the first proxied page load
|
||||
// already carries a credential — a tab opened a moment earlier would
|
||||
// otherwise get the 401 this whole module exists to prevent.
|
||||
const captured = await captureSessionCookie(running);
|
||||
running.cookie = captured.cookie;
|
||||
running.cookieFailed = captured.failed;
|
||||
return { ok: true, port, url: `http://127.0.0.1:${port}`, reused: false };
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, READY_POLL_MS));
|
||||
|
||||
@@ -4,7 +4,10 @@
|
||||
* Split like webhook-notify.ts, so the parts that matter are testable without a network:
|
||||
* - pure: `sanitiseReply`, `threadNameFor`, `buildPost`, `discordConfigProblem`, `maskToken`
|
||||
* - store: `~/.codeman/discord.json` (bot token, 0600 via tmp+rename) and
|
||||
* `~/.codeman/discord-bridge.json` (sessionId -> threadId, not secret)
|
||||
* `~/.codeman/discord-bridge.json` (sessionId -> threadId, not secret) and
|
||||
* `~/.codeman/discord-reply-dedupe.json` (bounded reply IDs/timestamps, private).
|
||||
* Allowed replies are claimed before attachments or typing; store failures never cost a reply.
|
||||
* An unreadable file is never overwritten; invalid readable ID metadata can heal.
|
||||
* - IO: `DiscordApi` (REST, injected fetch), `DiscordGateway` (inbound WebSocket, injected
|
||||
* socket factory) and `DiscordBridge` (the rules that tie them to sessions)
|
||||
*
|
||||
@@ -27,6 +30,7 @@ import { join } from 'node:path';
|
||||
import { probePathKind } from './utils/bounded-path-probe.js';
|
||||
import { DISCORD_RECEIVED_DIR } from './web/paste-image-gc.js';
|
||||
import WebSocket from 'ws';
|
||||
import { DiscordReplyDedupe } from './discord-reply-dedupe.js';
|
||||
import { WEBHOOK_SCOPES, type WebhookUrgency } from './types/push.js';
|
||||
import {
|
||||
DISCORD_ON_DELETE,
|
||||
@@ -824,6 +828,7 @@ export interface DiscordBridgeDeps {
|
||||
}
|
||||
|
||||
export class DiscordBridge {
|
||||
private readonly replies: DiscordReplyDedupe;
|
||||
private cfg: DiscordConfig = { ...DEFAULT_DISCORD_CONFIG };
|
||||
private threads: Record<string, string> = {};
|
||||
private loaded = false;
|
||||
@@ -857,6 +862,7 @@ export class DiscordBridge {
|
||||
|
||||
constructor(private readonly deps: DiscordBridgeDeps) {
|
||||
this.now = deps.now ?? Date.now;
|
||||
this.replies = new DiscordReplyDedupe(deps.configDir, this.now);
|
||||
this.api = new DiscordApi(() => this.cfg.token, deps.fetchImpl, deps.sleep);
|
||||
}
|
||||
|
||||
@@ -1301,6 +1307,7 @@ export class DiscordBridge {
|
||||
if (!this.cfg.allowedUserIds.includes(m.author?.id)) return;
|
||||
const sessionId = Object.keys(this.threads).find((k) => this.threads[k] === m.channel_id);
|
||||
if (!sessionId) return;
|
||||
if (!(await this.replies.claim(m.guild_id, m.channel_id, m.id))) return;
|
||||
const t = this.now();
|
||||
const prev = this.lastReply.get(sessionId);
|
||||
if (prev !== undefined && t - prev < REPLY_MIN_INTERVAL_MS) {
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* @fileoverview Best-effort replay protection for Discord replies.
|
||||
*
|
||||
* Owns `<data dir>/discord-reply-dedupe.json`: at most 2,048 `guild:channel:message`
|
||||
* ids with the time each was claimed, kept for 7 days, written 0600 through a temp
|
||||
* file and a rename. It holds ids only, never message content.
|
||||
*
|
||||
* `DiscordBridge.handleMessage()` calls `claim()` once per allowed message, after the
|
||||
* guild, allowlist and thread gates and before the rate limit, the exited-agent check,
|
||||
* any download and any typing, so a gateway replay of a message that was refused is
|
||||
* refused again rather than typed.
|
||||
*
|
||||
* Rules a reader has to keep:
|
||||
* - A store failure never costs a reply: the claim falls back to memory, warns once
|
||||
* per outage and the reply is still typed.
|
||||
* - A file that could not be read (an errno failure, a symlink, anything but a regular
|
||||
* file) is never overwritten.
|
||||
* - Readable but invalid content (bad JSON, bad rows, oversized) is replaced.
|
||||
* - Rows read from disk go first, so claims made while the file was unreadable are
|
||||
* the ones the 2,048 bound keeps.
|
||||
*/
|
||||
import fs from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
const LIMIT = 2048;
|
||||
const RETENTION_MS = 7 * 24 * 60 * 60_000;
|
||||
export class DiscordReplyDedupe {
|
||||
private seen = new Map<string, number>();
|
||||
private loaded = false;
|
||||
private dirty = false;
|
||||
private warned = false;
|
||||
private chain: Promise<unknown> = Promise.resolve();
|
||||
constructor(
|
||||
private readonly dir: string,
|
||||
private readonly now: () => number = Date.now,
|
||||
private readonly warn: () => void = () =>
|
||||
console.warn('Discord reply metadata unavailable (discord-reply-dedupe.json); using in-memory deduplication')
|
||||
) {}
|
||||
claim(guild: string, channel: string, message: string): Promise<boolean> {
|
||||
const run = this.chain.then(() => this.take(guild, channel, message));
|
||||
this.chain = run.catch(() => undefined);
|
||||
return run;
|
||||
}
|
||||
private async take(guild: string, channel: string, message: string): Promise<boolean> {
|
||||
// Restored legacy configurations and malformed gateway IDs must not poison the store.
|
||||
if (![guild, channel, message].every((id) => /^\d{15,25}$/.test(id))) return true;
|
||||
const path = join(this.dir, 'discord-reply-dedupe.json');
|
||||
const cutoff = this.now() - RETENTION_MS;
|
||||
if (!this.loaded) {
|
||||
let contentRead = false;
|
||||
try {
|
||||
const st = await fs.lstat(path);
|
||||
if (!st.isFile() || st.isSymbolicLink()) throw Object.assign(new Error('Unsafe metadata'), { code: 'EINVAL' });
|
||||
if (st.size > 512 * 1024) {
|
||||
contentRead = true; // A known oversized regular file is invalid metadata, not an IO failure.
|
||||
throw new Error('Oversized metadata');
|
||||
}
|
||||
const text = await fs.readFile(path, 'utf8');
|
||||
contentRead = true;
|
||||
const rows: unknown = JSON.parse(text);
|
||||
if (!Array.isArray(rows) || rows.length > LIMIT) throw new Error('Invalid metadata');
|
||||
const recovered = new Map<string, number>();
|
||||
for (const row of rows) {
|
||||
if (!Array.isArray(row) || !/^\d{15,25}:\d{15,25}:\d{15,25}$/.test(row[0]) || !Number.isFinite(row[1]))
|
||||
throw new Error('Invalid metadata');
|
||||
if (row[1] >= cutoff) recovered.set(row[0], row[1]);
|
||||
}
|
||||
// Older disk rows precede newer claims made while reads were unavailable.
|
||||
this.seen = new Map([...recovered, ...this.seen]);
|
||||
this.loaded = true;
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code === 'ENOENT') this.loaded = true;
|
||||
else {
|
||||
this.report();
|
||||
// Invalid content is recoverable ID-only metadata; unreadable/unsafe files stay untouched.
|
||||
if (contentRead && !(err as NodeJS.ErrnoException).code) {
|
||||
this.loaded = true;
|
||||
this.dirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const [key, at] of this.seen) if (at < cutoff) this.seen.delete(key);
|
||||
const key = `${guild}:${channel}:${message}`;
|
||||
const fresh = !this.seen.has(key);
|
||||
if (fresh) {
|
||||
this.seen.set(key, this.now());
|
||||
this.dirty = true;
|
||||
} // Before awaiting IO or typing, including during an outage.
|
||||
while (this.seen.size > LIMIT) this.seen.delete(this.seen.keys().next().value!);
|
||||
if (!this.loaded || !this.dirty) return fresh; // Never overwrite a store file we could not read.
|
||||
const tmp = `${path}.${randomUUID()}.tmp`;
|
||||
try {
|
||||
await fs.mkdir(this.dir, { recursive: true });
|
||||
await fs.writeFile(tmp, JSON.stringify([...this.seen]), { mode: 0o600, flag: 'wx' });
|
||||
await fs.rename(tmp, path);
|
||||
this.warned = false;
|
||||
this.dirty = false;
|
||||
} catch {
|
||||
this.report();
|
||||
} finally {
|
||||
await fs.rm(tmp, { force: true }).catch(() => undefined);
|
||||
}
|
||||
return fresh;
|
||||
}
|
||||
private report(): void {
|
||||
if (!this.warned) this.warn();
|
||||
this.warned = true;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 283 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user