mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-20 13:09:33 +01:00
Compare commits
76
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5548c17c4a | ||
|
|
1d33220493 | ||
|
|
baf9d6a6a4 | ||
|
|
d00a8d6cbf | ||
|
|
a9ed3f55c3 | ||
|
|
acd90efe73 | ||
|
|
9d0f29fb22 | ||
|
|
6a5b818f65 | ||
|
|
507116f019 | ||
|
|
8202e07286 | ||
|
|
6222444e82 | ||
|
|
1207c316c0 | ||
|
|
923db64a10 | ||
|
|
756d8d875e | ||
|
|
f25e94141f | ||
|
|
c31e4fc716 | ||
|
|
99a69a87cf | ||
|
|
5df5628518 | ||
|
|
4344ce8c11 | ||
|
|
b732cec36d | ||
|
|
c7b6e1cb4e | ||
|
|
b5a356dadf | ||
|
|
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 | ||
|
|
10e443a309 | ||
|
|
e99b42c387 | ||
|
|
574eae72f3 | ||
|
|
75ea908f29 | ||
|
|
d44b049c51 | ||
|
|
259cabd738 | ||
|
|
f1b2a2ab75 | ||
|
|
03cb6a68b4 | ||
|
|
6fb8b27768 | ||
|
|
f604deba3e | ||
|
|
60f1900081 | ||
|
|
fa4815b465 | ||
|
|
a26be7c98f | ||
|
|
4423949923 | ||
|
|
5396e33b48 |
No files matched your search
@@ -10,7 +10,7 @@
|
||||
"name": "codeman",
|
||||
"source": "./plugins/codeman",
|
||||
"description": "Drive Codeman from inside a Claude Code session: spawn worker sessions, prompt them, wait for them, read their answers, clean up. Acts inside a Codeman-managed session; outside one it only reads saved Codex conversations offline.",
|
||||
"version": "1.51.0",
|
||||
"version": "1.51.1",
|
||||
"author": {
|
||||
"name": "Ark0N",
|
||||
"url": "https://github.com/Ark0N"
|
||||
|
||||
@@ -1,5 +1,43 @@
|
||||
# aicodeman
|
||||
|
||||
## 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.51.1 (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`.
|
||||
|
||||
@@ -158,6 +160,8 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
|
||||
**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)
|
||||
|
||||
**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)
|
||||
|
||||
**Auto-compact and auto-clear** (opt-in per session, Respawn tab; `session-auto-ops.ts`, pure decision `decideAutoThreshold()`): for a Claude session the size compared with the threshold is the context Claude Code reports on its statusline (`context_window.total_input_tokens`, cache reads included, handed over by `POST /api/status-telemetry` through `Session.noteContextReport()`); the session's token counter never sees the cached context and is only the fallback for a launch without the exporter. Thresholds go up to the reported window (`contextWindowSize`, 1M while unknown). ⚠️ After a `/compact` or `/clear` the report from before the command is ignored by VALUE, never for a length of time (a 601k compact took 39 s). ⚠️ The decision is made AGAIN when the command goes out (`_decideAtSend()`): a report fires the trigger in the middle of a turn, and the wait for that turn to end can outlast a compaction by Claude Code itself, so a `/clear` sent on the old answer would wipe a conversation that is small again. A skipped command stamps nothing. ⚠️ Nothing is sent into a usage-limit pause (`_heldByLimit()`, until auto-resume's `continue` went out), or that `continue` is typed into an empty conversation. → [architecture-invariants#auto-compact-and-auto-clear-thresholds](docs/architecture-invariants.md#auto-compact-and-auto-clear-thresholds)
|
||||
@@ -186,7 +190,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
|
||||
**External CLI modes (OpenCode, Codex, Gemini, Antigravity, Pi, Grok, DeepSeek, OMP, Copilot, jcode)**: `isExternalCliMode()` in `session.ts` gates Claude-specific behavior off (Ralph tracker, BashToolParser, token parsing, ❯ readiness; readiness is output stabilization); work detection is per-CLI `capabilities.workDetect` data, not this gate. All ten **require tmux, no direct PTY fallback** (secrets go via socket-scoped `tmux setenv`, never the command line). ⚠️ `run*()` in `session-ui.js` MUST unwrap the `{success,data}` envelope. ⚠️ **Codex uses predictive write-through echo, never the buffer overlay**: `_predictHookOnData` must never `return` (wire path stays byte-identical), and flushed text and a bracketed paste must go out as separate delayed writes. ⚠️ **Pi**: no bypass flag, never invent one; `approveProjectTrust` executes repo code, so it is in the clamp's **materialize** branch; never wire `--api-key`. ⚠️ **Grok**: `alwaysApprove` is stripped for non-granted owners (only-if-sent). ⚠️ **DeepSeek**: the agent is a PROFILE (Run gates on `isDeepSeekRunnable()`); the permission switch is the `DSH_PERMISSION_MODE` env var, so `clampEnvOverridesForOwner()` must DROP `DSH_PERMISSION_MODE`, `DSH_HOME` and `DEEPSEEK_BASE_URL` for non-granted owners; `hooksAvailableForMode()` is per-SESSION for it (pass `sessionHookOptions(session)`) and is never a stand-in for `mode === 'claude'`; answers come from `deepseek-transcript.ts`, paired by header `cwd` + boot window, never newest-mtime. ⚠️ **OMP**: `OMP_AUTH_BROKER_URL`/`_TOKEN` are clamped the same way. ⚠️ **Copilot**: `allowAll` (`--yolo`) is a `privilegedParam` and `COPILOT_HOME`/`COPILOT_ALLOW_ALL`/`COPILOT_PROVIDER_*`/`COPILOT_MODEL` are privileged env keys, and so is every other `COPILOT_*` variable the CLI reads that switches approvals, runs code with no approval row or sends its sign-in token elsewhere (the 1.0.98 list is in `stock.ts`; the prefix admits whatever a later release adds, so re-read the bundle whenever the measured version moves); the resume id must start with a letter or digit (`path-segment`), since `--resume`'s value is optional and `--resume --yolo` would otherwise make `--yolo` its own flag; `--name` is dropped next to `--resume`/`--continue` (Copilot refuses the pair); its mouse DECSETs are stripped (`strip-mux-and-mouse`) so a drag selects and the wheel is forwarded by `_shouldForwardWheelToApp` while `cliMouseTracking` is on; `composerReadyMark` is the footer hint `/ commands · ? help`, NOT `❯` (the folder-trust dialog draws `❯ 1. Yes`); `last-response` reads the pane's visible screen (`transcriptNeedsScreenCapture`) through a per-CLI `PANE_DIALECTS` row, because its stream is cursor moves, not lines (a prompt row scrolled off by a tall answer reads as the answer's tail unless a banner/trust dialog is on screen, and typed composer text is not a prompt); Docker seeds no Copilot credential (`config.json` holds a plain-text token without a keyring). ⚠️ **jcode**: every pane is a client of ONE shared per-user daemon and the tools run in the daemon with ITS env, so jcode gets no agent skill and no `JCODE_*` envOverrides prefix (a per-session value would act as another session or reach every one); `last-response` is an honest empty (external + `transcript: 'none'`, never the segmenter or the Claude scan); ⚠️ that daemon is a descendant of whichever pane started it, so `capabilities.sharedDaemon` makes `killSession` spare descendants outside the pane's process group (`descendantsInPaneGroup()`, `proc-tree.ts`), or closing that one tab cuts every other jcode session off; it resolves through the generic registry resolver, with no per-CLI resolver module (`docs/jcode-integration.md`). → [architecture-invariants#external-cli-modes-opencode-codex-gemini-antigravity-pi-grok-deepseek-omp](docs/architecture-invariants.md#external-cli-modes-opencode-codex-gemini-antigravity-pi-grok-deepseek-omp)
|
||||
|
||||
**DeepSeek web UI** (`POST`/`GET`/`DELETE /api/deepseek/web`, `deepseek-web-server.ts`): the Run menu's "DeepSeek web UI..." entry supervises ONE background `dsh web` child process, deliberately **NOT a shell session**. ⚠️ Every piece is load-bearing: exactly one server (a second click REUSES it), restarted when the browser authority changes (`--trusted-host`, last asker wins), killed on shutdown via `stopDeepSeekWeb()` (the detached child would otherwise outlive Codeman and hold its port), and failures returned to the caller. ⚠️ Never hardcode the port: search from 3080 across 40, detect free ports by BINDING, then wait for the server to really answer. ⚠️ Both `POST` and `DELETE` must stay behind `canUsernameRunPrivilegedCommands` (booting a profile runs its plugin code; the server is shared). → [architecture-invariants#deepseek-web-ui](docs/architecture-invariants.md#deepseek-web-ui)
|
||||
**DeepSeek web UI** (`POST`/`GET`/`DELETE /api/deepseek/web`, `deepseek-web-server.ts`): the Run menu's "DeepSeek web UI..." entry supervises ONE background `dsh web` child process, deliberately **NOT a shell session**. ⚠️ Every piece is load-bearing: exactly one server (a second click REUSES it, but only for the same starter and while its cookie works), restarted when the browser authority changes (`--trusted-host`, last asker wins), killed on shutdown via `stopDeepSeekWeb()` (the detached child would otherwise outlive Codeman and hold its port), and failures returned to the caller. ⚠️ Never hardcode the port: search from 3080 across 40, detect free ports by BINDING, then wait for the server to really answer. ⚠️ Both `POST` and `DELETE` must stay behind `canUsernameRunPrivilegedCommands` (booting a profile runs its plugin code; the server is shared). ⚠️ The launch token is traded for dsh's session cookie once at startup, and the web-tab proxy presents it on both legs only to the `managed: 'deepseek-web'` tab on the `127.0.0.1` port it was minted for (in multi-user mode, only to a granted owner who started it). → [architecture-invariants#deepseek-web-ui](docs/architecture-invariants.md#deepseek-web-ui)
|
||||
|
||||
**Case rename** (`POST /api/cases/:name/rename`, `src/case-rename.ts`; `docs/wiki/Core-Concepts.md#case`): a case under the cases dir is its folder name and always moves; a linked case renames its alias and moves its real folder only with `renameFolder`; remote and Docker cases are refused. ⚠️ A folder that sessions have open is the hazard: live sessions at or under it make the route answer `409 requiresStop` with their names, and only `stopSessions: true` ends them (via `ctx.cleanupSession`: closed like a tab close, uploads included, nothing is restarted); the free-target pre-check runs before that and refuses a dangling symlink too (`lstat`, as `moveCaseFolder` does), so no session is ended for a move that cannot happen. `withCaseLock` holds the old and new paths for the whole operation (`isCasePathLocked`; the `Session` constructor throws for a working directory inside a held path, so nothing is constructed mid-move). ⚠️ A create awaits the owner's layout lock and a settings read between `new Session` and the server's map, where the rename looks for open sessions, so the constructor also records the session (`noteCaseSessionStarting`) until `registerSessionWithLayout()` or `stop()` settles it (30 s TTL for one that never registers), and a folder move refuses `409` with `renameCode: "BUSY"` while one is recorded at or under the folder (`isCaseSessionStarting`, checked in the same tick that takes the lock); an alias-only rename is not refused. A create whose path was validated before the move but whose `Session` is constructed after it is not covered (the plain check-then-use race of any create path), `moveCaseFolder` refuses an existing target itself (POSIX `rename` would silently replace an EMPTY directory) and retries `EBUSY`/`EPERM`/`EACCES` before answering `423 LOCKED`. If the registries (`linked-cases.json`, `caseOrder`, `lastUsedCase`, `lastPickedCase`, `caseSettings`) fail after the move, `settings.json` and the folder are put back (a failed move-back says the folder is now at the new path), and an error after `stopSessions` carries `stoppedSessions`. Claude Code keys history by path (`claudeProjectDirName`: every non-alphanumeric becomes `-`), so `<claude config>/projects/<old>` is renamed too, or merged entry by entry, never overwriting, into one already at the new key (case delete never removes history, so an earlier case of the new name leaves one); other CLIs' history, Docker bind mounts, `git worktree` links, cron jobs' `workingDir`, Claude history of subfolder sessions and Claude Code's per-project entry in `~/.claude.json` (local-scope `mcpServers`, `allowedTools`, trust; writing another CLI's config is the opt-in MCP sync's job) are NOT migrated. The history scanner prefers the decoded project key over a transcript's `cwd` that no longer exists, so Resume follows a rename. Only an admin's rename touches the server-wide `settings.json` (`caseOrder`, `lastUsedCase`, `lastPickedCase`, `caseSettings`); the owner's default session group is carried across with `TabLayoutService`. `settings.json` is written before `linked-cases.json`, so a failed or refused registry write puts `settings.json` back and leaves the registry as it was. ⚠️ Every write to `linked-cases.json` (link, unlink, rename, and a create or clone into a custom folder) goes through `mutateLinkedCases()` (`src/web/linked-cases-writer.ts`: serialized, temp file + rename, and a file that does not parse is refused, never read as `{}`; the one direct writer is config-backup restore, `restoreConfigBackup()`, which must work on such a file), and a check that must still hold when the entry is written (the name is free; for a rename, the old entry still names the folder) runs INSIDE its callback: two clones that claimed one name used to both pass a re-read made outside it and both answer success. Pinned by `test/linked-cases-writer.test.ts`, and for a rename by `test/routes/case-rename-routes.test.ts`.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -226,7 +230,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
|
||||
**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)
|
||||
|
||||
**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)
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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.51.1",
|
||||
"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.51.1",
|
||||
"transport": {
|
||||
"type": "stdio"
|
||||
},
|
||||
|
||||
+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() {
|
||||
|
||||
@@ -18,7 +18,7 @@ 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
|
||||
|
||||
### Reverse-proxy base path
|
||||
|
||||
@@ -41,7 +41,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 +135,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.
|
||||
|
||||
@@ -149,7 +149,7 @@ Spawn commands are pinned as literal strings in `test/cli-registry-spawn-golden.
|
||||
|
||||
### 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.
|
||||
|
||||
@@ -267,7 +267,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.
|
||||
|
||||
@@ -682,6 +682,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×.
|
||||
@@ -1123,7 +1125,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 +1141,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.
|
||||
|
||||
@@ -1255,7 +1259,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 +1273,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.
|
||||
|
||||
@@ -1299,6 +1303,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 +1327,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 +1345,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
|
||||
|
||||
@@ -1549,3 +1555,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
|
||||
|
||||
@@ -300,7 +300,7 @@ This matters because it is invisible when it is wrong. `capabilities.privilegedP
|
||||
|
||||
## Fields declared for later
|
||||
|
||||
`accent`, `capabilities.echo`, `capabilities.wheelForward`, `capabilities.keyboardAccessory` and `capabilities.maxFrameBytes` are **declared but not yet read**. (`shortBadge` was on this list until the CLI management list in Settings started showing it.) They all describe frontend behaviour, and the frontend is deliberately untouched here: `app.js`, `terminal-ui.js` and `styles.css` keep their own hand-authored per-CLI rules, and moving them is its own piece of work verified by a browser/mobile suite the CI gate cannot see.
|
||||
`accent`, `capabilities.echo`, `capabilities.keyboardAccessory` and `capabilities.maxFrameBytes` are **declared but not yet read**. (`shortBadge` was on this list until the CLI management list in Settings started showing it, and `capabilities.wheelForward` until the browser's wheel gate started reading it, see below.) They all describe frontend behaviour, and the frontend is deliberately untouched here: `app.js`, `terminal-ui.js` and `styles.css` keep their own hand-authored per-CLI rules, and moving them is its own piece of work verified by a browser/mobile suite the CI gate cannot see.
|
||||
|
||||
Treat those values as **transcribed, not authoritative** — nothing enforces that `echo.policy` matches `_updateLocalEchoState`'s fallthrough, so re-measure before wiring one up. `accent` is the one exception: it was measured against styles.css on 2026-09-21 (method in the comment above `CLAUDE` in `stock.ts`), though nothing keeps it in step with the CSS either. A field that is both wrong and unread is worse than an absent one, because the next reader trusts it; `test/cli-registry-no-id-branching.test.ts` pins the list so it cannot quietly grow, and wiring one up makes its line there fail, which is the direction you want.
|
||||
|
||||
@@ -308,6 +308,10 @@ Treat those values as **transcribed, not authoritative** — nothing enforces th
|
||||
|
||||
Everything else in the interface is live, including `overlays.remote` / `overlays.docker`, which back `defaultRemoteCommandForMode()` and `defaultDockerCommandForMode()` directly. Those two used to be hardcoded `Record<…CommandMode, string>` tables duplicating the registry with nothing keeping the two in step; `test/location-overlay-commands.test.ts` pins every resulting command as a literal string.
|
||||
|
||||
### Wheel forwarding for a custom full-screen CLI
|
||||
|
||||
`capabilities.wheelForward` reaches the browser as `window.__codemanWheelForward` (id to rule, every CLI whose mode is not `never`, disabled ones included, since disabling a CLI leaves its running sessions open), and `_shouldForwardWheelToApp` in terminal-ui.js reads only that map, so a custom entry gets the same wheel as a stock one under its own id. A full-screen TUI that turns mouse tracking on itself (a wrapper around pi, for example) needs two values in its `clis.json` entry, the ones stock pi carries: `"altScreen": "strip-mux-and-mouse"` (the server strips its mouse DECSETs and publishes `cliMouseTracking`, and a drag selects locally) and `"wheelForward": { "mode": "always" }` (the wheel goes to the CLI as SGR reports while that flag is on). With the custom-entry defaults (`strip-mux-only`, `never`) the DECSETs reach xterm, which handles the wheel only until a tab switch or reload replays the pane without them; from then on the wheel scrolls an empty local buffer. Use `always` rather than `version-gated` for such an entry: a `version-gated` rule forwards only when the session has a `cliVersion`, and the server probes one only for an entry that declares `capabilities.gates` (`cliNeedsVersionProbe` in `session.ts`), so a custom entry with `version-gated` and no gates never forwards, and nothing says why. ⚠️ Saving the entry from the Settings form rebuilds its capabilities from those defaults, so both values have to be set again in the file after an edit there.
|
||||
|
||||
## Consumers outside the server
|
||||
|
||||
Two things need the catalogue but cannot import TypeScript, so `npm run generate:cli-catalog`
|
||||
|
||||
@@ -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.
|
||||
+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 |
|
||||
@@ -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
|
||||
|
||||
---
|
||||
|
||||
@@ -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
|
||||
+10
@@ -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:
|
||||
|
||||
+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
|
||||
|
||||
@@ -255,6 +255,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
|
||||
```
|
||||
|
||||
|
||||
@@ -48,6 +48,7 @@ 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. |
|
||||
| Auto Copy Selection | Off | Copies highlighted terminal text to the clipboard the moment you finish selecting it. Ctrl+C still copies on demand. |
|
||||
|
||||
@@ -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.**
|
||||
|
||||
Generated
+2
-10
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "aicodeman",
|
||||
"version": "1.51.0",
|
||||
"version": "1.51.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "aicodeman",
|
||||
"version": "1.51.0",
|
||||
"version": "1.51.1",
|
||||
"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",
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "aicodeman",
|
||||
"version": "1.51.0",
|
||||
"version": "1.51.1",
|
||||
"description": "Self-hosted mission control for AI coding agents: run Claude Code, Codex, OpenCode, Gemini, DeepSeek, Grok and more 24/7 in tmux, from any device.",
|
||||
"mcpName": "io.github.Ark0N/codeman",
|
||||
"type": "module",
|
||||
@@ -29,6 +29,7 @@
|
||||
"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 +124,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",
|
||||
|
||||
@@ -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.51.1",
|
||||
"author": {
|
||||
"name": "Ark0N",
|
||||
"url": "https://github.com/Ark0N"
|
||||
|
||||
@@ -157,7 +157,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"
|
||||
@@ -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';
|
||||
|
||||
@@ -178,13 +178,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);
|
||||
|
||||
@@ -817,5 +817,3 @@ export const CliEntrySchema = z
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export type ValidatedCliEntry = z.infer<typeof CliEntrySchema>;
|
||||
@@ -303,8 +303,8 @@ const CLAUDE: CliEntry = {
|
||||
transcript: 'claude-jsonl',
|
||||
altScreen: 'strip-full',
|
||||
echo: { policy: 'buffer', anchor: { kind: 'glyph', glyph: '❯', offset: 2 } },
|
||||
// Declared-for-later: the live rule (`_shouldForwardWheelToApp`, terminal-ui.js) is this version
|
||||
// AND the server-published `cliMouseTracking` flag (#498), so wiring this field up needs both.
|
||||
// Read by `_shouldForwardWheelToApp` (terminal-ui.js) through `window.__codemanWheelForward`;
|
||||
// forwarding also needs the server-published `cliMouseTracking` flag (#498).
|
||||
wheelForward: { mode: 'version-gated', minVersion: '2.1.187' },
|
||||
// A repaint-mode Claude pane keeps no local history, so when the wheel is not
|
||||
// forwarded (older CLI, inline renderer, the local-scrollback opt-out) a scroll is
|
||||
@@ -1926,8 +1926,8 @@ const COPILOT: CliEntry = {
|
||||
// (`cliMouseTracking`). Same shape and reason as opencode. The wheel keeps working because
|
||||
// `_shouldForwardWheelToApp` forwards it as SGR reports while the CLI is tracking.
|
||||
altScreen: 'strip-mux-and-mouse',
|
||||
// Forwards the wheel as SGR reports while the CLI is tracking the mouse, at any version
|
||||
// (`_shouldForwardWheelToApp` in terminal-ui.js has no version check for copilot).
|
||||
// Forwards the wheel as SGR reports while the CLI is tracking the mouse, at any version:
|
||||
// `always` is what keeps `_shouldForwardWheelToApp` (terminal-ui.js) from checking one.
|
||||
wheelForward: { mode: 'always' },
|
||||
// Pages its own transcript on PageUp/PageDown (1.0.95, measured in tmux: three PageUp moved
|
||||
// lines 109-140 to 010-042 and PageDown returned). This is the fallback when the
|
||||
|
||||
@@ -596,10 +596,18 @@ export interface CliCapabilities {
|
||||
* Forwarding the wheel to the CLI's own transcript. 'never' keeps local scrollback;
|
||||
* 'version-gated' forwards from `minVersion` on; 'always' forwards at any version. Either
|
||||
* forwarding mode applies only while the CLI has mouse tracking on (`cliMouseTracking`).
|
||||
* Read by the browser's gate (`_shouldForwardWheelToApp` in terminal-ui.js) through
|
||||
* `window.__codemanWheelForward`, which the server builds from this field for every CLI
|
||||
* whose mode is not `never`, disabled ones included (their running sessions stay open).
|
||||
*
|
||||
* ⚠️ Declared only: nothing reads this field yet (see DECLARED-FOR-LATER below). The browser's
|
||||
* gate is `_shouldForwardWheelToApp` in terminal-ui.js, which keeps its own hand-written
|
||||
* per-CLI rules, so changing a value here changes nothing until that gate is changed too.
|
||||
* ⚠️ 'version-gated' needs the session's `cliVersion`, and the server probes a version only
|
||||
* for an entry that declares `capabilities.gates` (`cliNeedsVersionProbe`, session.ts). An
|
||||
* entry without gates never forwards under 'version-gated', silently, so it uses 'always'.
|
||||
*
|
||||
* ⚠️ `cliMouseTracking` is only ever set for a CLI whose mouse DECSETs the server strips
|
||||
* (`altScreen: 'strip-full'` or `'strip-mux-and-mouse'`), so a forwarding mode on any other
|
||||
* `altScreen` never forwards: xterm keeps the DECSETs and encodes the wheel itself, until a
|
||||
* replay drops its mouse mode.
|
||||
*/
|
||||
wheelForward: { mode: 'never' | 'version-gated' | 'always'; minVersion?: string };
|
||||
/**
|
||||
@@ -1009,14 +1017,15 @@ export interface CliOverlays {
|
||||
/**
|
||||
* ⚠️ DECLARED-FOR-LATER: fields no code reads yet.
|
||||
*
|
||||
* `accent`, `overlays.credStore`, `capabilities.echo`, `capabilities.wheelForward`,
|
||||
* `capabilities.keyboardAccessory` and `capabilities.maxFrameBytes` all describe FRONTEND
|
||||
* `accent`, `overlays.credStore`, `capabilities.echo`, `capabilities.keyboardAccessory` and
|
||||
* `capabilities.maxFrameBytes` all describe FRONTEND
|
||||
* behaviour, and most of the frontend is deliberately untouched by the change that introduced
|
||||
* this registry — `app.js`, `terminal-ui.js`, `styles.css` and friends keep their own
|
||||
* hand-authored per-CLI rules, and moving them is its own piece of work with its own way of
|
||||
* being verified (a mobile/browser suite the CI gate cannot see). `shortBadge` graduated out of
|
||||
* this list (docs/cli-enable-disable-plan.md, Phase 2): `GET /api/clis` reads it for the
|
||||
* CLI-management Settings list.
|
||||
* CLI-management Settings list, and so did `capabilities.wheelForward`, which the browser's wheel
|
||||
* gate reads through `window.__codemanWheelForward`.
|
||||
*
|
||||
* They are declared now because each entry should describe its CLI completely, and because
|
||||
* transcribing them while the hand-written source is still on screen is when the values are
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,6 @@
|
||||
* - `applyWorkspaceHooks(workspace, install?)` — the ONE install-vs-refresh decision
|
||||
* point every claude-session create path routes through (see its doc comment)
|
||||
* - `ensureCodemanHooks(casePath)` — safely installs/updates hooks for a managed case
|
||||
* - `updateCaseEnvVars(casePath, envVars)` — merges env vars into settings
|
||||
*
|
||||
* Hook events generated: `idle_prompt`, `permission_prompt`, `elicitation_dialog`,
|
||||
* `elicitation_complete`, `elicitation_response`, `stop`, `teammate_idle`,
|
||||
@@ -632,37 +631,6 @@ export async function stripCaseEnvKeys(casePath: string, keysToRemove: readonly
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates env vars in .claude/settings.local.json for the given case path.
|
||||
* Merges with existing env field; removes vars set to empty string.
|
||||
*/
|
||||
export async function updateCaseEnvVars(casePath: string, envVars: Record<string, string>): Promise<void> {
|
||||
await withSafeSettingsWrite(casePath, 'env vars', async (claudeDir, settingsPath) => {
|
||||
if (!(await pathExistsForWrite(claudeDir))) {
|
||||
await mkdir(claudeDir, { recursive: true });
|
||||
}
|
||||
|
||||
let existing: Record<string, unknown> = {};
|
||||
try {
|
||||
existing = JSON.parse(await readFile(settingsPath, 'utf-8'));
|
||||
} catch {
|
||||
existing = {};
|
||||
}
|
||||
|
||||
const currentEnv = (existing.env as Record<string, string>) || {};
|
||||
for (const [key, value] of Object.entries(envVars)) {
|
||||
if (value) {
|
||||
currentEnv[key] = value;
|
||||
} else {
|
||||
delete currentEnv[key];
|
||||
}
|
||||
}
|
||||
existing.env = currentEnv;
|
||||
|
||||
await writeFile(settingsPath, JSON.stringify(existing, null, 2) + '\n');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the `model` field in .claude/settings.local.json for the given case path.
|
||||
* Pass a non-empty string to set, or empty/null to remove.
|
||||
|
||||
@@ -112,7 +112,7 @@ export const LIMITED_BELOW_PARAMS_B = 12;
|
||||
export const DISK_HEADROOM_BYTES = 10 * GIB;
|
||||
/**
|
||||
* How many other models are listed under the pick, at most. Above what the stock catalogue
|
||||
* holds (10 models: 9 beside the pick), so a Mac is shown every model that fits it and the
|
||||
* holds (11 models: 10 beside the pick), so a Mac is shown every model that fits it and the
|
||||
* install accepts every one of them. Still a bound: test/local-model-catalog.test.ts fails for
|
||||
* a catalogue that outgrows it, so nothing drops out of the list unseen.
|
||||
*/
|
||||
|
||||
@@ -8,4 +8,4 @@
|
||||
export { RESEARCH_AGENT_PROMPT } from './research-agent.js';
|
||||
export { PLANNER_PROMPT } from './planner.js';
|
||||
export { PHASE_EXECUTION_PROMPT, TEAM_LEAD_PROMPT, REPLAN_PROMPT, SINGLE_TASK_PROMPT } from './orchestrator.js';
|
||||
export { RALPH_STATUS_CONTRACT, buildRalphLoopPrompt, type RalphLoopPromptOptions } from './ralph.js';
|
||||
export { buildRalphLoopPrompt } from './ralph.js';
|
||||
@@ -882,13 +882,6 @@ export class RalphTracker extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a phrase matches any valid completion phrase (primary or alternate).
|
||||
*/
|
||||
isValidCompletionPhrase(phrase: string): boolean {
|
||||
return this.findMatchingCompletionPhrase(phrase) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find which completion phrase (primary or alternate) matches the given phrase.
|
||||
*/
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
* - `DetectionStatus`, `ActiveTimerInfo` — status types
|
||||
*
|
||||
* Key methods: `start()`, `stop()`, `getStatus()`, `getConfig()`,
|
||||
* `getDetectionStatus()`, `getActiveTimers()`, `getAggregateMetrics()`,
|
||||
* `getDetectionStatus()`, `getActiveTimers()`,
|
||||
* `getTimingHistory()`, `getHealthScore()`
|
||||
*
|
||||
* @dependencies session (PTY output), ai-idle-checker, ai-plan-checker,
|
||||
@@ -76,14 +76,7 @@ import {
|
||||
AI_PLAN_CHECK_TIMEOUT_MS,
|
||||
AI_PLAN_CHECK_COOLDOWN_MS,
|
||||
} from './config/ai-defaults.js';
|
||||
import {
|
||||
getErrorMessage,
|
||||
type RespawnCycleMetrics,
|
||||
type RespawnAggregateMetrics,
|
||||
type RalphLoopHealthScore,
|
||||
type TimingHistory,
|
||||
type CycleOutcome,
|
||||
} from './types.js';
|
||||
import { getErrorMessage, type RalphLoopHealthScore, type TimingHistory, type CycleOutcome } from './types.js';
|
||||
|
||||
// ========== Constants ==========
|
||||
|
||||
@@ -1903,13 +1896,6 @@ export class RespawnController extends EventEmitter {
|
||||
this.emit('actionLog', action);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get recent action log entries.
|
||||
*/
|
||||
getRecentActions(): ActionLogEntry[] {
|
||||
return [...this.recentActions];
|
||||
}
|
||||
|
||||
// ========== Multi-Layer Detection Methods ==========
|
||||
// Pattern detection delegated to ./respawn-patterns.js (isCompletionMessage, hasWorkingPattern, extractTokenCount)
|
||||
|
||||
@@ -3178,23 +3164,6 @@ export class RespawnController extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get aggregate metrics for monitoring.
|
||||
* @returns Copy of aggregate metrics
|
||||
*/
|
||||
getAggregateMetrics(): RespawnAggregateMetrics {
|
||||
return this.cycleMetrics.getAggregate();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get recent cycle metrics for analysis.
|
||||
* @param limit - Maximum number of metrics to return (default: 20)
|
||||
* @returns Recent cycle metrics, newest first
|
||||
*/
|
||||
getRecentCycleMetrics(limit: number = 20): RespawnCycleMetrics[] {
|
||||
return this.cycleMetrics.getRecent(limit);
|
||||
}
|
||||
|
||||
// ========== P2-005: Health Score (delegated to respawn-health.ts) ==========
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
/**
|
||||
* @fileoverview LRU cache for task descriptions parsed from terminal output.
|
||||
*
|
||||
* Stores descriptions extracted from Claude Code's Task tool invocations
|
||||
* (e.g., "Explore(Check files)") keyed by timestamp. Used to correlate
|
||||
* with SubagentWatcher discoveries for better window titles.
|
||||
*
|
||||
* @module session-task-cache
|
||||
*/
|
||||
|
||||
import { LRUMap } from './utils/lru-map.js';
|
||||
|
||||
/** Default maximum number of task descriptions to keep */
|
||||
const DEFAULT_MAX_SIZE = 100;
|
||||
|
||||
/** Default maximum age for task descriptions (30 seconds) */
|
||||
const DEFAULT_MAX_AGE_MS = 30_000;
|
||||
|
||||
/**
|
||||
* LRU cache for task descriptions parsed from terminal output.
|
||||
*
|
||||
* Descriptions are keyed by the timestamp when they were parsed.
|
||||
* Old entries are automatically cleaned up based on maxAgeMs.
|
||||
* Size is bounded by the underlying LRUMap.
|
||||
*/
|
||||
export class SessionTaskCache {
|
||||
private readonly cache: LRUMap<number, string>;
|
||||
private readonly maxAgeMs: number;
|
||||
|
||||
constructor(maxSize: number = DEFAULT_MAX_SIZE, maxAgeMs: number = DEFAULT_MAX_AGE_MS) {
|
||||
this.cache = new LRUMap<number, string>({ maxSize });
|
||||
this.maxAgeMs = maxAgeMs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a task description at the given timestamp.
|
||||
*/
|
||||
add(timestamp: number, description: string): void {
|
||||
this.cache.set(timestamp, description);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove task descriptions older than maxAgeMs.
|
||||
* LRUMap maintains insertion order, so we can break early
|
||||
* once we find a non-expired entry.
|
||||
*/
|
||||
private cleanupOld(): void {
|
||||
const cutoff = Date.now() - this.maxAgeMs;
|
||||
for (const timestamp of this.cache.keysInOrder()) {
|
||||
if (timestamp < cutoff) {
|
||||
this.cache.delete(timestamp);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all recent task descriptions sorted by timestamp (most recent first).
|
||||
*/
|
||||
getAll(): Array<{ timestamp: number; description: string }> {
|
||||
this.cleanupOld();
|
||||
const results: Array<{ timestamp: number; description: string }> = [];
|
||||
for (const [timestamp, description] of this.cache) {
|
||||
results.push({ timestamp, description });
|
||||
}
|
||||
return results.sort((a, b) => b.timestamp - a.timestamp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a task description that was parsed close to a given timestamp.
|
||||
* Used to correlate with SubagentWatcher discoveries.
|
||||
*
|
||||
* @param subagentStartTime - The timestamp when the subagent was discovered
|
||||
* @param maxAgeMs - Maximum age difference to consider (default 10 seconds)
|
||||
* @returns The matching description or undefined
|
||||
*/
|
||||
findNear(subagentStartTime: number, maxAgeMs: number = 10000): string | undefined {
|
||||
this.cleanupOld();
|
||||
|
||||
let bestMatch: { timestamp: number; description: string } | undefined;
|
||||
let bestDiff = Infinity;
|
||||
|
||||
for (const [timestamp, description] of this.cache) {
|
||||
const diff = Math.abs(subagentStartTime - timestamp);
|
||||
if (diff < maxAgeMs && diff < bestDiff) {
|
||||
bestMatch = { timestamp, description };
|
||||
bestDiff = diff;
|
||||
}
|
||||
}
|
||||
|
||||
return bestMatch?.description;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all cached descriptions.
|
||||
*/
|
||||
clear(): void {
|
||||
this.cache.clear();
|
||||
}
|
||||
}
|
||||
+3
-127
@@ -17,7 +17,7 @@
|
||||
*
|
||||
* Key methods: `runPrompt()`, `startInteractive()`, `startShell()`,
|
||||
* `writeViaMux()`, `toState()`, `stop()`, `resize()`, `isIdle()`,
|
||||
* `setAutoCompact()`, `findTaskDescriptionNear()`, `getTerminalBuffer()`
|
||||
* `setAutoCompact()`, `getTerminalBuffer()`
|
||||
*
|
||||
* @dependencies session-cli-builder (args/env), session-auto-ops (auto-compact/clear),
|
||||
* ralph-tracker (todo/completion parsing), bash-tool-parser (tool invocation tracking),
|
||||
@@ -117,7 +117,6 @@ import {
|
||||
SPINNER_PATTERN,
|
||||
CLAUDE_WORKING_LINE_PATTERN,
|
||||
MAX_SESSION_TOKENS,
|
||||
execPattern,
|
||||
getClaudeCliVersion,
|
||||
getClaudeBinaryPath,
|
||||
spawnPtyWithHelperRepair,
|
||||
@@ -156,7 +155,6 @@ import {
|
||||
} from './session-cli-builder.js';
|
||||
import { SessionAutoOps, type ContextReport } from './session-auto-ops.js';
|
||||
import { detectUsageLimitPause } from './usage-limit-patterns.js';
|
||||
import { SessionTaskCache } from './session-task-cache.js';
|
||||
import { InteractivePtyExitBreaker } from './session-pty-exit-breaker.js';
|
||||
import { isGeneratedSessionName, SubmittedPromptTracker } from './session-auto-name.js';
|
||||
import { parseTerminalAttachmentRequests } from './attachment-magic.js';
|
||||
@@ -222,12 +220,6 @@ const MAX_CLAUDE_SESSION_CHAIN = 32;
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const FOCUS_ESCAPE_FILTER = /\x1b\[\?1004[hl]|\x1b\[[IO]/g;
|
||||
|
||||
// Pattern to match Task tool invocations in terminal output
|
||||
// Matches: "Explore(Description)", "Task(Description)", "Bash(Description)", etc.
|
||||
// The prefix characters vary (●, ·, ✶, etc.) so we don't require them
|
||||
// We look for the tool name followed by (description)
|
||||
const TASK_TOOL_PATTERN = /\b(Explore|Task|Bash|Plan|general-purpose)\(([^)]+)\)/g;
|
||||
|
||||
// Pre-compiled patterns for hot paths (avoid regex compilation per call)
|
||||
/** Pattern to strip leading ANSI escapes and whitespace from terminal buffer */
|
||||
// eslint-disable-next-line no-control-regex
|
||||
@@ -235,8 +227,6 @@ const LEADING_ANSI_WHITESPACE_PATTERN = /^(\x1b\[\??[\d;]*[A-Za-z]|[\s\r\n])+/;
|
||||
/** Pattern to match Ctrl+L (form feed) characters */
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const CTRL_L_PATTERN = /\x0c/g;
|
||||
/** Pattern to split by newlines (CR or LF) */
|
||||
const NEWLINE_SPLIT_PATTERN = /\r?\n/;
|
||||
|
||||
/**
|
||||
* True for external-CLI run modes (non-Claude) that use their own TUI and output format:
|
||||
@@ -574,9 +564,6 @@ export class Session extends EventEmitter {
|
||||
readonly createdAt: number;
|
||||
readonly mode: SessionMode;
|
||||
|
||||
// Task description cache (extracted to SessionTaskCache)
|
||||
private _taskCache = new SessionTaskCache();
|
||||
|
||||
private _name: string;
|
||||
private _nameSource: SessionNameSource;
|
||||
/** `pinCliSessionName` as of the last spawn (see {@link _refreshCliNamePin}). */
|
||||
@@ -834,10 +821,6 @@ export class Session extends EventEmitter {
|
||||
// Ralph tracking (Ralph Wiggum loops and todo lists inside Claude Code)
|
||||
private _ralphTracker: RalphTracker;
|
||||
|
||||
// Agent tree tracking
|
||||
private _parentAgentId: string | null = null;
|
||||
private _childAgentIds: string[] = [];
|
||||
|
||||
// Bounded dedup set for terminal attachment magic-links already requested.
|
||||
private _attachmentMagicSeen = new Set<string>();
|
||||
private _attachmentHistory: SessionAttachmentHistoryItem[] = [];
|
||||
@@ -961,9 +944,7 @@ export class Session extends EventEmitter {
|
||||
toolsUpdate: (tools: ActiveBashTool[]) => void;
|
||||
} | null = null;
|
||||
|
||||
// Task descriptions parsed from terminal output — delegated to SessionTaskCache
|
||||
|
||||
// Throttle expensive PTY processing (Ralph, bash parser, task descriptions)
|
||||
// Throttle expensive PTY processing (Ralph, bash parser)
|
||||
// Accumulates clean data between processing windows to avoid running regex on every chunk
|
||||
private _lastExpensiveProcessTime: number = 0;
|
||||
private _pendingCleanData: string = '';
|
||||
@@ -1999,14 +1980,6 @@ export class Session extends EventEmitter {
|
||||
return this._taskTracker;
|
||||
}
|
||||
|
||||
get runningTaskCount(): number {
|
||||
return this._taskTracker.getRunningCount();
|
||||
}
|
||||
|
||||
get taskTree(): BackgroundTask[] {
|
||||
return this._taskTracker.getTaskTree();
|
||||
}
|
||||
|
||||
get taskStats(): { total: number; running: number; completed: number; failed: number } {
|
||||
return this._taskTracker.getStats();
|
||||
}
|
||||
@@ -2028,38 +2001,10 @@ export class Session extends EventEmitter {
|
||||
return this._ralphTracker.getTodoStats();
|
||||
}
|
||||
|
||||
// Bash tool tracking getters
|
||||
get bashToolParser(): BashToolParser {
|
||||
return this._bashToolParser;
|
||||
}
|
||||
|
||||
get activeTools(): ActiveBashTool[] {
|
||||
return this._bashToolParser.activeTools;
|
||||
}
|
||||
|
||||
get parentAgentId(): string | null {
|
||||
return this._parentAgentId;
|
||||
}
|
||||
|
||||
set parentAgentId(value: string | null) {
|
||||
this._parentAgentId = value;
|
||||
}
|
||||
|
||||
get childAgentIds(): string[] {
|
||||
return [...this._childAgentIds];
|
||||
}
|
||||
|
||||
addChildAgentId(agentId: string): void {
|
||||
if (!this._childAgentIds.includes(agentId)) {
|
||||
this._childAgentIds.push(agentId);
|
||||
}
|
||||
}
|
||||
|
||||
removeChildAgentId(agentId: string): void {
|
||||
const idx = this._childAgentIds.indexOf(agentId);
|
||||
if (idx >= 0) this._childAgentIds.splice(idx, 1);
|
||||
}
|
||||
|
||||
// Nice priority config getters and setters
|
||||
get niceConfig(): NiceConfig {
|
||||
return { ...this._niceConfig };
|
||||
@@ -2519,8 +2464,6 @@ export class Session extends EventEmitter {
|
||||
ralphEnabled: this._ralphTracker.enabled,
|
||||
ralphAutoEnableDisabled: this._ralphTracker.autoEnableDisabled || undefined,
|
||||
ralphCompletionPhrase: this._ralphTracker.loopState.completionPhrase || undefined,
|
||||
parentAgentId: this._parentAgentId || undefined,
|
||||
childAgentIds: this._childAgentIds.length > 0 ? this._childAgentIds : undefined,
|
||||
niceEnabled: this._niceConfig.enabled,
|
||||
niceValue: this._niceConfig.niceValue,
|
||||
color: this._color,
|
||||
@@ -4411,7 +4354,7 @@ export class Session extends EventEmitter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Process expensive parsers (ANSI strip, Ralph, bash tool, token, CLI info, task descriptions).
|
||||
* Process expensive parsers (ANSI strip, Ralph, bash tool, token, CLI info).
|
||||
* Called on a throttled schedule (every EXPENSIVE_PROCESS_INTERVAL_MS) instead of on every
|
||||
* PTY data chunk. Receives accumulated raw data to process in one batch.
|
||||
*/
|
||||
@@ -4464,11 +4407,6 @@ export class Session extends EventEmitter {
|
||||
this.parseClaudeCodeInfo(getCleanData());
|
||||
}
|
||||
|
||||
// Parse task descriptions from terminal output (e.g., "Explore(Check files)")
|
||||
if (rawData.includes('(') && rawData.includes(')')) {
|
||||
this.parseTaskDescriptionsFromTerminalData(getCleanData());
|
||||
}
|
||||
|
||||
// Legacy gerunds, Claude-only. The status-line pattern above already ran for every
|
||||
// CLI that declares one, so this adds only the older wording. Current Claude
|
||||
// randomizes the word ("Actualizing…", "Finagling…"), so these catch a fraction of
|
||||
@@ -4970,67 +4908,10 @@ export class Session extends EventEmitter {
|
||||
} else if (trimmed) {
|
||||
this._textOutput.append(line + '\n');
|
||||
}
|
||||
|
||||
// Parse task descriptions from terminal output (e.g., "Explore(Description)")
|
||||
// This captures the short description from Claude Code's Task tool output
|
||||
// Use direct method since cleanLine is already ANSI-stripped (line 1460)
|
||||
this.parseTaskDescriptionsDirect(cleanLine);
|
||||
}
|
||||
// Note: BufferAccumulator auto-trims when max size exceeded
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse task descriptions from terminal data (may contain multiple lines).
|
||||
* Called from interactive mode's onData handler with ANSI-stripped data.
|
||||
* @param cleanData - Terminal data with ANSI codes already stripped
|
||||
*/
|
||||
private parseTaskDescriptionsFromTerminalData(cleanData: string): void {
|
||||
// Quick pre-check: skip if no parentheses present
|
||||
if (!cleanData.includes('(') || !cleanData.includes(')')) return;
|
||||
|
||||
// Split by newlines and process each line (data already ANSI-stripped)
|
||||
const lines = cleanData.split(NEWLINE_SPLIT_PATTERN);
|
||||
for (const line of lines) {
|
||||
this.parseTaskDescriptionsDirect(line);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse task descriptions from a pre-cleaned line (no ANSI codes).
|
||||
* Used by both processOutput() and parseTaskDescriptionsFromTerminalData().
|
||||
*/
|
||||
private parseTaskDescriptionsDirect(cleanLine: string): void {
|
||||
// Quick pre-check: skip expensive regex if no common tool patterns present
|
||||
if (!cleanLine.includes('(') || !cleanLine.includes(')')) return;
|
||||
|
||||
execPattern(TASK_TOOL_PATTERN, cleanLine, (match) => {
|
||||
const description = match[2].trim();
|
||||
if (description && description.length > 0) {
|
||||
this._taskCache.add(Date.now(), description);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get recent task descriptions parsed from terminal output.
|
||||
* Returns descriptions sorted by timestamp (most recent first).
|
||||
*/
|
||||
getRecentTaskDescriptions(): Array<{ timestamp: number; description: string }> {
|
||||
return this._taskCache.getAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a task description that was parsed close to a given timestamp.
|
||||
* Used to correlate with SubagentWatcher discoveries.
|
||||
*
|
||||
* @param subagentStartTime - The timestamp when the subagent was discovered
|
||||
* @param maxAgeMs - Maximum age difference to consider (default 10 seconds)
|
||||
* @returns The matching description or undefined
|
||||
*/
|
||||
findTaskDescriptionNear(subagentStartTime: number, maxAgeMs: number = 10000): string | undefined {
|
||||
return this._taskCache.findNear(subagentStartTime, maxAgeMs);
|
||||
}
|
||||
|
||||
// Parse token count from Claude's status line in interactive mode
|
||||
// Matches patterns like "123.4k tokens", "5234 tokens", "1.2M tokens"
|
||||
//
|
||||
@@ -5981,10 +5862,6 @@ export class Session extends EventEmitter {
|
||||
this._status = killMux ? 'stopped' : 'idle';
|
||||
this._currentTaskId = null;
|
||||
|
||||
// Clear task description cache and agent tree to prevent memory leak
|
||||
this._taskCache.clear();
|
||||
this._childAgentIds = [];
|
||||
|
||||
// Kill the associated mux session if requested
|
||||
if (killMux && this._mux) {
|
||||
// Try to kill mux session even if _muxSession is not set (e.g., restored sessions)
|
||||
@@ -6038,6 +5915,5 @@ export class Session extends EventEmitter {
|
||||
this._messages = [];
|
||||
this._taskTracker.clear();
|
||||
this._ralphTracker.clear();
|
||||
this._taskCache.clear();
|
||||
}
|
||||
}
|
||||
@@ -429,29 +429,6 @@ export class StateStore {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to recover state from backup file.
|
||||
* Call this if main state file is corrupt.
|
||||
*/
|
||||
recoverFromBackup(): boolean {
|
||||
const backupPath = this.filePath + '.bak';
|
||||
try {
|
||||
if (existsSync(backupPath)) {
|
||||
const backupContent = readFileSync(backupPath, 'utf-8');
|
||||
const parsed = JSON.parse(backupContent) as Partial<AppState>;
|
||||
this.state = this._mergeWithInitialState(parsed);
|
||||
console.log('[StateStore] Successfully recovered state from backup');
|
||||
// Reset circuit breaker after successful recovery
|
||||
this.circuitBreakerOpen = false;
|
||||
this.consecutiveSaveFailures = 0;
|
||||
return true;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[StateStore] Failed to recover from backup:', err);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset the circuit breaker (for manual intervention).
|
||||
*/
|
||||
|
||||
+33
-19
@@ -15,7 +15,8 @@ import { join } from 'node:path';
|
||||
|
||||
import { watch as chokidarWatch, type FSWatcher as ChokidarWatcher } from 'chokidar';
|
||||
|
||||
import type { TeamConfig, TeamMember, TeamTask, InboxMessage } from './types.js';
|
||||
import { getErrorMessage, type TeamConfig, type TeamTask, type InboxMessage } from './types.js';
|
||||
import { closeWatcherOnError } from './utils/close-watcher-on-error.js';
|
||||
import { LRUMap } from './utils/lru-map.js';
|
||||
import { TEAM_POLL_INTERVAL_MS, MAX_CACHED_TEAMS, MAX_CACHED_TASKS } from './config/team-config.js';
|
||||
|
||||
@@ -36,6 +37,8 @@ export class TeamWatcher extends EventEmitter {
|
||||
private sessionToTeam: Map<string, string> = new Map();
|
||||
private teamsWatcher: ChokidarWatcher | null = null;
|
||||
private tasksWatcher: ChokidarWatcher | null = null;
|
||||
// Watchers stopped by an error and not yet back for a whole poll: one warning per outage.
|
||||
private watchersDown = new Set<'teams' | 'tasks'>();
|
||||
|
||||
constructor(teamsDir?: string, tasksDir?: string) {
|
||||
super();
|
||||
@@ -47,11 +50,28 @@ export class TeamWatcher extends EventEmitter {
|
||||
start(): void {
|
||||
if (this.pollTimer) return;
|
||||
this.poll();
|
||||
this.pollTimer = setInterval(() => this.poll(), TEAM_POLL_INTERVAL_MS);
|
||||
this.pollTimer = setInterval(() => {
|
||||
this.setupFsWatchers(); // re-creates a watcher an error stopped
|
||||
this.poll();
|
||||
}, TEAM_POLL_INTERVAL_MS);
|
||||
this.setupFsWatchers();
|
||||
}
|
||||
|
||||
private watcherStopped(name: 'teams' | 'tasks', err: unknown): void {
|
||||
if (this.watchersDown.has(name)) return;
|
||||
this.watchersDown.add(name);
|
||||
console.warn(`[TeamWatcher] ${name} watcher stopped, relying on polling: ${getErrorMessage(err)}`);
|
||||
}
|
||||
|
||||
/** Creates each watcher that is not running; one still running since the last call ends its outage. */
|
||||
private setupFsWatchers(): void {
|
||||
if (this.teamsWatcher) this.watchersDown.delete('teams');
|
||||
else this.setupTeamsWatcher();
|
||||
if (this.tasksWatcher) this.watchersDown.delete('tasks');
|
||||
else this.setupTasksWatcher();
|
||||
}
|
||||
|
||||
private setupTeamsWatcher(): void {
|
||||
try {
|
||||
this.teamsWatcher = chokidarWatch(this.teamsDir, {
|
||||
depth: 2,
|
||||
@@ -66,13 +86,16 @@ export class TeamWatcher extends EventEmitter {
|
||||
this.teamsWatcher.on('change', teamsHandler);
|
||||
this.teamsWatcher.on('unlink', teamsHandler);
|
||||
this.teamsWatcher.on('unlinkDir', teamsHandler);
|
||||
this.teamsWatcher.on('error', (err) => {
|
||||
console.warn('[TeamWatcher] chokidar teams watcher error:', err);
|
||||
closeWatcherOnError(this.teamsWatcher, (err) => {
|
||||
this.teamsWatcher = null;
|
||||
this.watcherStopped('teams', err);
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn('[TeamWatcher] Failed to set up teams chokidar watcher, relying on polling:', err);
|
||||
this.watcherStopped('teams', err);
|
||||
}
|
||||
}
|
||||
|
||||
private setupTasksWatcher(): void {
|
||||
try {
|
||||
this.tasksWatcher = chokidarWatch(this.tasksDir, {
|
||||
depth: 1,
|
||||
@@ -84,11 +107,12 @@ export class TeamWatcher extends EventEmitter {
|
||||
|
||||
this.tasksWatcher.on('add', () => this.pollTasks().catch(() => {})); // Ignore - poll errors are non-fatal, next poll will retry
|
||||
this.tasksWatcher.on('change', () => this.pollTasks().catch(() => {})); // Ignore - poll errors are non-fatal, next poll will retry
|
||||
this.tasksWatcher.on('error', (err) => {
|
||||
console.warn('[TeamWatcher] chokidar tasks watcher error:', err);
|
||||
closeWatcherOnError(this.tasksWatcher, (err) => {
|
||||
this.tasksWatcher = null;
|
||||
this.watcherStopped('tasks', err);
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn('[TeamWatcher] Failed to set up tasks chokidar watcher, relying on polling:', err);
|
||||
this.watcherStopped('tasks', err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,6 +137,7 @@ export class TeamWatcher extends EventEmitter {
|
||||
this.taskMtimes.clear();
|
||||
this.inboxMtimes.clear();
|
||||
this.sessionToTeam.clear();
|
||||
this.watchersDown.clear();
|
||||
}
|
||||
|
||||
/** Get all discovered teams */
|
||||
@@ -175,17 +200,6 @@ export class TeamWatcher extends EventEmitter {
|
||||
return activeTasks > 0;
|
||||
}
|
||||
|
||||
/** Get teammates that have real tmux panes (not in-process) */
|
||||
getTmuxPaneTeammates(teamName: string): Array<TeamMember & { tmuxPaneId: string }> {
|
||||
const team = this.teams.get(teamName);
|
||||
if (!team) return [];
|
||||
|
||||
return team.members.filter(
|
||||
(m): m is TeamMember & { tmuxPaneId: string } =>
|
||||
m.agentType !== 'team-lead' && !!m.tmuxPaneId && m.tmuxPaneId !== 'in-process'
|
||||
);
|
||||
}
|
||||
|
||||
/** Get count of active teammates for a session */
|
||||
getActiveTeammateCount(sessionId: string): number {
|
||||
const team = this.getTeamForSession(sessionId);
|
||||
|
||||
@@ -4451,21 +4451,6 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync mouse mode based on pane count: enable if split (>1 pane), disable if single.
|
||||
* Called by TeamWatcher when teammates spawn/despawn panes.
|
||||
* Uses `tmux list-panes` for bulletproof detection — counts actual panes, not config.
|
||||
*/
|
||||
async syncMouseMode(muxName: string): Promise<boolean> {
|
||||
if (IS_TEST_MODE) return true;
|
||||
const panes = await this.listPanes(muxName);
|
||||
if (panes.length > 1) {
|
||||
return this.enableMouseMode(muxName);
|
||||
} else {
|
||||
return this.disableMouseMode(muxName);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List all panes in a tmux session.
|
||||
* Returns structured info for each pane.
|
||||
@@ -4782,67 +4767,6 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start piping pane output to a file using tmux pipe-pane.
|
||||
* Only pipes output direction (-O) to avoid echoing input.
|
||||
*/
|
||||
startPipePane(muxName: string, paneTarget: string, outputFile: string): boolean {
|
||||
if (IS_TEST_MODE) return true;
|
||||
if (!isValidMuxName(muxName)) {
|
||||
console.error('[TmuxManager] Invalid session name in startPipePane:', muxName);
|
||||
return false;
|
||||
}
|
||||
if (!SAFE_PANE_TARGET_PATTERN.test(paneTarget)) {
|
||||
console.error('[TmuxManager] Invalid pane target:', paneTarget);
|
||||
return false;
|
||||
}
|
||||
if (!isValidPath(outputFile)) {
|
||||
console.error('[TmuxManager] Invalid output file path:', outputFile);
|
||||
return false;
|
||||
}
|
||||
|
||||
const target = paneTarget.startsWith('%') ? `${muxName}.${paneTarget}` : `${muxName}.%${paneTarget}`;
|
||||
|
||||
try {
|
||||
execSync(`${this.tmux()} pipe-pane -O -t ${shellescape(target)} ${shellescape('cat >> ' + outputFile)}`, {
|
||||
encoding: 'utf-8',
|
||||
timeout: EXEC_TIMEOUT_MS,
|
||||
});
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error('[TmuxManager] Failed to start pipe-pane:', err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop piping pane output (calling pipe-pane with no command stops piping).
|
||||
*/
|
||||
stopPipePane(muxName: string, paneTarget: string): boolean {
|
||||
if (IS_TEST_MODE) return true;
|
||||
if (!isValidMuxName(muxName)) {
|
||||
console.error('[TmuxManager] Invalid session name in stopPipePane:', muxName);
|
||||
return false;
|
||||
}
|
||||
if (!SAFE_PANE_TARGET_PATTERN.test(paneTarget)) {
|
||||
console.error('[TmuxManager] Invalid pane target:', paneTarget);
|
||||
return false;
|
||||
}
|
||||
|
||||
const target = paneTarget.startsWith('%') ? `${muxName}.${paneTarget}` : `${muxName}.%${paneTarget}`;
|
||||
|
||||
try {
|
||||
execSync(`${this.tmux()} pipe-pane -t ${shellescape(target)}`, {
|
||||
encoding: 'utf-8',
|
||||
timeout: EXEC_TIMEOUT_MS,
|
||||
});
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error('[TmuxManager] Failed to stop pipe-pane:', err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
getAttachCommand(): string {
|
||||
return 'tmux';
|
||||
}
|
||||
|
||||
@@ -153,6 +153,16 @@ export function restrictTmuxPrefixTable(tmux: string, run: TmuxRunner = defaultR
|
||||
let listing: string | null;
|
||||
try {
|
||||
listing = run(`${tmux} list-keys -T prefix`);
|
||||
// ⚠️ tmux 3.7 through 3.7c (fixed in 3.8) print NOTHING on stdout for
|
||||
// `list-keys -T prefix` when the table holds exactly one binding (the line goes
|
||||
// to a status message instead), which is the shape this function leaves behind: read blank as "ask the full listing" and keep
|
||||
// only its prefix-table lines, or every call would reset an already-reduced table.
|
||||
if (!listing.trim()) {
|
||||
listing = run(`${tmux} list-keys`)
|
||||
.split('\n')
|
||||
.filter((line) => PREFIX_LINE.test(line.trim()))
|
||||
.join('\n');
|
||||
}
|
||||
} catch {
|
||||
listing = null; // an empty table makes list-keys fail on some tmux builds
|
||||
}
|
||||
|
||||
+72
-14
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* @fileoverview `codeman tui`: the full-screen dashboard plus the two
|
||||
* non-interactive fast paths (`--list`, `<n>`).
|
||||
* non-interactive fast paths (`--list`, `<n|name>`).
|
||||
*
|
||||
* This is the IO half of `src/tui/`: it owns the terminal, the timers, stdin
|
||||
* and the tmux handoff. Every decision it makes that can be stated as a
|
||||
@@ -2643,7 +2643,7 @@ export async function runTui(options: TuiRunOptions = {}): Promise<number> {
|
||||
if (!stdout.isTTY || !stdin.isTTY) {
|
||||
process.stderr.write(
|
||||
`${palette.err('codeman tui needs an interactive terminal.')}\n` +
|
||||
`Use ${palette.info('codeman tui --list')} for a plain list, or ${palette.info('codeman tui <n>')} to attach.\n`
|
||||
`Use ${palette.info('codeman tui --list')} for a plain list, or ${palette.info('codeman tui <n|name>')} to attach.\n`
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
@@ -2689,17 +2689,72 @@ export async function runTuiList(options: TuiRunOptions = {}): Promise<number> {
|
||||
}
|
||||
}
|
||||
|
||||
/** What `codeman tui <session>` points at, resolved against one snapshot of the list. */
|
||||
export type TuiAttachTarget =
|
||||
| { kind: 'row'; row: TuiRow }
|
||||
/** A number with no row, or a name nothing in the list carries. */
|
||||
| { kind: 'none' }
|
||||
/** Several LIVE sessions carry the name; `positions` are their `--list` numbers. */
|
||||
| { kind: 'ambiguous'; positions: number[] }
|
||||
/** Only a finished (RECENT) row carries the name: nothing to attach to. */
|
||||
| { kind: 'finished' };
|
||||
|
||||
/**
|
||||
* `codeman tui <n>`: attach straight to the nth row of `--list`. No screen setup
|
||||
* at all, so it is as fast as the API call it makes.
|
||||
* Resolve `codeman tui <session>` against the rows `--list` prints.
|
||||
*
|
||||
* Digits only is a position, exactly as before names were accepted. Anything else
|
||||
* is a session name, matched exactly (case-sensitive) and only against the
|
||||
* session's name, never its folder or a prompt. Session names are not unique in
|
||||
* Codeman, so more than one LIVE match refuses rather than guessing; a RECENT row
|
||||
* is history with no pane, so it never counts as a live match.
|
||||
*/
|
||||
export async function runTuiAttach(position: number, options: TuiRunOptions = {}): Promise<number> {
|
||||
export function resolveAttachTarget(rows: readonly TuiRow[], target: number | string): TuiAttachTarget {
|
||||
if (typeof target === 'number' || /^\d+$/.test(target)) {
|
||||
const row = rows[Math.trunc(Number(target)) - 1];
|
||||
return row ? { kind: 'row', row } : { kind: 'none' };
|
||||
}
|
||||
const positions: number[] = [];
|
||||
let finished = false;
|
||||
rows.forEach((row, index) => {
|
||||
if (row.session.name !== target) return;
|
||||
if (row.group === 'recent') finished = true;
|
||||
else positions.push(index + 1);
|
||||
});
|
||||
if (positions.length === 1) return { kind: 'row', row: rows[positions[0] - 1] };
|
||||
if (positions.length > 1) return { kind: 'ambiguous', positions };
|
||||
return finished ? { kind: 'finished' } : { kind: 'none' };
|
||||
}
|
||||
|
||||
/** The stderr text for a target that resolved to no row, ending in a newline. */
|
||||
export function attachTargetError(
|
||||
resolved: Exclude<TuiAttachTarget, { kind: 'row' }>,
|
||||
target: number | string
|
||||
): string {
|
||||
const list = palette.info('codeman tui --list');
|
||||
switch (resolved.kind) {
|
||||
case 'ambiguous':
|
||||
return (
|
||||
`${palette.err(`${resolved.positions.length} live sessions are named ${target} (${resolved.positions.join(', ')} in the list)`)}\n` +
|
||||
`Attach by number instead: ${palette.info(`codeman tui ${resolved.positions[0]}`)}, or run ${list}.\n`
|
||||
);
|
||||
case 'finished':
|
||||
return `${palette.err(`there is no live session named ${target}, only a finished one`)}\nRun ${list} to see the live ones.\n`;
|
||||
case 'none':
|
||||
return typeof target === 'number' || /^\d+$/.test(target)
|
||||
? `${palette.err(`there is no session ${target}`)}\nRun ${list} to see the numbers.\n`
|
||||
: `${palette.err(`there is no session named ${target}`)}\nNames match exactly. Run ${list} and attach by number instead.\n`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `codeman tui <session>`: attach straight to a row of `--list`, by its number or
|
||||
* by its session name. No screen setup at all, so it is as fast as the API call
|
||||
* it makes. The target is resolved before the terminal check, so a script learns
|
||||
* that a name does not exist (or is ambiguous) without needing a TTY.
|
||||
*/
|
||||
export async function runTuiAttach(target: number | string, options: TuiRunOptions = {}): Promise<number> {
|
||||
const stdin = options.stdin ?? process.stdin;
|
||||
const stdout = options.stdout ?? process.stdout;
|
||||
if (!stdout.isTTY || !stdin.isTTY) {
|
||||
process.stderr.write(`${palette.err('attaching needs an interactive terminal.')}\n`);
|
||||
return 1;
|
||||
}
|
||||
const env = options.env ?? process.env;
|
||||
const client = options.client ?? new TuiClient();
|
||||
try {
|
||||
@@ -2712,11 +2767,14 @@ export async function runTuiAttach(position: number, options: TuiRunOptions = {}
|
||||
process.stderr.write(authHint());
|
||||
return 1;
|
||||
}
|
||||
const row = state.rows[Math.trunc(position) - 1];
|
||||
if (!row) {
|
||||
process.stderr.write(
|
||||
`${palette.err(`there is no session ${position}`)}\nRun ${palette.info('codeman tui --list')} to see the numbers.\n`
|
||||
);
|
||||
const resolved = resolveAttachTarget(state.rows, target);
|
||||
if (resolved.kind !== 'row') {
|
||||
process.stderr.write(attachTargetError(resolved, target));
|
||||
return 1;
|
||||
}
|
||||
const row = resolved.row;
|
||||
if (!stdout.isTTY || !stdin.isTTY) {
|
||||
process.stderr.write(`${palette.err('attaching needs an interactive terminal.')}\n`);
|
||||
return 1;
|
||||
}
|
||||
const plan = planAttach(row.session.muxName, {
|
||||
|
||||
+15
-4
@@ -991,6 +991,19 @@ export class TuiClient {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* One key table as `list-keys` prints it. ⚠️ tmux 3.7 through 3.7c (fixed in 3.8)
|
||||
* print NOTHING on stdout for `list-keys -T <table>` when the table holds exactly
|
||||
* one binding (the line goes to a status message instead), which is the shape Codeman reduces the prefix table to. So a
|
||||
* blank answer is retried as the full listing: every line there names its table,
|
||||
* and both parsers already filter on it.
|
||||
*/
|
||||
private async listKeyTable(table: TuiKeyTable): Promise<string> {
|
||||
const { stdout } = await this.exec('tmux', ['-L', this.socket, 'list-keys', '-T', table]);
|
||||
if (stdout.trim()) return stdout;
|
||||
return (await this.exec('tmux', ['-L', this.socket, 'list-keys'])).stdout;
|
||||
}
|
||||
|
||||
/**
|
||||
* The key that detaches, straight from tmux's own key table. Key tables are
|
||||
* server-global, so unlike the prefix this takes no session. A failure is
|
||||
@@ -998,8 +1011,7 @@ export class TuiClient {
|
||||
*/
|
||||
async readDetachKey(): Promise<string | null> {
|
||||
try {
|
||||
const { stdout } = await this.exec('tmux', ['-L', this.socket, 'list-keys', '-T', 'prefix']);
|
||||
return parseDetachKey(stdout);
|
||||
return parseDetachKey(await this.listKeyTable('prefix'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
@@ -1012,8 +1024,7 @@ export class TuiClient {
|
||||
*/
|
||||
async readPrefixBinding(key: string, table: TuiKeyTable = 'prefix'): Promise<string | null> {
|
||||
try {
|
||||
const { stdout } = await this.exec('tmux', ['-L', this.socket, 'list-keys', '-T', table]);
|
||||
return parsePrefixBinding(stdout, key, table);
|
||||
return parsePrefixBinding(await this.listKeyTable(table), key, table);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -29,20 +29,6 @@ import type { SessionMode } from './session.js';
|
||||
/** Where a foreign tmux server lives. Mirrors Codeman's own three locations. */
|
||||
export type ForeignTmuxLocationKind = 'local' | 'docker' | 'remote';
|
||||
|
||||
/**
|
||||
* A location to scan. `hostId` refers to the saved docker-host / remote-host
|
||||
* registry entry, so the transport can be rebuilt without trusting the browser.
|
||||
*/
|
||||
export interface ForeignTmuxLocation {
|
||||
kind: ForeignTmuxLocationKind;
|
||||
/** Registry id (`docker-hosts.json` / `remote-hosts.json`). Absent for local. */
|
||||
hostId?: string;
|
||||
/** Display label for the UI. Absent for local. */
|
||||
label?: string;
|
||||
/** Container to `docker exec` into (`kind === 'docker'`). */
|
||||
containerName?: string;
|
||||
}
|
||||
|
||||
/** One pane row from the probe script, after parsing. */
|
||||
export interface ForeignPaneProbe {
|
||||
socketPath: string;
|
||||
|
||||
@@ -698,9 +698,6 @@ export interface LocalModelRefusal {
|
||||
message: LocalModelInstallMessage;
|
||||
}
|
||||
|
||||
/** What every verb answers on success: the view after the verb. */
|
||||
export type LocalModelVerbAnswer = LocalModelInstallView;
|
||||
|
||||
/**
|
||||
* Why a verb was refused with 409.
|
||||
* - `job-running`: a job is running (a second install, a resume, a remove or a runtime action).
|
||||
|
||||
@@ -1103,10 +1103,6 @@ export interface SessionState {
|
||||
ralphAutoEnableDisabled?: boolean;
|
||||
/** Ralph completion phrase (if set) */
|
||||
ralphCompletionPhrase?: string;
|
||||
/** Parent agent ID if this session is a spawned agent */
|
||||
parentAgentId?: string;
|
||||
/** Child agent IDs spawned by this session */
|
||||
childAgentIds?: string[];
|
||||
/** Nice priority enabled */
|
||||
niceEnabled?: boolean;
|
||||
/** Nice value (-20 to 19) */
|
||||
|
||||
@@ -9,11 +9,7 @@
|
||||
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import {
|
||||
createCliExecutableResolver,
|
||||
formatCliNotFoundMessage,
|
||||
type CliResolverHost,
|
||||
} from './cli-executable-resolver.js';
|
||||
import { createCliExecutableResolver, type CliResolverHost } from './cli-executable-resolver.js';
|
||||
|
||||
/** Common directories where the Antigravity CLI binary may be installed */
|
||||
/**
|
||||
@@ -23,9 +19,6 @@ import {
|
||||
*/
|
||||
const ANTIGRAVITY_SEARCH_DIRS = (): string[] => (getCli('antigravity')?.discovery.searchDirs ?? []).map(expandHome);
|
||||
|
||||
const ANTIGRAVITY_NOT_FOUND =
|
||||
'Antigravity CLI not found. Install with: curl -fsSL https://antigravity.google/cli/install.sh | bash';
|
||||
|
||||
function createAntigravityResolver(host?: CliResolverHost, now?: () => number) {
|
||||
return createCliExecutableResolver({ binary: 'agy', searchDirs: ANTIGRAVITY_SEARCH_DIRS, now }, host);
|
||||
}
|
||||
@@ -53,7 +46,3 @@ export function resolveAntigravityDir(): string | null {
|
||||
export function isAntigravityAvailable(): boolean {
|
||||
return resolveAntigravityDir() !== null;
|
||||
}
|
||||
|
||||
export function getAntigravityNotFoundMessage(): string {
|
||||
return formatCliNotFoundMessage(ANTIGRAVITY_NOT_FOUND, antigravityResolver.diagnostics());
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import { execFileSync } from 'node:child_process';
|
||||
import { delimiter, join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
|
||||
import { createCliExecutableResolver, formatCliNotFoundMessage } from './cli-executable-resolver.js';
|
||||
import { createCliExecutableResolver } from './cli-executable-resolver.js';
|
||||
|
||||
/** Common directories where the Claude CLI binary may be installed */
|
||||
const CLAUDE_SEARCH_DIRS = [
|
||||
@@ -24,7 +24,6 @@ const CLAUDE_SEARCH_DIRS = [
|
||||
];
|
||||
|
||||
const claudeResolver = createCliExecutableResolver({ binary: 'claude', searchDirs: CLAUDE_SEARCH_DIRS });
|
||||
const CLAUDE_NOT_FOUND = 'Claude CLI not found. Install it with: curl -fsSL https://claude.ai/install.sh | bash';
|
||||
|
||||
/**
|
||||
* Returns true if the Claude CLI binary can be located (via `which` or one of
|
||||
@@ -46,10 +45,6 @@ export function findClaudeDir(): string | null {
|
||||
return claudeResolver.resolve()?.directory ?? null;
|
||||
}
|
||||
|
||||
export function getClaudeNotFoundMessage(): string {
|
||||
return formatCliNotFoundMessage(CLAUDE_NOT_FOUND, claudeResolver.diagnostics());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an absolute path to the `claude` binary, falling back to the bare
|
||||
* name `'claude'` when it cannot be located (so PATH resolution still gets a
|
||||
|
||||
@@ -82,26 +82,6 @@ export async function resolveCliLaunchError(mode: string, rawConfig?: Record<str
|
||||
return resolveCliBinDir(mode) === null ? missingCliMessage(mode) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is this CLI actually usable? For an ordinary CLI that is exactly "its binary resolved".
|
||||
* For a launcher it is that AND whatever its profile demands.
|
||||
*
|
||||
* ⚠️ A named-but-unimplemented profile fails CLOSED. In practice `schema.ts` rejects such an
|
||||
* entry at load time, so this is the second line of defence rather than the first — but the
|
||||
* direction matters: offering a Run that always fails is worse than reporting unavailable.
|
||||
*/
|
||||
export function isCliRunnable(id: string): boolean {
|
||||
const entry = getCli(id);
|
||||
if (!entry) return false;
|
||||
// No binary to find (`shell`): tmux-manager resolves the login shell in code.
|
||||
const resolved = entry.discovery.binaries.length === 0 ? true : resolveCliBinDir(id) !== null;
|
||||
const profileName = entry.discovery.launcherProfile;
|
||||
if (profileName === undefined) return resolved;
|
||||
const profile = LAUNCHER_PROFILES[profileName];
|
||||
if (!profile) return false;
|
||||
return resolved && profile.isRunnable();
|
||||
}
|
||||
|
||||
/**
|
||||
* The launcher's default target, for the `launcherDefaultTarget` engine value. Null for
|
||||
* every non-launcher CLI, which is what makes the corresponding launch arg drop out.
|
||||
|
||||
@@ -172,20 +172,6 @@ function createRegistryResolver(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an isolated resolver for `entry` around an injected probe, host and clock — the
|
||||
* test seam. Omitting `probe` keeps the ambient, VITEST-gated one, which is exactly what
|
||||
* the hermeticity tests exercise.
|
||||
*/
|
||||
export function createCliResolverForTest(
|
||||
entry: CliEntry,
|
||||
probe?: CliCandidateProbe,
|
||||
host?: CliResolverHost,
|
||||
now?: () => number
|
||||
): RegistryResolver {
|
||||
return createRegistryResolver(entry, probe ?? probeCliCandidate, host, now);
|
||||
}
|
||||
|
||||
/**
|
||||
* One memoized resolver per id, for the process lifetime — the same caching the per-CLI
|
||||
* modules already do for themselves, just keyed by id so generic code holding only a
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* @fileoverview Close a chokidar watcher on its first error, safely.
|
||||
*
|
||||
* chokidar 3 with `persistent: false` has no guard for an `fs.watch` that
|
||||
* throws (EMFILE once the inotify instance limit is used up, ENOSPC once the
|
||||
* watch limit is): it emits the error, then a TypeError from closing the
|
||||
* watcher it never got, then retries on the parent directory, one level per
|
||||
* pass, and re-adds `/` forever, since the parent of `/` is `/`. Only a closed
|
||||
* watcher ends that loop, so a watcher whose `'error'` handler just logs logs
|
||||
* forever.
|
||||
*
|
||||
* Closing from the handler is not enough on its own:
|
||||
* - `close()` removes every listener, and the TypeError of the same pass is
|
||||
* emitted after it. With no `'error'` listener EventEmitter throws it, and it
|
||||
* reaches the process as an unhandled rejection. So a no-op listener stays
|
||||
* on the closed watcher.
|
||||
* - callbacks chokidar already has in flight can still call `add()` (a deleted
|
||||
* file's `_remove()` re-adds the file when chokidar thinks it was the only
|
||||
* watched path), and `add()` sets `closed = false`, which starts the climb
|
||||
* again, silently now. So `add()` becomes a no-op on the closed watcher.
|
||||
*
|
||||
* @module utils/close-watcher-on-error
|
||||
*/
|
||||
|
||||
import type { FSWatcher } from 'chokidar';
|
||||
|
||||
/**
|
||||
* Close `watcher` on its first `'error'` and pass that error to `onClosed`,
|
||||
* once. The caller's polling has to cover what the watcher watched and create it
|
||||
* again later: chokidar 3 reports a one-off ENOENT race through the same error.
|
||||
*/
|
||||
export function closeWatcherOnError(watcher: FSWatcher, onClosed: (err: unknown) => void): void {
|
||||
watcher.once('error', (err: unknown) => {
|
||||
watcher.close().catch(() => {}); // best-effort, like the stop() paths
|
||||
watcher.on('error', () => {}); // see the fileoverview
|
||||
watcher.add = () => watcher; // likewise
|
||||
onClosed(err);
|
||||
});
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import { createCliExecutableResolver, formatCliNotFoundMessage } from './cli-executable-resolver.js';
|
||||
import { createCliExecutableResolver } from './cli-executable-resolver.js';
|
||||
import { parseCodexRateLimitsResponse, type StatusTelemetry } from '../usage-telemetry.js';
|
||||
|
||||
/**
|
||||
@@ -22,7 +22,6 @@ const CODEX_SEARCH_DIRS = (): string[] => (getCli('codex')?.discovery.searchDirs
|
||||
|
||||
const CODEX_BINARY = process.platform === 'win32' ? 'codex.exe' : 'codex';
|
||||
const codexResolver = createCliExecutableResolver({ binary: CODEX_BINARY, searchDirs: CODEX_SEARCH_DIRS });
|
||||
const CODEX_NOT_FOUND = 'Codex CLI not found. Install with: npm install -g @openai/codex';
|
||||
|
||||
/**
|
||||
* Finds the directory containing the `codex` binary.
|
||||
@@ -47,10 +46,6 @@ export function isCodexAvailable(): boolean {
|
||||
return resolveCodexDir() !== null;
|
||||
}
|
||||
|
||||
export function getCodexNotFoundMessage(): string {
|
||||
return formatCliNotFoundMessage(CODEX_NOT_FOUND, codexResolver.diagnostics());
|
||||
}
|
||||
|
||||
type CodexRateLimitsRequest = (binaryPath: string, clientVersion: string) => Promise<unknown>;
|
||||
|
||||
const APP_SERVER_TIMEOUT_MS = 10_000;
|
||||
|
||||
@@ -17,11 +17,7 @@ import { execFileSync } from 'node:child_process';
|
||||
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import {
|
||||
createCliExecutableResolver,
|
||||
formatCliNotFoundMessage,
|
||||
type CliResolverHost,
|
||||
} from './cli-executable-resolver.js';
|
||||
import { createCliExecutableResolver, type CliResolverHost } from './cli-executable-resolver.js';
|
||||
|
||||
/**
|
||||
* Directories probed after `which`, read from this CLI's registry entry so the spawn
|
||||
@@ -36,8 +32,6 @@ const COPILOT_SEARCH_DIRS = (): string[] => (getCli('copilot')?.discovery.search
|
||||
*/
|
||||
export const COPILOT_VERSION_REGEX = /GitHub Copilot CLI (\d+\.\d+\.\d+)/;
|
||||
|
||||
const COPILOT_NOT_FOUND = 'GitHub Copilot CLI not found. Install with: npm install -g @github/copilot';
|
||||
|
||||
/**
|
||||
* Run `copilot --version` on a candidate path and return the trimmed version when
|
||||
* it is the GitHub Copilot CLI. Returns null for anything else — a missing
|
||||
@@ -125,10 +119,6 @@ export function isCopilotAvailable(): boolean {
|
||||
return resolveCopilotDir() !== null;
|
||||
}
|
||||
|
||||
export function getCopilotNotFoundMessage(): string {
|
||||
return formatCliNotFoundMessage(COPILOT_NOT_FOUND, copilotResolver.diagnostics());
|
||||
}
|
||||
|
||||
/**
|
||||
* Version reported by the resolved `copilot` binary, or null when copilot is
|
||||
* unavailable. Surfaced through `GET /api/copilot/status` so a misresolution is
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
*/
|
||||
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
||||
import { readdirSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
|
||||
@@ -379,11 +379,6 @@ export function getDeepSeekCliVersion(): string | null {
|
||||
return deepSeekResolver.resolve()?.metadata ?? null;
|
||||
}
|
||||
|
||||
/** Does the named profile exist and can it drive a pane? */
|
||||
export function profileExists(name: string): boolean {
|
||||
return existsSync(join(resolveDshHome(), 'profiles', name, 'package.json'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a DeepSeek session cannot start, or null when it can.
|
||||
*
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import { createCliExecutableResolver, formatCliNotFoundMessage } from './cli-executable-resolver.js';
|
||||
import { createCliExecutableResolver } from './cli-executable-resolver.js';
|
||||
|
||||
/** Common directories where the Gemini CLI binary may be installed */
|
||||
/**
|
||||
@@ -20,7 +20,6 @@ import { createCliExecutableResolver, formatCliNotFoundMessage } from './cli-exe
|
||||
const GEMINI_SEARCH_DIRS = (): string[] => (getCli('gemini')?.discovery.searchDirs ?? []).map(expandHome);
|
||||
|
||||
const geminiResolver = createCliExecutableResolver({ binary: 'gemini', searchDirs: GEMINI_SEARCH_DIRS });
|
||||
const GEMINI_NOT_FOUND = 'Gemini CLI not found. Install with: npm install -g @google/gemini-cli';
|
||||
|
||||
/**
|
||||
* Finds the directory containing the `gemini` binary.
|
||||
@@ -38,7 +37,3 @@ export function resolveGeminiDir(): string | null {
|
||||
export function isGeminiAvailable(): boolean {
|
||||
return resolveGeminiDir() !== null;
|
||||
}
|
||||
|
||||
export function getGeminiNotFoundMessage(): string {
|
||||
return formatCliNotFoundMessage(GEMINI_NOT_FOUND, geminiResolver.diagnostics());
|
||||
}
|
||||
@@ -23,11 +23,7 @@ import { execFileSync } from 'node:child_process';
|
||||
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import {
|
||||
createCliExecutableResolver,
|
||||
formatCliNotFoundMessage,
|
||||
type CliResolverHost,
|
||||
} from './cli-executable-resolver.js';
|
||||
import { createCliExecutableResolver, type CliResolverHost } from './cli-executable-resolver.js';
|
||||
|
||||
/** Common directories where the Grok CLI binary may be installed */
|
||||
/**
|
||||
@@ -49,8 +45,6 @@ const GROK_SEARCH_DIRS = (): string[] => (getCli('grok')?.discovery.searchDirs ?
|
||||
*/
|
||||
export const GROK_VERSION_REGEX = /(?:^|\s)(\d+\.\d+\.\d+)/;
|
||||
|
||||
const GROK_NOT_FOUND = 'Grok CLI not found. Install with: curl -fsSL https://x.ai/cli/install.sh | bash';
|
||||
|
||||
/**
|
||||
* Run `grok --version` on a candidate path and return the version token when it
|
||||
* looks like the coding agent. Returns null for anything else: a missing
|
||||
@@ -137,10 +131,6 @@ export function isGrokAvailable(): boolean {
|
||||
return resolveGrokDir() !== null;
|
||||
}
|
||||
|
||||
export function getGrokNotFoundMessage(): string {
|
||||
return formatCliNotFoundMessage(GROK_NOT_FOUND, grokResolver.diagnostics());
|
||||
}
|
||||
|
||||
/**
|
||||
* Version reported by the resolved `grok` binary, or null when grok is
|
||||
* unavailable. Surfaced through `GET /api/grok/status` so a misresolution is
|
||||
|
||||
+3
-49
@@ -12,7 +12,7 @@ export { Debouncer, KeyedDebouncer } from './debouncer.js';
|
||||
export { startEventLoopMonitor } from './event-loop-monitor.js';
|
||||
export type { EventLoopMonitorHandle } from './event-loop-monitor.js';
|
||||
export { StaleExpirationMap } from './stale-expiration-map.js';
|
||||
export { isProcessRunning, waitForProcessesExit, PROCESS_EXIT_POLL_MS } from './process-exit-wait.js';
|
||||
export { waitForProcessesExit } from './process-exit-wait.js';
|
||||
export {
|
||||
ANSI_ESCAPE_PATTERN_FULL,
|
||||
ANSI_ESCAPE_PATTERN_SIMPLE,
|
||||
@@ -30,59 +30,13 @@ export { assertNever } from './type-safety.js';
|
||||
export { toSingleLine } from './single-line.js';
|
||||
export { wrapWithNice } from './nice-wrapper.js';
|
||||
export { resolveLocalShell, loginShellArgs } from './shell-resolver.js';
|
||||
export {
|
||||
findClaudeDir,
|
||||
getAugmentedPath,
|
||||
getClaudeCliVersion,
|
||||
getClaudeBinaryPath,
|
||||
getClaudeNotFoundMessage,
|
||||
} from './claude-cli-resolver.js';
|
||||
export { getAugmentedPath, getClaudeCliVersion, getClaudeBinaryPath } from './claude-cli-resolver.js';
|
||||
export { spawnPtyWithHelperRepair } from './node-pty-repair.js';
|
||||
export { resolveOpenCodeDir, getOpenCodeNotFoundMessage } from './opencode-cli-resolver.js';
|
||||
export {
|
||||
resolveCodexDir,
|
||||
resolveCodexBinaryPath,
|
||||
isCodexAvailable,
|
||||
getCodexNotFoundMessage,
|
||||
readCodexPlanUsage,
|
||||
} from './codex-cli-resolver.js';
|
||||
export { resolveGeminiDir, isGeminiAvailable, getGeminiNotFoundMessage } from './gemini-cli-resolver.js';
|
||||
export {
|
||||
resolveAntigravityDir,
|
||||
isAntigravityAvailable,
|
||||
getAntigravityNotFoundMessage,
|
||||
} from './antigravity-cli-resolver.js';
|
||||
export { resolvePiDir, isPiAvailable, getPiCliVersion, getPiNotFoundMessage } from './pi-cli-resolver.js';
|
||||
export { resolveGrokDir, isGrokAvailable, getGrokCliVersion, getGrokNotFoundMessage } from './grok-cli-resolver.js';
|
||||
export {
|
||||
resolveDeepSeekDir,
|
||||
isDeepSeekAvailable,
|
||||
isDeepSeekRunnable,
|
||||
getDeepSeekCliVersion,
|
||||
getDeepSeekNotFoundMessage,
|
||||
listDeepSeekProfiles,
|
||||
resolveDefaultDeepSeekProfile,
|
||||
isLaunchableProfile,
|
||||
resolveDshHome,
|
||||
profileExists,
|
||||
} from './deepseek-cli-resolver.js';
|
||||
export type { DeepSeekProfile, DeepSeekProfileKind } from './deepseek-cli-resolver.js';
|
||||
export { compileFileQuery, matchFileQuery } from './file-query.js';
|
||||
export type { FileQueryMatcher } from './file-query.js';
|
||||
export { resolveOmpDir, isOmpAvailable, getOmpNotFoundMessage, getOmpCliVersion } from './omp-cli-resolver.js';
|
||||
export {
|
||||
resolveCopilotDir,
|
||||
isCopilotAvailable,
|
||||
getCopilotNotFoundMessage,
|
||||
getCopilotCliVersion,
|
||||
} from './copilot-cli-resolver.js';
|
||||
export { readCopilotPlanUsage, resolveCopilotToken } from './copilot-plan-usage.js';
|
||||
export {
|
||||
boundedPathExists,
|
||||
describeUnknownPath,
|
||||
probePath,
|
||||
probePathKind,
|
||||
isNearStalledPath,
|
||||
unknownPathReason,
|
||||
} from './bounded-path-probe.js';
|
||||
export type { PathProbeState, PathProbeKind, PathProbeOptions } from './bounded-path-probe.js';
|
||||
export type { PathProbeOptions } from './bounded-path-probe.js';
|
||||
@@ -17,11 +17,7 @@ import { execFileSync } from 'node:child_process';
|
||||
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import {
|
||||
createCliExecutableResolver,
|
||||
formatCliNotFoundMessage,
|
||||
type CliResolverHost,
|
||||
} from './cli-executable-resolver.js';
|
||||
import { createCliExecutableResolver, type CliResolverHost } from './cli-executable-resolver.js';
|
||||
|
||||
/**
|
||||
* Directories probed after `which`, read from this CLI's registry entry so the spawn
|
||||
@@ -42,8 +38,6 @@ const OMP_SEARCH_DIRS = (): string[] => (getCli('omp')?.discovery.searchDirs ??
|
||||
*/
|
||||
export const OMP_VERSION_REGEX = /(?:^|\s)omp\/(\d+\.\d+\.\d+)/;
|
||||
|
||||
const OMP_NOT_FOUND = 'OMP CLI not found. Install with: curl -fsSL https://omp.sh/install | sh';
|
||||
|
||||
/**
|
||||
* Run `omp --version` on a candidate path and return the trimmed version when
|
||||
* it looks like the coding agent. Returns null for anything else — a missing
|
||||
@@ -125,10 +119,6 @@ export function isOmpAvailable(): boolean {
|
||||
return resolveOmpDir() !== null;
|
||||
}
|
||||
|
||||
export function getOmpNotFoundMessage(): string {
|
||||
return formatCliNotFoundMessage(OMP_NOT_FOUND, ompResolver.diagnostics());
|
||||
}
|
||||
|
||||
/**
|
||||
* Version reported by the resolved `omp` binary, or null when omp is
|
||||
* unavailable. Surfaced through `GET /api/omp/status` so a misresolution is
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import { createCliExecutableResolver, formatCliNotFoundMessage } from './cli-executable-resolver.js';
|
||||
import { createCliExecutableResolver } from './cli-executable-resolver.js';
|
||||
|
||||
/** Common directories where the OpenCode CLI binary may be installed */
|
||||
/**
|
||||
@@ -20,7 +20,6 @@ import { createCliExecutableResolver, formatCliNotFoundMessage } from './cli-exe
|
||||
const OPENCODE_SEARCH_DIRS = (): string[] => (getCli('opencode')?.discovery.searchDirs ?? []).map(expandHome);
|
||||
|
||||
const openCodeResolver = createCliExecutableResolver({ binary: 'opencode', searchDirs: OPENCODE_SEARCH_DIRS });
|
||||
const OPENCODE_NOT_FOUND = 'OpenCode CLI not found. Install with: curl -fsSL https://opencode.ai/install | bash';
|
||||
|
||||
/**
|
||||
* Finds the directory containing the `opencode` binary.
|
||||
@@ -39,7 +38,3 @@ export function resolveOpenCodeDir(): string | null {
|
||||
export function isOpenCodeAvailable(): boolean {
|
||||
return resolveOpenCodeDir() !== null;
|
||||
}
|
||||
|
||||
export function getOpenCodeNotFoundMessage(): string {
|
||||
return formatCliNotFoundMessage(OPENCODE_NOT_FOUND, openCodeResolver.diagnostics());
|
||||
}
|
||||
@@ -19,11 +19,7 @@ import { execFileSync } from 'node:child_process';
|
||||
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import {
|
||||
createCliExecutableResolver,
|
||||
formatCliNotFoundMessage,
|
||||
type CliResolverHost,
|
||||
} from './cli-executable-resolver.js';
|
||||
import { createCliExecutableResolver, type CliResolverHost } from './cli-executable-resolver.js';
|
||||
|
||||
/** Common directories where the Pi CLI binary may be installed */
|
||||
/**
|
||||
@@ -48,8 +44,6 @@ const PI_SEARCH_DIRS = (): string[] => (getCli('pi')?.discovery.searchDirs ?? []
|
||||
*/
|
||||
export const PI_VERSION_REGEX = /(?:^|\s)(\d+\.\d+\.\d+)/;
|
||||
|
||||
const PI_NOT_FOUND = 'Pi CLI not found. Install with: npm install -g --ignore-scripts @earendil-works/pi-coding-agent';
|
||||
|
||||
/**
|
||||
* Run `pi --version` on a candidate path and return the trimmed version when it
|
||||
* looks like the coding agent. Returns null for anything else — a missing
|
||||
@@ -132,10 +126,6 @@ export function isPiAvailable(): boolean {
|
||||
return resolvePiDir() !== null;
|
||||
}
|
||||
|
||||
export function getPiNotFoundMessage(): string {
|
||||
return formatCliNotFoundMessage(PI_NOT_FOUND, piResolver.diagnostics());
|
||||
}
|
||||
|
||||
/**
|
||||
* Version reported by the resolved `pi` binary, or null when pi is unavailable.
|
||||
* Surfaced through `GET /api/pi/status` so a misresolution is diagnosable from the UI.
|
||||
|
||||
+5
-5
@@ -56,13 +56,13 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
||||
|
||||
**Command palette + shortcut registry**: `Ctrl/Cmd/Alt+K` opens the session palette; shortcuts live in a rebindable registry (`DEFAULT_SHORTCUTS`/`getShortcutRegistry()`/`matchesShortcutEvent()` in app.js, overrides in `settings.shortcutOverrides`). ⚠️ Palette-chord keys must ALSO be swallowed in `attachCustomKeyEventHandler` (terminal-ui.js) or xterm writes the control byte into the PTY. ⚠️ The global Escape handler (app.js) calls EVERY close method on every Escape, in the capture phase, so a close method that does more than hide (the palette and Session Manager restore focus) must return early when its overlay is not open. ⚠️ `saveAppSettings()` rebuilds settings from the DOM, so keys edited elsewhere (`shortcutOverrides`, `showTokenCount`, `showCost`) need explicit `_prev` carry-over. ⚠️ **Smart copy (`Ctrl+C`)**: with no selection it must `return true` without `preventDefault()` or the interrupt is lost; keep `copyTerminalSelection` out of `SHORTCUT_ACTIONS`. The gate tests the CLEANED selection (`CodemanCopySelection.clean`: trailing padding, plus a LEADING margin only up to the width the CLI declares in `capabilities.transcriptGutter`, never one derived from the pane); the strip is not idempotent, so clean once and pass the RAW selection on, and leave Alt+drag column selections untouched. → [architecture-invariants#command-palette-and-shortcut-registry](../../docs/architecture-invariants.md#command-palette-and-shortcut-registry)
|
||||
|
||||
**Per-device vs synced settings**: the `displayKeys` set in settings-ui.js is a **client-side merge policy**, not a wire filter. A display key seeds from the server only when localStorage has no value for it, which is what prevents one device overwriting another; `showPlanUsageLimits` is additionally `delete`d from the incoming payload outright. Separately, `SettingsUpdateSchema` is `.strict()` and simply **does not declare** `skin`, `showFileViewerButton`, `showCronButton`, `webglRendererEnabled`, `localEchoEnabled`, `keyboardHoldsRows`, `cjkInputEnabled`, or `extendedKeyboardBar`, so sending one of those is a validation error. The rest (`showResponseViewer`, `showPlanUsageLimits`, `language`, and most `show*` keys) ARE in the schema and do persist server-side; they are per-device by client policy only. ⚠️ Adding a new per-device setting means deciding **both** questions: membership in `displayKeys`, and presence in the schema.
|
||||
**Per-device vs synced settings**: the `displayKeys` set in settings-ui.js is a **client-side merge policy**, not a wire filter. A display key seeds from the server only when localStorage has no value for it, which is what prevents one device overwriting another; `showPlanUsageLimits` is additionally `delete`d from the incoming payload outright. Separately, `SettingsUpdateSchema` is `.strict()` and simply **does not declare** `skin`, `showFileViewerButton`, `showCronButton`, `webglRendererEnabled`, `localEchoEnabled`, `keyboardHoldsRows`, `cjkInputEnabled`, `cjkInputHoldUntilEnter`, or `extendedKeyboardBar`, so sending one of those is a validation error. The rest (`showResponseViewer`, `showPlanUsageLimits`, `language`, and most `show*` keys) ARE in the schema and do persist server-side; they are per-device by client policy only. ⚠️ Adding a new per-device setting means deciding **both** questions: membership in `displayKeys`, and presence in the schema.
|
||||
|
||||
**Settings surface** (`#appSettingsModal` + `#sessionOptionsModal` + `#createCaseModal`): one `set-*` language shared through a single `:is(...)` id scope in styles.css. App Settings' rail is a table of contents over ONE scrolling document (`switchSettingsTab` scrolls); Session Options and Add Case really switch (`switchOptionsTab` / `switchCaseModalTab`), and their larger per-modal size blocks are the design, not drift. ⚠️ **The load/save contract is `getElementById` by id**: renaming or dropping a control id silently stops it loading or saving. ⚠️ The Session Options "Session" entry still keys off `context` (label-only rename). ⚠️ Add Case keeps its legacy `.form-row` markup via an adapter; every `<details>` there needs `.set-adv-chev` plus both marker suppressions. ⚠️ Model cards and the effort segment are views over hidden `<select>`s, which stay the source of truth. ⚠️ `.modal-tabs*` classes are retired; `admin-ui.js` needs `.set-rail-items` + `.set-doc` to survive any restructure. Guard: `test/app-settings-structure.test.ts`. → [architecture-invariants#settings-surface-app-settings-session-options-add-case](../../docs/architecture-invariants.md#settings-surface-app-settings-session-options-add-case)
|
||||
|
||||
**Header button visibility**: most header controls are opt-in and hidden by a marker class (`btn-multimonitor--hidden`, `btn-response-viewer-header--hidden`, `btn-file-viewer--hidden`, `btn-cron--hidden`, and the desktop-gated `btn-split--hidden` / `btn-tile-grid--hidden`, which also need a `@media (max-width: 1179px)` backstop) that `applyHeaderVisibilitySettings()` (settings-ui.js) toggles after settings load; the multi-monitor button is instead stripped at render by `renderIndexHtml`. ⚠️ Hiding must go through the marker class: the base rules are `display:inline-flex !important`, so an inline style cannot override them. Current desktop default is WS/CPU/MEM + File Viewer + Tiles (1180px and wider) + gear, with the token chip and lifecycle-log button OFF. ⚠️ New header controls must not leak onto phones; `test/mobile-header-buttons-policy.test.ts` is the static guard. The one opt-in exception is File Viewer (#759): `mobile.css` no longer hides it at phone width, so it stays off a phone only through the handheld default in `getDefaultSettings()` and the `html.mobile-init` startup rule (both pinned by that test), and shows once the setting is switched on on that phone. → [architecture-invariants#header-button-visibility-multi-monitor-response-viewer-file-viewer-cron](../../docs/architecture-invariants.md#header-button-visibility-multi-monitor-response-viewer-file-viewer-cron)
|
||||
|
||||
**Terminal font weight** (`terminalFontWeight` / `terminalFontWeightBold`, per-device, default = xterm's own `normal`/`bold`): Claude Code's markdown bold is a bare `ESC[1m`, so the weight step is its only cue. `CodemanTerminalFont.resolveWeights()` (constants.js, pure) resolves each slot against **its own** xterm default. ⚠️ The `@font-face` for `fonts/jetbrains-mono-variable.woff2` must stay declared `100 800` (the browser synthesizes from the descriptor, not the file); narrowing it silently makes the setting a no-op. ⚠️ A live save must reach both echo overlays (`refreshFont()`) and open Agent Teams panes. ⚠️ Leave `_awaitTerminalFont()` untouched. Test: `test/terminal-font-weight.test.ts`. → [architecture-invariants#terminal-font-weight](../../docs/architecture-invariants.md#terminal-font-weight)
|
||||
**Terminal font weight** (`terminalFontWeight` / `terminalFontWeightBold`, per-device, default = xterm's own `normal`/`bold`): Claude Code's markdown bold is a bare `ESC[1m`, so the weight step is its only cue. `CodemanTerminalFont.resolveWeights()` (constants.js, pure) resolves each slot against **its own** xterm default. ⚠️ The `@font-face` for `fonts/jetbrains-mono-variable.woff2` must stay declared `100 800` (the browser synthesizes from the descriptor, not the file); narrowing it silently makes the setting a no-op. ⚠️ A live save must reach both echo overlays (`refreshFont()`) and every open tile and split pane (`_forEachTile`). ⚠️ Leave `_awaitTerminalFont()` untouched. Test: `test/terminal-font-weight.test.ts`. → [architecture-invariants#terminal-font-weight](../../docs/architecture-invariants.md#terminal-font-weight)
|
||||
|
||||
**Theme skins / branding / i18n**: `skin` selects a palette via `data-skin` on `<html>`, applied by an **inline pre-paint script** in `index.html` reading `localStorage['codeman:skin']` to avoid a flash of wrong theme. ⚠️ A skin is **four things that must stay in sync**, and missing any one degrades silently: the `html[data-skin="…"]` token block in `styles.css`, the xterm ANSI palette in `terminal-ui.js`, the pre-paint allowlist, and the Settings picker (both in `index.html`). `test/skin-themes.test.ts` is the static guard. Light skins additionally need `color-scheme: light` and xterm `minimumContrastRatio: 4.5`, and `applyTerminalSkin()` must call the local-echo overlay's `refreshFont()` because it caches the terminal fg/bg. `displayName` changes user-facing browser branding only and must NEVER rename npm package, CLI, API, storage, CSS, or protocol identifiers. `language` (`en`/`zh-CN`) keeps English as the canonical source so live switching stays reversible. User display names flow through `textContent`/attribute APIs and the server title's HTML escaper, never `innerHTML`. → [architecture-invariants#theme-skins](../../docs/architecture-invariants.md#theme-skins)
|
||||
|
||||
@@ -82,11 +82,11 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
||||
|
||||
**WebSocket output-gap reconcile** (`_wsOutputGapSession`, app.js): output frames carry no sequence number, so an unintentional WS close while SSE stays up marks the session and the next open reconciles. ⚠️ The marker is cleared only once a repaint actually happened (`_markTerminalBufferReconciled()`, never in a `finally`). → [architecture-invariants#websocket-output-gap-reconcile](../../docs/architecture-invariants.md#websocket-output-gap-reconcile)
|
||||
|
||||
**Dismissing the on-screen keyboard** (`terminal-ui.js`): two gestures blur the terminal's hidden textarea. (1) `_installMobileKeyboardDismiss()`, a document `touchend` that must never fire inside `#terminalContainer` or on a control (`MOBILE_KEYBOARD_DISMISS_EXEMPT_SELECTOR`, via `closest()`; roving-tabindex items sit at `tabindex=-1`, so the grouped rail's are listed as `[role="treeitem"]`). (2) In `_handleMobileTerminalTap`, a second tap on inert `content` blurs; the prompt row keeps focus-then-position. ⚠️ A scroll also ends in `touchend`: both classifiers must share one threshold (`TAP_THRESHOLD` reads `MOBILE_KEYBOARD_DISMISS_TAP_SLOP`), and multi-touch is never a tap. ⚠️ An accessory key that keeps the keyboard up (`ACCESSORY_REFOCUS_ACTIONS`, keyboard-accessory.js) cancels its `mousedown` default, so the press does not blur the terminal; the click-time `terminal.focus()` stays as the fallback. Letting the tap blur and refocusing afterwards made every such key start a dismissal, a blur/focus pair per tap. A first tap on clear/compact only arms the confirm and is treated the same (`test/accessory-keeps-terminal-focus.test.ts`). ⚠️ CI cannot see the only test for (1): run `npm run test:mobile -- test/mobile/keyboard.test.ts` by hand and diff the FAIL list against master. → [architecture-invariants#dismissing-the-on-screen-keyboard](../../docs/architecture-invariants.md#dismissing-the-on-screen-keyboard)
|
||||
**Dismissing the on-screen keyboard** (`terminal-ui.js`): two gestures blur the terminal's hidden textarea. (1) `_installMobileKeyboardDismiss()`, a document `touchend` that must never fire inside `#terminalContainer` or on a control (`MOBILE_KEYBOARD_DISMISS_EXEMPT_SELECTOR`, via `closest()`; roving-tabindex items sit at `tabindex=-1`, so the grouped rail's are listed as `[role="treeitem"]`). (2) In `_handleMobileTerminalTap`, a second tap on inert `content` blurs; the prompt row keeps focus-then-position. ⚠️ A scroll also ends in `touchend`: both classifiers must share one threshold (`TAP_THRESHOLD` reads `MOBILE_KEYBOARD_DISMISS_TAP_SLOP`), and multi-touch is never a tap. ⚠️ An accessory key that keeps the keyboard up (`ACCESSORY_REFOCUS_ACTIONS`, keyboard-accessory.js) cancels its `mousedown` default, so the press does not blur the terminal; the click-time `terminal.focus()` stays as the fallback. Letting the tap blur and refocusing afterwards made every such key start a dismissal, a blur/focus pair per tap. A first tap on clear/compact only arms the confirm and is treated the same (`test/accessory-keeps-terminal-focus.test.ts`). ⚠️ The content touchstart blur skips the visible `#cjkInput` (`_contentTouchStartBlurs()`), or every swipe on the live screen closed its keyboard; a tap still closes it (inert content, a link, a long press). On phones `updateLayoutForKeyboard()` also moves `.app` by `visualViewport.offsetTop` while the keyboard is up, and lifts the fixed bars inside it from `.app`'s bottom (architecture-invariants, Folding devices section). ⚠️ CI cannot see the only test for (1): run `npm run test:mobile -- test/mobile/keyboard.test.ts` by hand and diff the FAIL list against master. → [architecture-invariants#dismissing-the-on-screen-keyboard](../../docs/architecture-invariants.md#dismissing-the-on-screen-keyboard)
|
||||
|
||||
**Phone toolbar: Enter replaces Shell** (post-1.8.0): inside `@media (max-width: 599px)` `btn-shell` is `display:none` and `btn-enter` takes its slot (`order: 4`); starting a shell moved into the Run dropdown (`Terminal / Shell` → `setRunMode('shell')` → `run()` → `runShell()`, button label "Run SH"). `runMode` is `z.string().max(20)` server-side, so new modes need no schema change. Desktop and tablet keep the green Run Shell button unchanged.
|
||||
|
||||
⚠️ **`sendEnterKey()` MUST go through `terminal._core.coreService.triggerDataEvent('\r', true)`** — not `sendInput()`, and never a raw POST to `/api/sessions/:id/input`. `localEchoEnabled` defaults to `MobileDetection.isTouchDevice()`, so on every phone the characters you type are buffered in the `LocalEchoOverlay` and have **never reached the PTY**; the `onData` Enter branch in terminal-ui.js is what flushes `pendingText` first and only then sends `\r` (after an 80ms delay so text lands first). Sending a bare `\r` submits an empty line and strands the typed text on screen, so the button looks dead. Replaying the keypress reuses the overlay flush, the flushed-offset cleanup and the ordering instead of reimplementing them. `KeyboardAccessory.sendKey()` is for escape sequences (arrows/Esc) and is the WRONG template to copy for input.
|
||||
⚠️ **`sendEnterKey()` MUST go through `terminal._core.coreService.triggerDataEvent('\r', true)`** — not `sendInput()`, and never a raw POST to `/api/sessions/:id/input`. `localEchoEnabled` defaults to `MobileDetection.isTouchDevice()`, so on every phone the characters you type are buffered in the `LocalEchoOverlay` and have **never reached the PTY**; the `onData` Enter branch in terminal-ui.js is what flushes `pendingText` first and only then sends `\r` (after an 80ms delay so text lands first). Sending a bare `\r` submits an empty line and strands the typed text on screen, so the button looks dead. Replaying the keypress reuses the overlay flush, the flushed-offset cleanup and the ordering instead of reimplementing them. `KeyboardAccessory.sendKey()` is for escape sequences (arrows/Esc) and is the WRONG template to copy for input. The one deliberate exception: while the CJK field is visible (`#cjkInput.cjk-input-visible`), `onData` drops everything under `window.cjkActive`, so `sendEnterKey()` calls `CjkInput.submit()` instead, which sends what the field holds (a Send on Enter answer, or live text not yet flushed) and then Enter.
|
||||
|
||||
⚠️ **Skin overrides outrank plain class rules.** `styles.css` nests its skin block inside `html:not([data-skin="og"]) { … }`, so a bare `.btn-toolbar` rule in there resolves to specificity **(0,2,1)** and beats a `.btn-toolbar.btn-x` rule **(0,2,0)** in `mobile.css` regardless of load order. Toolbar-button colors set from mobile.css therefore need `!important`: that is why mobile.css leans on it so heavily. Symptom: only your `!important` properties land and everything else silently renders in generic toolbar grey. Press feedback on the phone bars sidesteps this: the `:active` rules for `.btn-toolbar`, the mobile icon buttons and `.accessory-btn` (mobile.css) use `transform` and `filter` only, which nothing on these buttons sets at a higher specificity, so one rule reads the same on every skin; a background `:active` lost to the skin block on all but og, and an inset `box-shadow` lost to the skin hover rules, which is why neither is used. The light skins darken instead of brightening, and `prefers-reduced-motion` drops the scale.
|
||||
|
||||
@@ -94,6 +94,6 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
||||
|
||||
**SSE staleness watchdog** (`computeSseStale()` in constants.js, `_checkSseStale()` + a 5s interval in app.js): an `EventSource` can stop delivering without erroring, so the client forces a reconnect when nothing arrives. ⚠️ The server keepalive must stay the named `sse:heartbeat` event (`cleanupDeadClients()`, sse-stream-manager.ts), never an SSE comment, which `EventSource` cannot observe; its no-op client listener must stay registered. ⚠️ Judge staleness only while `connected` and online (the loop breaker). ⚠️ The liveness stamp lives inside `addListener`. ⚠️ Clear the interval only at the top of `connectSSE()`, or intervals stack. ⚠️ The watchdog cannot see an attempt that never OPENS (no response headers: no `open`, no `error`, never `connected`), so each attempt is bounded by `SSE_CONNECT_TIMEOUT_MS` (15s, `CodemanSseStale.CONNECT_TIMEOUT_MS`) and then retried through `_handleSseConnectionFailure()`, the same backoff `onerror` uses. Its timer is cleared at the top of `connectSSE()` BEFORE the offline early return, on `open`, and in `_handleSseConnectionFailure()`; the timer and the handler both ignore an `EventSource` that has been replaced. The window `offline` handler leaves it running on purpose (`navigator.onLine` can report offline on a working network). Tests: `test/sse-connect-timeout.test.ts`. → [architecture-invariants#sse-staleness-watchdog](../../docs/architecture-invariants.md#sse-staleness-watchdog)
|
||||
|
||||
**Z-index layers** (keep new overlays consistent with this stack): local echo overlay (7; with local echo on it also draws the iOS IME composition preview, as an underlined tail after its pending text via `setComposition`), iOS IME composition preview span when local echo is off (6 inside `.xterm-helpers`, whose own z-index 5 is its EFFECTIVE layer, so it sits UNDER the overlay and must never be used while the overlay shows text), terminal touch-selection bar (900, below floating agent windows), subagent windows + split picker menu + Tiles count menu (1000), plan agents (1100), mobile/tablet fixed header (1200), modals on ≤768px (1300, must beat the fixed header), log viewers (2000), connection-loss overlay (2500), image popups (3000), response viewer (5000, backdrop 4999), folder grid (5090, above the response viewer it opens from, below the file preview its tiles open), file-preview overlay (5100, must outrank the response viewer that launches it), toasts/path picker (10000+), custom-model center-status banner (10001; its `[hidden]` must re-assert `display: none` or `dismiss()` leaves an invisible click-blocker), custom-model swap-confirm/context-warning modals (10010). → [architecture-invariants#z-index-layers](../../docs/architecture-invariants.md#z-index-layers)
|
||||
**Z-index layers** (keep new overlays consistent with this stack): local echo overlay (7; with local echo on it also draws the iOS IME composition preview, as an underlined tail after its pending text via `setComposition`), iOS IME composition preview span when local echo is off (6 inside `.xterm-helpers`, whose own z-index 5 is its EFFECTIVE layer, so it sits UNDER the overlay and must never be used while the overlay shows text), terminal touch-selection bar (900, below floating agent windows), subagent windows + split picker menu + Tiles count menu (1000), mobile/tablet fixed header (1200), modals on ≤768px (1300, must beat the fixed header), log viewers (2000), connection-loss overlay (2500), image popups (3000), response viewer (5000, backdrop 4999), folder grid (5090, above the response viewer it opens from, below the file preview its tiles open), file-preview overlay (5100, must outrank the response viewer that launches it), toasts/path picker (10000+), custom-model center-status banner (10001; its `[hidden]` must re-assert `display: none` or `dismiss()` leaves an invisible click-blocker), custom-model swap-confirm/context-warning modals (10010). → [architecture-invariants#z-index-layers](../../docs/architecture-invariants.md#z-index-layers)
|
||||
|
||||
**Keyboard shortcuts**: Escape (close), Ctrl+? (shortcut overlay), Ctrl/Cmd/Alt+K (session palette), Ctrl+Tab (next), Alt+[/] (prev/next tab), Alt+1-9 (switch tab), Ctrl+Shift+{/} (move tab left/right), Shift+Enter or Ctrl+Enter (newline), Ctrl+C (copy selection, else interrupt) / Ctrl+Shift+C (copy, never interrupts), Ctrl+L (clear), Ctrl+Shift+R (restore size), Ctrl+Shift+V (voice input), Ctrl/Cmd +/- (font), Shift+Wheel (local scrollback when mouse passthrough is active), Shift+drag (start a selection in a stripped-DECSET pane, where xterm's own Shift branch is unreachable and a Shift+drag used to select nothing; `_installShiftDragSelection`), right-click (copy the selection, the mintty/PuTTY convention, since xterm paints into a canvas and the native menu has no Copy for it; with nothing selected the native menu is left alone). Rebindable via the registry. ⚠️ **Ctrl+W is deliberately NOT bound** (owner decision): it is delete-word in every shell and agent CLI, and as Close Session it killed sessions with no confirm; `close-session` keeps `bindings: []` and stays bindable (`test/ctrl-w-never-closes.test.ts`).
|
||||
@@ -1,8 +1,6 @@
|
||||
/** @fileoverview Owner-scoped tab-layout capabilities exposed to route modules. */
|
||||
import type { TabLayoutService } from '../../tab-layout-service.js';
|
||||
|
||||
export type { LegacyOrderActor, LegacyOrderPutResult, SessionOrderProjectionChange } from '../../tab-layout-service.js';
|
||||
|
||||
export interface TabLayoutPort {
|
||||
readonly tabLayouts: TabLayoutService;
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
*
|
||||
* @mixin Extends CodemanApp.prototype via Object.assign
|
||||
* @dependency app.js (CodemanApp class must be defined)
|
||||
* @loadorder 14 of 15 — loaded after ralph-wizard.js
|
||||
* @loadorder 14 of 15 — loaded after session-ui.js
|
||||
*/
|
||||
|
||||
// Codeman — Centralized API fetch helpers for CodemanApp
|
||||
|
||||
+29
-68
@@ -11,7 +11,6 @@
|
||||
* panels-ui.js — Subagent panel, agent teams, project insights, file browser, log viewer,
|
||||
* image popups, monitor, token stats, toast, system stats
|
||||
* session-ui.js — Quick start, session options modal, case settings, mobile case picker
|
||||
* ralph-wizard.js — Ralph Loop wizard modal
|
||||
* api-client.js — API helper methods (fetch wrappers)
|
||||
* subagent-windows.js — Floating subagent terminal windows
|
||||
*
|
||||
@@ -299,13 +298,6 @@ const _SSE_HANDLER_MAP = [
|
||||
[SSE_EVENTS.TUNNEL_QR_REGENERATED, '_onTunnelQrRegenerated'],
|
||||
[SSE_EVENTS.TUNNEL_QR_AUTH_USED, '_onTunnelQrAuthUsed'],
|
||||
|
||||
// Plan orchestration
|
||||
[SSE_EVENTS.PLAN_SUBAGENT, '_onPlanSubagent'],
|
||||
[SSE_EVENTS.PLAN_PROGRESS, '_onPlanProgress'],
|
||||
[SSE_EVENTS.PLAN_STARTED, '_onPlanStarted'],
|
||||
[SSE_EVENTS.PLAN_CANCELLED, '_onPlanCancelled'],
|
||||
[SSE_EVENTS.PLAN_COMPLETED, '_onPlanCompleted'],
|
||||
|
||||
// Orchestrator loop
|
||||
[SSE_EVENTS.ORCHESTRATOR_STATE_CHANGED, '_onOrchestratorStateChanged'],
|
||||
[SSE_EVENTS.ORCHESTRATOR_PLAN_PROGRESS, '_onOrchestratorPlanProgress'],
|
||||
@@ -863,31 +855,11 @@ class CodemanApp {
|
||||
// Once set, never recalculated. Persisted to localStorage and server.
|
||||
this.subagentParentMap = new Map();
|
||||
|
||||
// Agent Teams tracking
|
||||
this.teams = new Map(); // Map<teamName, TeamConfig>
|
||||
this.teamTasks = new Map(); // Map<teamName, TeamTask[]>
|
||||
this.teammateMap = new Map(); // Map<agentId-prefix, {name, color, teamName}> for quick lookup
|
||||
|
||||
// Teammate tmux pane terminals (Agent Teams feature)
|
||||
this.teammatePanesByName = new Map(); // Map<name, { paneTarget, sessionId, color }>
|
||||
this.teammateTerminals = new Map(); // Map<agentId, { terminal, fitAddon, paneTarget, sessionId, resizeObserver }>
|
||||
|
||||
this.terminalBufferCache = new Map(); // Map<sessionId, string> — client-side cache for instant tab re-visits (max 20)
|
||||
|
||||
this.ralphStatePanelCollapsed = true; // Default to collapsed
|
||||
this.ralphClosedSessions = new Set(); // Sessions where user explicitly closed Ralph panel
|
||||
|
||||
// Plan subagent windows (visible agents during plan generation)
|
||||
this.planSubagents = new Map(); // Map<agentId, { type, model, status, startTime, element, relativePos }>
|
||||
this.planSubagentWindowZIndex = ZINDEX_PLAN_SUBAGENT_BASE;
|
||||
this.planGenerationStopped = false; // Flag to ignore SSE events after Stop
|
||||
this.planAgentsMinimized = false; // Whether agent windows are minimized to tab
|
||||
|
||||
// Wizard dragging state
|
||||
this.wizardDragState = null; // { startX, startY, startLeft, startTop, isDragging }
|
||||
this.wizardDragListeners = null; // { move, up } for cleanup
|
||||
this.wizardPosition = null; // { left, top } - null means centered
|
||||
|
||||
// Project Insights tracking (active Bash tools with clickable file paths)
|
||||
this.projectInsights = new Map(); // Map<sessionId, ActiveBashTool[]>
|
||||
this.logViewerWindows = new Map(); // Map<windowId, { element, eventSource, filePath }>
|
||||
@@ -1819,15 +1791,6 @@ class CodemanApp {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Re-dock a session: close its window (which re-docks via its unload
|
||||
* announcement) and clear dashboard state now. */
|
||||
redockSession(id) {
|
||||
const win = this.detachedWindows.get(id);
|
||||
if (win && !win.closed) { try { win.close(); } catch {} }
|
||||
this._postWindowMessage({ type: 'close-request', id });
|
||||
this._redock(id);
|
||||
}
|
||||
|
||||
/** Clear all dashboard-side detached state/timers for a session, and take its
|
||||
* sizing back: the popup owned the pane while it was open, so the dashboard's
|
||||
* record of it is stale and the session it is showing needs re-measuring.
|
||||
@@ -4966,6 +4929,11 @@ class CodemanApp {
|
||||
document.body.classList.toggle('cjk-input-visible', !!showCjk);
|
||||
cjkEl.style.display = showCjk ? 'block' : 'none';
|
||||
cjkEl.setAttribute('aria-hidden', showCjk ? 'false' : 'true');
|
||||
if (typeof CjkInput !== 'undefined') {
|
||||
CjkInput.setHoldUntilEnter?.(
|
||||
!!(settings.cjkInputHoldUntilEnter ?? defaults.cjkInputHoldUntilEnter ?? false)
|
||||
);
|
||||
}
|
||||
if (!showCjk) window.cjkActive = false;
|
||||
if (typeof KeyboardHandler !== 'undefined') KeyboardHandler.updateLayoutForKeyboard();
|
||||
}
|
||||
@@ -4989,8 +4957,6 @@ class CodemanApp {
|
||||
this._xtermSnapshots?.clear();
|
||||
}
|
||||
this.projectInsights.clear();
|
||||
this.teams.clear();
|
||||
this.teamTasks.clear();
|
||||
// Clear all idle timers to prevent stale timers from firing
|
||||
for (const timer of this.idleTimers.values()) {
|
||||
clearTimeout(timer);
|
||||
@@ -5074,10 +5040,6 @@ class CodemanApp {
|
||||
// wrapping) clipped xterm's bottom rows behind the toolbar until a tab
|
||||
// switch or a window resize.
|
||||
// Clear any other orphaned timers
|
||||
if (this.planLoadingTimer) {
|
||||
clearInterval(this.planLoadingTimer);
|
||||
this.planLoadingTimer = null;
|
||||
}
|
||||
if (this.timerCountdownInterval) {
|
||||
clearInterval(this.timerCountdownInterval);
|
||||
this.timerCountdownInterval = null;
|
||||
@@ -9422,7 +9384,7 @@ class CodemanApp {
|
||||
|
||||
// `skipSnapshot`: the tile grid opening on the session it parks
|
||||
// (tile-grid.js openTileGrid), whose snapshot closing the grid discards.
|
||||
_cleanupPreviousSession(newSessionId, { skipSnapshot = false } = {}) {
|
||||
_cleanupPreviousSession(newSessionId, { skipSnapshot = false, keepCjkDraft = false } = {}) {
|
||||
// Snapshot the OUTGOING session's xterm rendered state (viewport + scrollback +
|
||||
// colors/attrs) before the terminal gets cleared/reset. Lets us restore the
|
||||
// exact view on switch-back rather than replaying codex's byte stream, which
|
||||
@@ -9475,8 +9437,16 @@ class CodemanApp {
|
||||
// Clear CJK input to prevent sending stale text to the wrong session.
|
||||
// Must go through CjkInput.clear() — a raw value wipe leaves the module's
|
||||
// pending flush timers armed and drops the phantom char it relies on.
|
||||
// A held Send on Enter draft survives a reload of the same session: nothing
|
||||
// switched, and the answer would be gone. On a real switch it is stashed for
|
||||
// the session being left (selectSession restores it on the way back), so a
|
||||
// stray swipe does not lose it. Live mode still clears, since a pending
|
||||
// debounced flush could fire mid-reconnect.
|
||||
if (typeof CjkInput !== 'undefined') {
|
||||
CjkInput.clear();
|
||||
if (!(keepCjkDraft && CjkInput.holdUntilEnter)) {
|
||||
if (this.activeSessionId) CjkInput.stashDraft?.(this.activeSessionId);
|
||||
CjkInput.clear();
|
||||
}
|
||||
} else {
|
||||
const cjkEl = document.getElementById('cjkInput');
|
||||
if (cjkEl) cjkEl.value = '';
|
||||
@@ -10016,11 +9986,19 @@ class CodemanApp {
|
||||
if (this._tileGrid.has(sessionId)) return this._selectTiledSession(sessionId, options);
|
||||
if (options?.auto === true && !options?.leaveTiles) return;
|
||||
this.closeTileGrid({ keepStored: true, reselect: false });
|
||||
// The focused tile's Send on Enter draft: the null below hides that
|
||||
// session from _cleanupPreviousSession, which would clear it unstashed.
|
||||
if (typeof CjkInput !== 'undefined' && this.activeSessionId) CjkInput.stashDraft?.(this.activeSessionId);
|
||||
// The parked terminal still holds what it showed before the grid opened;
|
||||
// with no active id, the switch below snapshots none of it.
|
||||
this.activeSessionId = null;
|
||||
}
|
||||
// A reload of the session already shown (tapping its own tab, the geometry
|
||||
// retry) is not a switch: _cleanupPreviousSession keeps a Send on Enter
|
||||
// draft for it, which it cannot tell on its own once activeSessionId is null.
|
||||
let reloadingSameSession = false;
|
||||
if (this.activeSessionId === sessionId && forceReload) {
|
||||
reloadingSameSession = true;
|
||||
this.terminalBufferCache?.delete(sessionId);
|
||||
this._xtermSnapshots?.delete(sessionId);
|
||||
try { localStorage.removeItem(`codeman-xs-${sessionId}`); } catch {}
|
||||
@@ -10067,9 +10045,10 @@ class CodemanApp {
|
||||
// A session tab takes the stage back from any active web tab.
|
||||
this._hideWebviewLayer?.();
|
||||
|
||||
this._cleanupPreviousSession(sessionId);
|
||||
this._cleanupPreviousSession(sessionId, { keepCjkDraft: reloadingSameSession });
|
||||
this.activeSessionId = sessionId;
|
||||
this._activateFileBrowserSession?.(sessionId);
|
||||
if (typeof CjkInput !== 'undefined') CjkInput.restoreDraft?.(sessionId);
|
||||
// A keyboard row hold belongs to the session it was taken for: release it here
|
||||
// if this one resizes instead (the geometry work below then fits it).
|
||||
this._reconcileKeyboardHold?.({ resize: false });
|
||||
@@ -10866,6 +10845,7 @@ class CodemanApp {
|
||||
this._flushedOffsets?.delete(sessionId);
|
||||
this._flushedTexts?.delete(sessionId);
|
||||
if (typeof KeyboardAccessoryBar !== 'undefined') KeyboardAccessoryBar.discardComposerDraft?.(sessionId);
|
||||
if (typeof CjkInput !== 'undefined') CjkInput.discardDraft?.(sessionId);
|
||||
// Drop any durably-queued input for a session that's actually gone (deleted/
|
||||
// exited). Not a lost prompt — the target no longer exists. Only reached on
|
||||
// real session removal, never on a tab switch.
|
||||
@@ -11147,6 +11127,9 @@ class CodemanApp {
|
||||
this._retireUrlSession();
|
||||
// Home is a choice to leave the grid too; it is remembered for Tiles.
|
||||
this.closeTileGrid?.({ keepStored: true, reselect: false });
|
||||
// A Send on Enter draft goes with its session: the null below hides that
|
||||
// session from the next _cleanupPreviousSession, which would clear it unstashed.
|
||||
if (typeof CjkInput !== 'undefined' && this.activeSessionId) CjkInput.stashDraft?.(this.activeSessionId);
|
||||
// Deselect active session and show welcome screen
|
||||
this.activeSessionId = null;
|
||||
try { localStorage.removeItem('codeman-active-session'); } catch {}
|
||||
@@ -11156,28 +11139,6 @@ class CodemanApp {
|
||||
this.renderRalphStatePanel();
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Ralph Loop Wizard (methods in ralph-wizard.js)
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
// Wizard state (initialized here, methods loaded from ralph-wizard.js)
|
||||
ralphWizardStep = 1;
|
||||
ralphWizardConfig = {
|
||||
taskDescription: '',
|
||||
completionPhrase: 'COMPLETE',
|
||||
maxIterations: 10,
|
||||
caseName: 'testcase',
|
||||
enableRespawn: false,
|
||||
generatedPlan: null,
|
||||
planGenerated: false,
|
||||
skipPlanGeneration: false,
|
||||
planDetailLevel: 'detailed',
|
||||
existingPlan: null,
|
||||
useExistingPlan: false,
|
||||
};
|
||||
planLoadingTimer = null;
|
||||
planLoadingStartTime = null;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Kill Sessions
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
* @dependency None (first in load order)
|
||||
* @loadorder 1 of 15 — constants.js → mobile-handlers.js → voice-input.js → notification-manager.js
|
||||
* → keyboard-accessory.js → input-cjk.js → app.js → terminal-ui.js → respawn-ui.js
|
||||
* → ralph-panel.js → settings-ui.js → panels-ui.js → session-ui.js → ralph-wizard.js
|
||||
* → ralph-panel.js → settings-ui.js → panels-ui.js → session-ui.js
|
||||
* → api-client.js → subagent-windows.js
|
||||
*/
|
||||
|
||||
@@ -113,7 +113,6 @@ const AUTO_CLOSE_NOTIFICATION_MS = 8000; // Auto-close browser notifications
|
||||
const DEFAULT_TOAST_DURATION_MS = 3000; // How long a corner toast stays by default
|
||||
const MIN_NOTIFICATION_DURATION_MS = 1000; // Shortest configurable toast / browser-notification time
|
||||
const MAX_NOTIFICATION_DURATION_MS = 300000; // Longest configurable toast / browser-notification time
|
||||
const THROTTLE_DELAY_MS = 100; // General UI throttle delay
|
||||
const TERMINAL_CHUNK_SIZE = 32 * 1024; // 32KB chunks for terminal buffer loading
|
||||
const TERMINAL_TAIL_SIZE = 1024 * 1024; // 1MB tail for initial load (more scrollback on tab switch)
|
||||
// A shell's automatic loads (tab select, drop recovery, a tile's load) read
|
||||
@@ -132,21 +131,15 @@ const SHELL_LOAD_HISTORY_LINES = 10000;
|
||||
const SHELL_LOAD_BASE_QUERY = `full=1&tail=${TERMINAL_TAIL_SIZE}&alt=recording`;
|
||||
const SHELL_LOAD_QUERY = `${SHELL_LOAD_BASE_QUERY}&lines=${SHELL_LOAD_HISTORY_LINES}`;
|
||||
const SYNC_WAIT_TIMEOUT_MS = 50; // Wait timeout for terminal sync
|
||||
const STATS_POLLING_INTERVAL_MS = 2000; // System stats polling
|
||||
const TUI_REDRAW_SETTLE_MS = 400; // Grace for a TUI to redraw after a real resize, before fetching its buffer
|
||||
|
||||
// Z-index base values for layered floating windows
|
||||
const ZINDEX_SUBAGENT_BASE = 1000;
|
||||
const ZINDEX_PLAN_SUBAGENT_BASE = 1100;
|
||||
const ZINDEX_LOG_VIEWER_BASE = 2000;
|
||||
const ZINDEX_IMAGE_POPUP_BASE = 3000;
|
||||
|
||||
// Subagent/floating window layout
|
||||
const WINDOW_INITIAL_TOP_PX = 120;
|
||||
const WINDOW_CASCADE_OFFSET_PX = 30;
|
||||
const WINDOW_MIN_WIDTH_PX = 200;
|
||||
const WINDOW_MIN_HEIGHT_PX = 200;
|
||||
const WINDOW_DEFAULT_WIDTH_PX = 300;
|
||||
|
||||
// WebGL renderer auto-fallback thresholds.
|
||||
// _installWebGLLongTaskGuard() observes longtask entries and disables WebGL
|
||||
@@ -1970,7 +1963,7 @@ function getEventCoords(e) {
|
||||
return { clientX: e.clientX, clientY: e.clientY };
|
||||
}
|
||||
|
||||
// HTML escape utility (shared by NotificationManager, CodemanApp, and ralph-wizard.js)
|
||||
// HTML escape utility (shared by NotificationManager and the CodemanApp mixins)
|
||||
const _htmlEscapeMap = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
||||
const _htmlEscapePattern = /[&<>"']/g;
|
||||
function escapeHtml(text) {
|
||||
|
||||
@@ -58,7 +58,7 @@
|
||||
* @dependency app.js (tab render pipeline), subagent-windows.js (window + line hooks),
|
||||
* tile-grid.js (tile mount, reveal and still-copy hooks)
|
||||
* @dependency constants.js (escapeHtml)
|
||||
* @loadorder 12.6 of 16, after webview-tabs.js, before ralph-wizard.js
|
||||
* @loadorder 12.6 of 16, after webview-tabs.js, before api-client.js
|
||||
*/
|
||||
|
||||
/** Tab entrance styles. `key` doubles as the `data-tab-anim` value. */
|
||||
|
||||
@@ -743,6 +743,11 @@
|
||||
"For local Claude sessions, opening the on-screen keyboard keeps the session's size and scrolls the view instead, so Claude does not reprint its screen and lose transcript lines. Full-screen interfaces (Codex, Claude's fullscreen mode) are resized as before.":
|
||||
'对于本地 Claude 会话,打开屏幕键盘时会保持会话尺寸并改为滚动视图,这样 Claude 不会重绘屏幕而丢失对话记录行。全屏界面(Codex、Claude 的全屏模式)仍像以前一样调整尺寸。',
|
||||
'CJK Input': '中日韩输入',
|
||||
'Input Field: Send on Enter': '输入框:按 Enter 发送',
|
||||
'CJK input (Enter = send, Esc = clear)': '中日韩输入(Enter 发送,Esc 清除)',
|
||||
'Type, Enter to send (Shift+Enter: new line, Esc: clear)': '输入文字,按 Enter 发送(Shift+Enter 换行,Esc 清除)',
|
||||
'With CJK Input on, keep typed text in the field until Enter instead of sending it as you type, so you can scroll the terminal and edit before sending. Autocorrect is on in this mode.':
|
||||
'开启中日韩输入后,输入的文字会保留在输入框中,直到按下 Enter 才发送,而不是边输入边发送,这样可以先滚动终端、编辑后再发送。此模式下会开启自动更正。',
|
||||
'Extended Keyboard Bar': '扩展键盘栏',
|
||||
'Gesture Control (beta)': '手势控制(测试版)',
|
||||
'Wheel Scrolls Local History': '滚轮滚动本地历史',
|
||||
|
||||
+9
-195
@@ -13,7 +13,8 @@
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
||||
<link rel="apple-touch-icon" href="icon-192.png">
|
||||
<link rel="manifest" href="manifest.json">
|
||||
<!-- use-credentials: the manifest fetch otherwise omits the session cookie, so a password-protected install answers 401 and the browser refuses to install the app. -->
|
||||
<link rel="manifest" href="manifest.json" crossorigin="use-credentials">
|
||||
<title>Codeman</title>
|
||||
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Cdefs%3E%3ClinearGradient id='g' x1='0%25' y1='0%25' x2='100%25' y2='100%25'%3E%3Cstop offset='0%25' stop-color='%2360a5fa'/%3E%3Cstop offset='100%25' stop-color='%233b82f6'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect width='32' height='32' rx='6' fill='%230a0a0a'/%3E%3Cpath d='M18 4L8 18h6l-2 10 10-14h-6z' fill='url(%23g)'/%3E%3C/svg%3E">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
@@ -1280,16 +1281,6 @@
|
||||
<div class="monitor-empty">No mux sessions</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="monitor-section" id="monitorPlanAgentsSection" style="display: none;">
|
||||
<div class="monitor-section-header">
|
||||
<span>Plan Wizard Agents</span>
|
||||
<span class="task-stats" id="monitorPlanAgentStats">0 active</span>
|
||||
<button class="btn-toolbar btn-sm btn-danger" onclick="app.cancelPlanFromMonitor()" title="Cancel plan generation">Cancel</button>
|
||||
</div>
|
||||
<div class="monitor-section-body" id="monitorPlanAgentsBody">
|
||||
<div class="monitor-empty">No plan agents</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="monitor-section" id="monitorSubagentsSection">
|
||||
<div class="monitor-section-header">
|
||||
<span>Background Agents</span>
|
||||
@@ -2074,6 +2065,13 @@
|
||||
</div>
|
||||
<label class="switch switch-sm"><input type="checkbox" id="appSettingsCjkInput"><span class="slider"></span></label>
|
||||
</div>
|
||||
<div class="set-row" data-search="cjk input send on enter hold draft pinned prompt field phone">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">Input Field: Send on Enter</span>
|
||||
<span class="set-row-desc">With CJK Input on, keep typed text in the field until Enter instead of sending it as you type, so you can scroll the terminal and edit before sending. Autocorrect is on in this mode.</span>
|
||||
</div>
|
||||
<label class="switch switch-sm"><input type="checkbox" id="appSettingsCjkHoldUntilEnter"><span class="slider"></span></label>
|
||||
</div>
|
||||
<div class="set-row" data-search="extended keyboard bar tab esc arrows phone">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">Extended Keyboard Bar <span class="set-tag">phone</span></span>
|
||||
@@ -4217,189 +4215,6 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Ralph Loop Wizard Modal -->
|
||||
<div class="modal" id="ralphWizardModal">
|
||||
<div class="modal-backdrop"></div>
|
||||
<div class="modal-content modal-wizard">
|
||||
<div class="modal-header">
|
||||
<h3>Start Ralph Loop</h3>
|
||||
<div class="modal-header-actions">
|
||||
<button class="modal-close" onclick="app.closeRalphWizard()" aria-label="Close Ralph wizard">×</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Wizard Progress Steps -->
|
||||
<div class="wizard-progress">
|
||||
<div class="wizard-step active" data-step="1">
|
||||
<span class="wizard-step-number">1</span>
|
||||
<span class="wizard-step-label">Describe</span>
|
||||
</div>
|
||||
<div class="wizard-step" data-step="2">
|
||||
<span class="wizard-step-number">2</span>
|
||||
<span class="wizard-step-label">Plan</span>
|
||||
</div>
|
||||
<div class="wizard-step" data-step="3">
|
||||
<span class="wizard-step-number">3</span>
|
||||
<span class="wizard-step-label">Launch</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-body">
|
||||
<!-- Step 1: Task & Completion Setup -->
|
||||
<div class="wizard-page wizard-page-compact" id="ralphWizardStep1">
|
||||
<div class="wizard-step-intro">
|
||||
<p>Describe your task below. Claude will generate an implementation plan with testing steps.</p>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label>What do you want to build?</label>
|
||||
<div class="textarea-with-assist">
|
||||
<textarea
|
||||
id="ralphTaskDescription"
|
||||
rows="3"
|
||||
placeholder="Build a REST API for user authentication with JWT tokens, login/logout endpoints, and password reset flow."></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="wizard-inline-row">
|
||||
<div class="wizard-inline-field">
|
||||
<label>Working Directory <span id="existingPlanBadge" class="existing-plan-badge" style="display:none"></span></label>
|
||||
<div class="case-select-inline">
|
||||
<select id="ralphCaseSelect" class="form-select" onchange="app.onRalphCaseChange()"></select>
|
||||
<button class="btn-toolbar btn-sm" onclick="app.showCreateCaseModal()">+</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="wizard-inline-field wizard-inline-field-small">
|
||||
<label>Iterations</label>
|
||||
<div class="iteration-presets-compact">
|
||||
<button type="button" class="iteration-preset-btn active" data-iterations="10" onclick="app.selectIterationPreset(10)">10</button>
|
||||
<button type="button" class="iteration-preset-btn" data-iterations="25" onclick="app.selectIterationPreset(25)">25</button>
|
||||
<button type="button" class="iteration-preset-btn" data-iterations="50" onclick="app.selectIterationPreset(50)">50</button>
|
||||
<button type="button" class="iteration-preset-btn" data-iterations="0" onclick="app.selectIterationPreset(0)">∞</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Hidden completion phrase with default -->
|
||||
<input type="hidden" id="ralphCompletionPhrase" value="COMPLETE">
|
||||
</div>
|
||||
|
||||
<!-- Step 2: Plan Generation -->
|
||||
<div class="wizard-page wizard-page-compact hidden" id="ralphWizardStep2">
|
||||
<!-- Existing plan detected (shown when @fix_plan.md exists) -->
|
||||
<div id="existingPlanSection" class="plan-section hidden">
|
||||
<!-- Content populated by app.updateExistingPlanUI() -->
|
||||
</div>
|
||||
|
||||
<!-- Loading state (shown during generation) -->
|
||||
<div id="planGenerationLoading" class="plan-loading-state hidden">
|
||||
<div class="plan-loading-content">
|
||||
<div class="plan-spinner"></div>
|
||||
<div class="plan-loading-text">
|
||||
<span class="plan-loading-title" id="planLoadingTitle">Starting Opus 4.5...</span>
|
||||
<span class="plan-loading-time" id="planLoadingTime">0s</span>
|
||||
</div>
|
||||
</div>
|
||||
<p class="plan-loading-hint" id="planLoadingHint">Initializing deep reasoning model</p>
|
||||
<div class="plan-loading-actions">
|
||||
<button class="btn-toolbar btn-sm plan-cancel-btn" onclick="app.cancelPlanGeneration()">Stop</button>
|
||||
<button class="btn-toolbar btn-sm" onclick="app.regeneratePlan()">Regenerate</button>
|
||||
</div>
|
||||
<!-- Auto-start toggle visible during generation -->
|
||||
<div class="plan-autostart-toggle">
|
||||
<label class="plan-autostart-label">
|
||||
<input type="checkbox" id="ralphAutoStartStep2" onchange="app.ralphWizardConfig.autoStart = this.checked">
|
||||
<span class="plan-autostart-text">Auto-launch when plan completes</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Stopped/Error state -->
|
||||
<div id="planGenerationError" class="plan-section hidden">
|
||||
<div class="plan-stopped-indicator" id="planStoppedIndicator">
|
||||
<span class="plan-stopped-icon">■</span>
|
||||
<span class="plan-stopped-text">Stopped</span>
|
||||
</div>
|
||||
<p class="plan-error-msg" id="planErrorMsg"></p>
|
||||
<div class="plan-actions">
|
||||
<button class="btn-toolbar btn-primary" onclick="app.generatePlan()">Regenerate Plan</button>
|
||||
</div>
|
||||
<p class="plan-skip-hint">Use <strong>Back</strong> to edit your task, or <strong>Next</strong> to continue without a plan</p>
|
||||
</div>
|
||||
|
||||
<!-- Editor state -->
|
||||
<div id="planEditor" class="plan-section hidden">
|
||||
<div class="plan-editor-header">
|
||||
<span>Implementation Plan <span class="plan-stats" id="planStats"></span></span>
|
||||
<div class="plan-editor-actions">
|
||||
<div class="plan-option-group">
|
||||
<label>Detail:</label>
|
||||
<div class="plan-detail-btns">
|
||||
<button type="button" class="plan-detail-btn" data-detail="standard" onclick="app.setPlanDetail('standard')" title="Single-pass generation with Opus 4.5">Standard</button>
|
||||
<button type="button" class="plan-detail-btn active" data-detail="detailed" onclick="app.setPlanDetail('detailed')" title="Enhanced: parallel subagents + verification (slower but more thorough)">Enhanced</button>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn-toolbar btn-sm" onclick="app.regeneratePlan()">Regenerate</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="planItemsList" class="plan-items-list"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Step 3: Preview & Launch -->
|
||||
<div class="wizard-page hidden" id="ralphWizardStep3">
|
||||
<div class="ralph-preview-section">
|
||||
<label>Prompt Preview</label>
|
||||
<div class="ralph-prompt-preview" id="ralphPromptPreview"></div>
|
||||
</div>
|
||||
|
||||
<div class="ralph-config-summary">
|
||||
<div class="config-summary-row">
|
||||
<span class="config-label">Completion Phrase:</span>
|
||||
<code id="summaryPhrase">COMPLETE</code>
|
||||
</div>
|
||||
<div class="config-summary-row">
|
||||
<span class="config-label">Max Iterations:</span>
|
||||
<span id="summaryIterations">10</span>
|
||||
</div>
|
||||
<div class="config-summary-row">
|
||||
<span class="config-label">Case:</span>
|
||||
<span id="summaryCase">testcase</span>
|
||||
</div>
|
||||
<div class="config-summary-row" style="display: none;">
|
||||
<span class="config-label">Plan:</span>
|
||||
<span id="summaryPlan">-</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Advanced Options (Collapsible) -->
|
||||
<details class="advanced-options">
|
||||
<summary>Advanced Options</summary>
|
||||
<div class="advanced-options-content">
|
||||
<div class="form-row form-row-switch">
|
||||
<label>Enable Respawn</label>
|
||||
<label class="switch">
|
||||
<input type="checkbox" id="ralphEnableRespawn">
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
<span class="form-hint">Auto-restart sessions when context fills up (usually not needed)</span>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Wizard Footer -->
|
||||
<div class="wizard-footer">
|
||||
<button class="btn-toolbar" id="ralphBackBtn" onclick="app.ralphWizardBack()" style="display: none;">Back</button>
|
||||
<div class="wizard-footer-right">
|
||||
<button class="btn-toolbar" onclick="app.closeRalphWizard()">Cancel</button>
|
||||
<button class="btn-toolbar btn-primary" id="ralphNextBtn" onclick="app.ralphWizardNext()">Next</button>
|
||||
<button class="btn-toolbar btn-success" id="ralphStartBtn" onclick="app.startRalphLoop()" style="display: none;">Start Loop</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- Kill All Confirmation Modal -->
|
||||
<div class="modal" id="killAllModal">
|
||||
<div class="modal-backdrop" onclick="app.closeKillAllModal()"></div>
|
||||
@@ -4764,7 +4579,6 @@
|
||||
<script defer src="edit-history-ui.js"></script>
|
||||
<script defer src="local-model-ui.js"></script>
|
||||
<script defer src="entrance-animations.js"></script>
|
||||
<script defer src="ralph-wizard.js"></script>
|
||||
<script defer src="api-client.js"></script>
|
||||
<script defer src="subagent-windows.js"></script>
|
||||
<script defer src="ultracode-windows.js"></script>
|
||||
|
||||
+321
-13
@@ -7,6 +7,21 @@
|
||||
* While this textarea has focus, window.cjkActive = true blocks xterm's onData.
|
||||
* Arrow keys and function keys are forwarded to PTY directly.
|
||||
*
|
||||
* ## Send on Enter (setting cjkInputHoldUntilEnter)
|
||||
*
|
||||
* The live mode above streams typed text to the PTY after a short debounce.
|
||||
* With Send on Enter on, the field is a chat box instead: _flush() holds the
|
||||
* text, and only Enter sends it, through the sendPrompt callback
|
||||
* (terminal-ui.js _sendCjkPrompt: a single character is typed, anything longer
|
||||
* goes as the composer's bracketed paste, Enter is always its own later write,
|
||||
* and a lone digit at a pending dialog goes without it). Shift+Enter is a
|
||||
* newline, Esc clears, Backspace and the arrows reach the PTY only from an
|
||||
* empty field, and so do the Ctrl shortcuts. Autocorrect is on. A held draft
|
||||
* belongs to one session (_owner): clear() stashes it under that session and
|
||||
* restoreDraft() brings it back when the session is shown again, except a
|
||||
* clear({ discard: true }) (the keyboard bar's clear-line key), which throws
|
||||
* it away.
|
||||
*
|
||||
* ## Android IME challenge
|
||||
*
|
||||
* Android virtual keyboards (WeChat, Sogou, Gboard in Chinese mode) use
|
||||
@@ -57,6 +72,27 @@ const CjkInput = (() => {
|
||||
let _dictationActive = false;
|
||||
let _dictationDecayTimer = null;
|
||||
let _printableKeydownAt = null;
|
||||
// Send-on-Enter mode (setting cjkInputHoldUntilEnter): typed text stays in the
|
||||
// field until Enter, like a chat box, instead of streaming to the PTY as it is
|
||||
// typed. Lets a phone user scroll the terminal and edit an answer before sending.
|
||||
let _hold = false;
|
||||
// Send-on-Enter: the held text as of the last settled input event (phantom
|
||||
// stripped). Tells a deletion that emptied the field from a Backspace on a field
|
||||
// that was already empty, and finds the one character an armed Ctrl applies to.
|
||||
let _heldBase = '';
|
||||
// Send-on-Enter: delivers a held answer, text first and Enter as a separate
|
||||
// delayed write, to the session it was typed for (terminal-ui.js).
|
||||
let _sendPrompt = null;
|
||||
// Send-on-Enter: whether setHoldUntilEnter() has applied the current mode to
|
||||
// the field yet, so a repeat call with the same mode leaves the field alone.
|
||||
let _holdApplied = false;
|
||||
// Send-on-Enter: held drafts of the sessions switched away from, by session id.
|
||||
const _drafts = new Map();
|
||||
// Send-on-Enter: the session the field's text belongs to (the one last shown,
|
||||
// set by restoreDraft). clear() stashes a held draft under it, so every path
|
||||
// that drops the active session before the next cleanup (goHome, the tile
|
||||
// grid's _replaceTileGrid and _onTileAdoptedElsewhere) keeps the answer.
|
||||
let _owner = null;
|
||||
const _listeners = {};
|
||||
|
||||
const PHANTOM = '';
|
||||
@@ -160,6 +196,7 @@ const CjkInput = (() => {
|
||||
}
|
||||
|
||||
function _resetToPhantom() {
|
||||
_heldBase = '';
|
||||
// Skip redundant writes: every programmatic value/selection mutation can
|
||||
// desync an Android IME's input session (InputConnection) — after which
|
||||
// the keyboard composes in its own UI but NO events ever reach the page.
|
||||
@@ -189,6 +226,13 @@ const CjkInput = (() => {
|
||||
_t('flush SKIP composing');
|
||||
return;
|
||||
}
|
||||
// Send-on-Enter: nothing leaves the field until Enter (keydown handler).
|
||||
if (_hold) {
|
||||
_t('flush SKIP hold');
|
||||
_holdSettle();
|
||||
_autoGrow();
|
||||
return;
|
||||
}
|
||||
const val = _strip(_textarea.value);
|
||||
_t(`flush ${val ? 'send len=' + val.length : 'empty'}`);
|
||||
if (val) {
|
||||
@@ -197,6 +241,133 @@ const CjkInput = (() => {
|
||||
_resetToPhantom();
|
||||
}
|
||||
|
||||
/** Send-on-Enter: grow the field with its content (up to the CSS max-height)
|
||||
* and let the keyboard layout re-read its height. */
|
||||
function _autoGrow() {
|
||||
if (!_textarea) return;
|
||||
// A hidden field (no session shown yet) measures 0: leave the CSS height,
|
||||
// or it stays a sliver until the next keystroke.
|
||||
if (_textarea.getClientRects && !_textarea.getClientRects().length) {
|
||||
_textarea.style.height = '';
|
||||
return;
|
||||
}
|
||||
// Only a touch device grows the field: there it is position: fixed above the
|
||||
// keyboard. On a desktop it sits in the flex column under the terminal, so
|
||||
// every line it gained would shrink the terminal box, refit and resize the
|
||||
// session's PTY (a CLI repaint each time). It stays one line there and
|
||||
// scrolls inside instead.
|
||||
if (!document.body?.classList?.contains('touch-device')) {
|
||||
_textarea.style.height = '';
|
||||
return;
|
||||
}
|
||||
const before = _textarea.style.height;
|
||||
_textarea.style.height = 'auto';
|
||||
// border-box: scrollHeight leaves the borders out, offsetHeight - clientHeight adds them back.
|
||||
_textarea.style.height = `${_textarea.scrollHeight + _textarea.offsetHeight - _textarea.clientHeight}px`;
|
||||
if (_textarea.style.height !== before && typeof KeyboardHandler !== 'undefined') {
|
||||
KeyboardHandler.updateLayoutForKeyboard?.();
|
||||
}
|
||||
}
|
||||
|
||||
/** Send-on-Enter: deliver the held text, then Enter, through `_sendPrompt`
|
||||
* (terminal-ui.js _sendCjkPrompt). Enter is never part of the text's write:
|
||||
* Codex takes characters arriving in one burst as a paste and folds an Enter
|
||||
* inside it into the paste, and Claude Code does the same for a long burst, so
|
||||
* even `1\r` in one write sits unsent. Returns false when the text was refused
|
||||
* (too long, no session), so the field keeps it. */
|
||||
function _sendHeld(val) {
|
||||
if (!_sendPrompt) {
|
||||
_t('hold send DROP no-prompt-path');
|
||||
return false;
|
||||
}
|
||||
return _sendPrompt(val) !== false;
|
||||
}
|
||||
|
||||
/** Enter: send what the field holds (or a bare Enter when it is empty) and
|
||||
* reset it. Returns false when a held answer was refused, which keeps it. */
|
||||
function _submit() {
|
||||
_composing = false;
|
||||
_cancelDebouncedFlush();
|
||||
clearTimeout(_compositionFlushTimer);
|
||||
_compositionFlushTimer = null;
|
||||
let val = _strip(_textarea.value);
|
||||
// Only blank lines held (Shift+Enter, then Enter): a bare Enter, not a
|
||||
// newline typed into the CLI.
|
||||
if (_hold && !val.trim()) val = '';
|
||||
if (_hold && val) {
|
||||
// Refused (too long, no session): keep the text so nothing is lost.
|
||||
if (!_sendHeld(val)) return false;
|
||||
} else if (val) {
|
||||
_send(val + '\r');
|
||||
} else {
|
||||
_send('\r');
|
||||
}
|
||||
_resetToPhantom();
|
||||
if (_hold) _autoGrow();
|
||||
return true;
|
||||
}
|
||||
|
||||
function _ctrlArmed() {
|
||||
return typeof KeyboardAccessoryBar !== 'undefined' && KeyboardAccessoryBar.isCtrlArmed?.() === true;
|
||||
}
|
||||
|
||||
/** Index of the one character `after` adds to `before`, or -1 when the change
|
||||
* is anything else (several characters, a deletion, a rewrite). */
|
||||
function _singleInsertionAt(before, after) {
|
||||
if (after.length !== before.length + 1) return -1;
|
||||
let i = 0;
|
||||
while (i < before.length && before[i] === after[i]) i++;
|
||||
return after.slice(i + 1) === before.slice(i) ? i : -1;
|
||||
}
|
||||
|
||||
/** Send-on-Enter: settle the field after an input event. With the shell bar's
|
||||
* one-shot Ctrl armed, a single typed character is not held: it leaves the
|
||||
* field and goes to the PTY, where _handleCjkInput turns it into the control
|
||||
* byte (`c` → Ctrl+C). Any other change spends the modifier, the same rule
|
||||
* live mode follows for a multi-character chunk. */
|
||||
function _holdSettle() {
|
||||
const before = _heldBase;
|
||||
const now = _strip(_textarea.value);
|
||||
_heldBase = now;
|
||||
if (now === before || !_ctrlArmed()) return;
|
||||
const at = _singleInsertionAt(before, now);
|
||||
if (at < 0 || now[at] === '\n') {
|
||||
KeyboardAccessoryBar.clearCtrl?.();
|
||||
return;
|
||||
}
|
||||
_t('hold ctrl key');
|
||||
_textarea.value = PHANTOM + before;
|
||||
_textarea.setSelectionRange(1 + at, 1 + at);
|
||||
_heldBase = before;
|
||||
_send(now[at]);
|
||||
}
|
||||
|
||||
/** Send-on-Enter input handling: nothing is flushed, the field only settles.
|
||||
* A deletion forwards Backspace to the PTY only when the field was ALREADY
|
||||
* empty, i.e. the phantom itself was deleted. Deleting the last held
|
||||
* character (or select-all + delete) must not also delete a character from
|
||||
* the CLI's own composer, which Attach, image paste, Path and the mic fill. */
|
||||
function _holdInput(e) {
|
||||
if (_composing) return; // composed text settles at compositionend (_flush)
|
||||
if (e.inputType === 'deleteContentBackward' || e.inputType === 'deleteWordBackward') {
|
||||
const wasEmpty = !_heldBase;
|
||||
_heldBase = _strip(_textarea.value);
|
||||
if (!_heldBase) {
|
||||
if (wasEmpty) _send('\x7f');
|
||||
_resetToPhantom();
|
||||
} else if (!_textarea.value.startsWith(PHANTOM)) {
|
||||
// Backspace at the very start of the text deleted the phantom: put it
|
||||
// back with the caret where it was, at the start of the text.
|
||||
_textarea.value = PHANTOM + _textarea.value;
|
||||
_textarea.setSelectionRange(1, 1);
|
||||
}
|
||||
_autoGrow();
|
||||
return;
|
||||
}
|
||||
_holdSettle();
|
||||
_autoGrow();
|
||||
}
|
||||
|
||||
/** Cancel any pending debounced flush */
|
||||
function _cancelDebouncedFlush() {
|
||||
if (_flushTimer) {
|
||||
@@ -226,14 +397,16 @@ const CjkInput = (() => {
|
||||
}
|
||||
|
||||
return {
|
||||
init({ send }) {
|
||||
init({ send, sendPrompt = null }) {
|
||||
if (_initialized) this.destroy();
|
||||
|
||||
_send = send;
|
||||
_sendPrompt = sendPrompt;
|
||||
_composing = false;
|
||||
_printableKeydownAt = null;
|
||||
_flushTimer = null;
|
||||
_textarea = document.getElementById('cjkInput');
|
||||
_holdApplied = false; // a new field has not had the mode applied
|
||||
if (!_textarea) return this;
|
||||
|
||||
_resetToPhantom();
|
||||
@@ -316,16 +489,14 @@ const CjkInput = (() => {
|
||||
_t(`keydown ${_kdesc(e.key)} kc=${e.keyCode} ic=${e.isComposing} c=${_composing}`);
|
||||
_printableKeydownAt = null;
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
_composing = false;
|
||||
_cancelDebouncedFlush();
|
||||
const val = _strip(_textarea.value);
|
||||
if (val) {
|
||||
_send(val + '\r');
|
||||
} else {
|
||||
_send('\r');
|
||||
// Send-on-Enter: Shift+Enter (or an IME still composing) is a newline
|
||||
// in the field, never a send.
|
||||
if (_hold && (e.shiftKey || e.isComposing || e.keyCode === 229)) {
|
||||
setTimeout(_autoGrow, 0);
|
||||
return;
|
||||
}
|
||||
_resetToPhantom();
|
||||
e.preventDefault();
|
||||
_submit();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -334,10 +505,15 @@ const CjkInput = (() => {
|
||||
_composing = false;
|
||||
_cancelDebouncedFlush();
|
||||
_resetToPhantom();
|
||||
if (_hold) _autoGrow();
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.ctrlKey && CTRL_KEYS[e.key]) {
|
||||
// Send-on-Enter with a draft in the field: Ctrl shortcuts are the
|
||||
// field's (Ctrl+Z undo, Ctrl+A select all, Ctrl+C copy a selection), so
|
||||
// they reach the CLI only while the field is empty, the rule Backspace
|
||||
// and the arrows already follow.
|
||||
if (e.ctrlKey && CTRL_KEYS[e.key] && (!_hold || _isEffectivelyEmpty())) {
|
||||
e.preventDefault();
|
||||
_send(CTRL_KEYS[e.key]);
|
||||
return;
|
||||
@@ -405,6 +581,11 @@ const CjkInput = (() => {
|
||||
_composing = false;
|
||||
}
|
||||
|
||||
if (_hold) {
|
||||
_holdInput(e);
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Backspace / delete detection ──
|
||||
if (e.inputType === 'deleteContentBackward' || e.inputType === 'deleteWordBackward') {
|
||||
if (_composing) return;
|
||||
@@ -464,9 +645,24 @@ const CjkInput = (() => {
|
||||
* can't flush into the wrong session). Restores the phantom so backspace
|
||||
* forwarding keeps working — unlike a raw `textarea.value = ''`.
|
||||
*/
|
||||
clear() {
|
||||
clear({ discard = false } = {}) {
|
||||
if (!_initialized || !_textarea) return;
|
||||
_t('clear (external)');
|
||||
_t(`clear (external)${discard ? ' discard' : ''}`);
|
||||
if (discard) {
|
||||
// The user threw the text away (the keyboard bar's clear-line key):
|
||||
// nothing is stashed, any older stash of this session goes too, and the
|
||||
// field keeps its owner, since the session shown has not changed.
|
||||
if (_owner) _drafts.delete(_owner);
|
||||
} else {
|
||||
// Send-on-Enter: a held draft is stashed for the session it was typed
|
||||
// for, whichever path got here. discardDraft() drops the owner of a
|
||||
// removed session, so its text is not stashed again.
|
||||
if (_hold && _owner) {
|
||||
const draft = _strip(_textarea.value);
|
||||
if (draft.trim()) _drafts.set(_owner, draft);
|
||||
}
|
||||
_owner = null;
|
||||
}
|
||||
_cancelDebouncedFlush();
|
||||
clearTimeout(_compositionFlushTimer);
|
||||
_compositionFlushTimer = null;
|
||||
@@ -475,6 +671,118 @@ const CjkInput = (() => {
|
||||
_resetToPhantom();
|
||||
},
|
||||
|
||||
/**
|
||||
* Send-on-Enter mode on or off (setting cjkInputHoldUntilEnter). On: text
|
||||
* stays in the field until Enter and the browser's autocorrect is allowed,
|
||||
* since nothing typed has reached the PTY yet. Off: the original live mode.
|
||||
*/
|
||||
setHoldUntilEnter(on) {
|
||||
// The placeholder first, before the early return: App Settings applies a
|
||||
// language switch live and then calls this with the mode unchanged. It is
|
||||
// written only when the text differs, so a field mid-composition is not
|
||||
// touched. i18n.js skips <textarea> subtrees (what is typed there is user
|
||||
// content), so it is translated here, like the prompt composer's.
|
||||
if (_textarea) {
|
||||
const source = !!on
|
||||
? 'Type, Enter to send (Shift+Enter: new line, Esc: clear)'
|
||||
: 'CJK input (Enter = send, Esc = clear)';
|
||||
const i18n = typeof window !== 'undefined' ? window.CodemanI18n : undefined;
|
||||
const placeholder = typeof i18n?.t === 'function' ? i18n.t(source) : source;
|
||||
if (_textarea.placeholder !== placeholder) _textarea.placeholder = placeholder;
|
||||
}
|
||||
// Called on every session select and SSE reconnect: with the mode
|
||||
// unchanged, leave the rest of the field alone, since rewriting its
|
||||
// attributes while it has focus can disturb a composition in progress.
|
||||
if (_holdApplied && _textarea && _hold === !!on) return;
|
||||
const wasHolding = _hold;
|
||||
_hold = !!on;
|
||||
if (!_textarea) return;
|
||||
_holdApplied = true;
|
||||
// Turning the mode off: live mode's next flush would send everything in
|
||||
// the field, a held multi-line draft included (its newline runs the first
|
||||
// line in a shell), and stashed drafts would come back if the mode is
|
||||
// switched on again. Drop them all.
|
||||
if (wasHolding && !_hold) {
|
||||
_drafts.clear();
|
||||
_resetToPhantom();
|
||||
}
|
||||
_heldBase = _strip(_textarea.value);
|
||||
const v = _hold ? 'on' : 'off';
|
||||
_textarea.setAttribute('autocorrect', v);
|
||||
_textarea.setAttribute('autocapitalize', _hold ? 'sentences' : 'off');
|
||||
_textarea.setAttribute('spellcheck', _hold ? 'true' : 'false');
|
||||
if (_hold) {
|
||||
_cancelDebouncedFlush();
|
||||
_autoGrow();
|
||||
} else {
|
||||
_textarea.style.height = '';
|
||||
}
|
||||
_t(`hold ${v}`);
|
||||
},
|
||||
|
||||
get holdUntilEnter() { return _hold; },
|
||||
|
||||
/**
|
||||
* Enter from outside the field (the phone toolbar's Enter button, which
|
||||
* xterm's onData would swallow while the field is visible). Same as Enter
|
||||
* in the field. Returns false when nothing was done (not initialized) or a
|
||||
* held answer was refused.
|
||||
*/
|
||||
submit() {
|
||||
if (!_initialized || !_textarea) return false;
|
||||
_t(`submit (external) c=${_composing}`);
|
||||
if (_composing) {
|
||||
// An IME still composing (Gboard holds the current word, iOS the
|
||||
// unconverted pinyin): reading and resetting the field under it can
|
||||
// desync the keyboard. Blur commits the composition, focus keeps the
|
||||
// keyboard up (still inside the tap's gesture), then send what landed.
|
||||
_textarea.blur();
|
||||
_textarea.focus();
|
||||
}
|
||||
return _submit();
|
||||
},
|
||||
|
||||
/**
|
||||
* Send-on-Enter: keep the held draft of the session being left, so a
|
||||
* switch (a stray sideways swipe) does not lose an answer. Call before
|
||||
* clear(); restoreDraft() puts it back when that session is shown again.
|
||||
*/
|
||||
stashDraft(sessionId) {
|
||||
if (!_initialized || !_textarea || !_hold || !sessionId) return;
|
||||
// An empty field leaves any stash alone: a draft only sits in the map
|
||||
// while its session is not shown (restoreDraft takes it out), and the
|
||||
// tile grid may stash an id whose draft is already put away.
|
||||
const draft = _strip(_textarea.value);
|
||||
if (draft.trim()) _drafts.set(sessionId, draft);
|
||||
},
|
||||
|
||||
/** Send-on-Enter: show the draft stashed for this session, if any, unless
|
||||
* the field already holds text. */
|
||||
restoreDraft(sessionId) {
|
||||
if (!_initialized || !_textarea) return;
|
||||
// The field now belongs to this session, draft or not (see _owner),
|
||||
// unless it still holds another session's text (no clear() in between).
|
||||
if (!_owner || !_strip(_textarea.value)) _owner = sessionId || null;
|
||||
if (!_hold || !_drafts.has(sessionId)) return;
|
||||
if (_strip(_textarea.value)) return;
|
||||
const draft = _drafts.get(sessionId);
|
||||
_drafts.delete(sessionId);
|
||||
_t(`restore draft len=${draft.length}`);
|
||||
_textarea.value = PHANTOM + draft;
|
||||
_textarea.setSelectionRange(_textarea.value.length, _textarea.value.length);
|
||||
_heldBase = draft;
|
||||
_autoGrow();
|
||||
},
|
||||
|
||||
/** Forget a stashed draft when its session no longer exists. */
|
||||
discardDraft(sessionId) {
|
||||
_drafts.delete(sessionId);
|
||||
if (_owner === sessionId) _owner = null;
|
||||
},
|
||||
|
||||
/** Diagnostic/test: the session the field's text belongs to. */
|
||||
get draftOwner() { return _owner; },
|
||||
|
||||
/** Diagnostic: recent IME event trace (ring buffer). */
|
||||
getTrace() {
|
||||
return _trace.slice();
|
||||
|
||||
Loaded 100 of 179 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user