diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 6c01537f..7f8db01d 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -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" diff --git a/CHANGELOG.md b/CHANGELOG.md index 118e157a..f94da79b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 ` (#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 ` 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 `` (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 diff --git a/CLAUDE.md b/CLAUDE.md index 58bf9315..76c71a9a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 ` to attach). +**Git**: Main branch is `master`. Terminal session dashboard: `codeman tui` (`--list` to list, `codeman tui ` or `codeman tui ` to attach). ## Additional Commands @@ -134,7 +134,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph **Agent CLI (`codeman agent …`, `src/cli-agent.ts`)**: the command-line client for the wait primitives and the session verbs, for agents the skill does not reach (pi, shell, no `jq`; `seedAgentSessionPreamble` covers every local session whose CLI takes the skill, `capabilities.agentSkillDir`; every pane still exports `CODEMAN_MUX`/`CODEMAN_SESSION_ID`/`CODEMAN_API_URL`). It is an HTTP CLIENT: inspection and guarded stage/submit use the ownership-checked `agent-session-routes.ts` module (experimental, behind `agentCoordinationEnabled`, SYNCED, default OFF: all three routes answer `403 FORBIDDEN` naming it while off, and the CLI shows that verbatim); the other verbs reuse existing routes, with no second transport (the plan's "Socket API" non-goal stands), every call carries `X-Codeman-Parent-Session`, only `spawn`'s quick-start carries `X-Codeman-Agent-Origin` (pinned in test/cli-agent.test.ts), while `spawn` without a case (cwd or `--working-dir`) is `POST /api/v1/sessions` plus `/interactive` or `/shell` without that header, so no agent-case marker, and refuses (exit 4, before any request) an empty `--working-dir` and a bare spawn from a HOME cwd, since it always sends an explicit `workingDir` and the server's no-`workingDir` hooks skip cannot apply (test/cli-agent-project-spawn.test.ts), auth (`src/codeman-credentials.ts`, shared with `codeman attach` and the TUI) from `CODEMAN_PASSWORD` or the data dir's `.env` (the same reader `codeman attach` uses — `readCodemanEnvFile`). Verbs return exit codes (`0` ok / `1` error / `2` timeout / `3` exited / `4` refused) instead of calling `process.exit`, so `test/cli-agent.test.ts` drives every verb against a recording fake transport plus the real `httpRequest` against a local server. ⚠️ Three guards live in code, not prose, and the tests pin them: refuse without `CODEMAN_MUX=1`+`CODEMAN_API_URL` (never guess a URL); `send` transmits printable text + `\r` only (`inputRefusal`: any byte < 0x20 or DEL refuses BEFORE the transport — opencode's `Ctrl+C` is `app_exit`), ESC exists solely as `interrupt` with no `\r`; `rm` fails closed (`deleteRefusal`: empty id, self shorter than 8, prefix match in EITHER direction, re-checked on the resolved id). ⚠️ The routes accept FULL ids only — an 8-char prefix is a 404 (measured live) — while `ls` prints prefixes, so `resolveSessionId` maps a short id through `GET /api/v1/sessions` and refuses an ambiguous one. It also refuses any id under 8 characters (exit 4, on every verb, before any request), the same floor as the server's `PARENT_SESSION_ID_MIN_PREFIX`, so `rm 9` can never pick an arbitrary session. ⚠️ A 400 for `--until stop` on a hook-less mode is passed through verbatim, never papered over: the marker path is the answer there. `spawn` on a readiness timeout exits 2 and LEAVES the session for inspection (the skill's `spawn_worker` deletes it; the CLI's caller is often a human); its stdout is the id ALONE (prose on stderr) so `SID=$(…)` works. ⚠️ Two server answers that look like success and are not: `delivered:false` without `duplicate` (the bytes went into a dead pane — the field exists so a client says "restart" instead of "wait longer") and `wait.ended:true, signal:null` (the worker died during a `stop`/`idle` wait: the registry satisfies only waiters that listed `exit`, then cancels the rest) — both exit 3, checked BEFORE the happy paths in `waitExitCode`. → README "`codeman agent`", `docs/api-reference.md` -**Discord bridge (`src/discord-bridge.ts`, `src/web/routes/discord-routes.ts`, `src/cli-notify.ts`)**: opt-in two-way Discord (a bot, not the one-way webhook), one thread per tab. Split like `webhook-notify.ts`: pure helpers, a 0600 store (`discord.json` holds the bot token, is never returned by these routes and is on the sensitive-path list; `discord-bridge.json` maps sessionId to thread id), then IO (`DiscordApi` REST with injected fetch, `DiscordGateway` inbound WebSocket with injected socket, `DiscordBridge` rules). Outbound hangs off `WebServer.sendPushNotifications` beside the webhook (so it works with zero push subscriptions) and tab events off `WebServer.broadcast` (`bridgeSessionEvent`); a finished turn (Claude's idle and stop hooks, DeepSeek's stop; the other CLIs raise no turn end, so theirs arrive with an error, a blocked respawn, a crash loop or `codeman notify`) or an error posts the CLI's WHOLE last message as markdown, read from its transcript through the response viewer's reader (`WebServer.lastResponseFor`, set by the session routes: the CLI's own transcript, or the pane segmented into turns for the CLIs that keep none; never for a shell), split over posts of at most 1900 characters and not posted twice (keyed on the text plus its turn, recorded only after the first post succeeds), while a dialog and every CLI without a transcript post the RENDERED tmux screen (`screenTail`, with the composer row and the status lines under it cut), never the raw stream, which a full-screen UI repaints in place; `staleThreads` (default `keep`) archives or deletes threads the bot owns that no tab maps to, after boot and then daily, never one under an hour old, never with an empty map and at most 25 per run. Inbound replies are typed through `session.writeViaMux`. ⚠️ Guards that live in code and tests pin: only `allowedUserIds`, in `guildId`, inside a thread the bridge created, are acted on, everything else is dropped unread; a reply is one printable line plus Enter (a lone digit while a permission or question is pending goes as the key alone, since the dialog acts on it), capped and rate limited, and `discord-notify` is a per-session token bucket (6 a minute, 429 `RATE_LIMITED`; `fileProblem` probes the folder with the bounded probe first); posts send `allowed_mentions` limited to the allowlisted ids; received files go only from Discord's own HTTPS hosts (max 5 x 8 MB, names reduced to `[A-Za-z0-9._-]`) into `/.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 "" [--urgent] [--file ]` 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 `/.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 "" [--urgent] [--file ]` 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,7 +158,9 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph **Workspace-trust dialog auto-accept** (`session-trust-dialog.ts`, pure): Claude Code's per-directory trust dialog is always answered yes, or the session is stuck. ⚠️ Match the compacted SCREEN (`compactScreenText()`, all whitespace removed), never the stream (tmux sends words joined by cursor-forwards, not spaces). ⚠️ Never answer with a blind `\r` (newer versions highlight "No, exit" first): `trustDialogNextKey()` returns ONE key per re-read frame (arrow, then Enter only once `❯` is on the trust option), and the LAST marked option wins. ⚠️ All three guards must hold: startup window `TRUST_DIALOG_WINDOW_MS` (90s), two-marker match (`isTrustDialogScreen`), attempt cap `TRUST_DIALOG_MAX_ATTEMPTS` (6). ⚠️ Read `capturePaneText()`; only a direct-PTY session falls back to a SHORT buffer tail. ⚠️ The scan must schedule its own next read (`_trustDialogTimer`, cleared in `_clearAllTimers()`), not rely on PTY output, and a throttled read is DEFERRED onto that timer, never dropped (the dialog's paint is often the pane's last output); a stopped session never scans. → [architecture-invariants#workspace-trust-dialog-auto-accept](docs/architecture-invariants.md#workspace-trust-dialog-auto-accept) -**Process-tree walks are bounded** (`proc-tree.ts`, pure): `collectDescendants(pid, byParent)` is the ONE descendant traversal, fed by one cached `ps -eo pid=,ppid=` snapshot (`refreshProcSnapshot()` in tmux-manager.ts: async, in-flight-shared, and ANY error discards the result rather than caching a truncated `ps`). ⚠️ Never walk a process tree with per-node `pgrep` or unbounded recursion (the unbounded version took a machine down): the walk must terminate on cycles, cap depth (`PROC_WALK_MAX_DEPTH`) and node count (`PROC_WALK_MAX_NODES`), and never spawn anything. ⚠️ Keep it in its own module so the test exercises the shipped code, and report truncation through `onTruncated` naming both caps, never silently. → [architecture-invariants#process-tree-walks-are-bounded](docs/architecture-invariants.md#process-tree-walks-are-bounded) +**Process-tree walks are bounded** (`proc-tree.ts`, pure): `collectDescendants(pid, byParent)` is the ONE descendant traversal, fed by one cached `ps -eo pid=,ppid=` snapshot (`refreshProcSnapshot()` in tmux-manager.ts: async, in-flight-shared, and ANY error discards the result rather than caching a truncated `ps`). ⚠️ Never walk a process tree with per-node `pgrep` or unbounded recursion (the unbounded version took a machine down): the walk must terminate on cycles, cap depth (`PROC_WALK_MAX_DEPTH`) and node count (`PROC_WALK_MAX_NODES`), and never spawn anything. ⚠️ Keep it in its own module so the test exercises the shipped code, and report truncation through `onTruncated` naming both caps, never silently. ⚠️ **A kill never takes pid 0 or 1** (`isSignalablePid()`): the children of pid 0 are the whole machine, and tmux really answers 0 for an empty pane (`split-window ''`), which the pane list at server start records as `session.pid`; a close then signalled every process of the account. `killSession` signals only through `signalProcess()`, walks nothing for such a pid and leaves the close to `tmux kill-session`. Never call `process.kill` in tmux-manager.ts with a signal anywhere else, and never drive a real `killSession` from a script: stub `process.kill` in vitest (`test/kill-pid-guard.test.ts`). → [architecture-invariants#process-tree-walks-are-bounded](docs/architecture-invariants.md#process-tree-walks-are-bounded) + +**A `persistent: false` chokidar watcher stops on its first error**: ⚠️ its `'error'` handler goes through `closeWatcherOnError()` (`utils/close-watcher-on-error.ts`), never a bare log or `close()`. chokidar 3 retries a failed `fs.watch` (EMFILE once the inotify instances are used up, ENOSPC once the watches are) on the parent directory up to `/` forever, logging every pass (one server wrote 174 GiB of log that way); a bare `close()` turns the follow-up TypeError into an unhandled rejection, and a callback already in flight can reopen it through `add()`. The watcher's own poll must cover what it watched and create it again on a later tick (`TeamWatcher`, `WorkflowRunWatcher`): chokidar 3 reports a one-off ENOENT race (a new file gone between its `stat` and `watch`) through the same TypeError, so a watcher that stayed closed would end live updates until a restart. Tests: `test/watcher-fs-watch-failure.test.ts`. **Auto-resume on usage limit** (opt-in per session, top of the Respawn tab): when Claude halts on a subscription limit, `usage-limit-patterns.ts` (pure, unit-tested) parses the reset time and `SessionAutoOps` arms a timer for reset+2min, then sends Esc + `continue`. ⚠️ Respawn cycles are blocked while paused (`isLimitPaused` guard in `onIdleDetected`), which is what prevents `/clear` from wiping the paused conversation. Claude-mode only. → [architecture-invariants#auto-resume-on-usage-limit](docs/architecture-invariants.md#auto-resume-on-usage-limit) @@ -188,7 +190,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph **External CLI modes (OpenCode, Codex, Gemini, Antigravity, Pi, Grok, DeepSeek, OMP, Copilot, jcode)**: `isExternalCliMode()` in `session.ts` gates Claude-specific behavior off (Ralph tracker, BashToolParser, token parsing, ❯ readiness; readiness is output stabilization); work detection is per-CLI `capabilities.workDetect` data, not this gate. All ten **require tmux, no direct PTY fallback** (secrets go via socket-scoped `tmux setenv`, never the command line). ⚠️ `run*()` in `session-ui.js` MUST unwrap the `{success,data}` envelope. ⚠️ **Codex uses predictive write-through echo, never the buffer overlay**: `_predictHookOnData` must never `return` (wire path stays byte-identical), and flushed text and a bracketed paste must go out as separate delayed writes. ⚠️ **Pi**: no bypass flag, never invent one; `approveProjectTrust` executes repo code, so it is in the clamp's **materialize** branch; never wire `--api-key`. ⚠️ **Grok**: `alwaysApprove` is stripped for non-granted owners (only-if-sent). ⚠️ **DeepSeek**: the agent is a PROFILE (Run gates on `isDeepSeekRunnable()`); the permission switch is the `DSH_PERMISSION_MODE` env var, so `clampEnvOverridesForOwner()` must DROP `DSH_PERMISSION_MODE`, `DSH_HOME` and `DEEPSEEK_BASE_URL` for non-granted owners; `hooksAvailableForMode()` is per-SESSION for it (pass `sessionHookOptions(session)`) and is never a stand-in for `mode === 'claude'`; answers come from `deepseek-transcript.ts`, paired by header `cwd` + boot window, never newest-mtime. ⚠️ **OMP**: `OMP_AUTH_BROKER_URL`/`_TOKEN` are clamped the same way. ⚠️ **Copilot**: `allowAll` (`--yolo`) is a `privilegedParam` and `COPILOT_HOME`/`COPILOT_ALLOW_ALL`/`COPILOT_PROVIDER_*`/`COPILOT_MODEL` are privileged env keys, and so is every other `COPILOT_*` variable the CLI reads that switches approvals, runs code with no approval row or sends its sign-in token elsewhere (the 1.0.98 list is in `stock.ts`; the prefix admits whatever a later release adds, so re-read the bundle whenever the measured version moves); the resume id must start with a letter or digit (`path-segment`), since `--resume`'s value is optional and `--resume --yolo` would otherwise make `--yolo` its own flag; `--name` is dropped next to `--resume`/`--continue` (Copilot refuses the pair); its mouse DECSETs are stripped (`strip-mux-and-mouse`) so a drag selects and the wheel is forwarded by `_shouldForwardWheelToApp` while `cliMouseTracking` is on; `composerReadyMark` is the footer hint `/ commands · ? help`, NOT `❯` (the folder-trust dialog draws `❯ 1. Yes`); `last-response` reads the pane's visible screen (`transcriptNeedsScreenCapture`) through a per-CLI `PANE_DIALECTS` row, because its stream is cursor moves, not lines (a prompt row scrolled off by a tall answer reads as the answer's tail unless a banner/trust dialog is on screen, and typed composer text is not a prompt); Docker seeds no Copilot credential (`config.json` holds a plain-text token without a keyring). ⚠️ **jcode**: every pane is a client of ONE shared per-user daemon and the tools run in the daemon with ITS env, so jcode gets no agent skill and no `JCODE_*` envOverrides prefix (a per-session value would act as another session or reach every one); `last-response` is an honest empty (external + `transcript: 'none'`, never the segmenter or the Claude scan); ⚠️ that daemon is a descendant of whichever pane started it, so `capabilities.sharedDaemon` makes `killSession` spare descendants outside the pane's process group (`descendantsInPaneGroup()`, `proc-tree.ts`), or closing that one tab cuts every other jcode session off; it resolves through the generic registry resolver, with no per-CLI resolver module (`docs/jcode-integration.md`). → [architecture-invariants#external-cli-modes-opencode-codex-gemini-antigravity-pi-grok-deepseek-omp](docs/architecture-invariants.md#external-cli-modes-opencode-codex-gemini-antigravity-pi-grok-deepseek-omp) -**DeepSeek web UI** (`POST`/`GET`/`DELETE /api/deepseek/web`, `deepseek-web-server.ts`): the Run menu's "DeepSeek web UI..." entry supervises ONE background `dsh web` child process, deliberately **NOT a shell session**. ⚠️ Every piece is load-bearing: exactly one server (a second click REUSES it), restarted when the browser authority changes (`--trusted-host`, last asker wins), killed on shutdown via `stopDeepSeekWeb()` (the detached child would otherwise outlive Codeman and hold its port), and failures returned to the caller. ⚠️ Never hardcode the port: search from 3080 across 40, detect free ports by BINDING, then wait for the server to really answer. ⚠️ Both `POST` and `DELETE` must stay behind `canUsernameRunPrivilegedCommands` (booting a profile runs its plugin code; the server is shared). → [architecture-invariants#deepseek-web-ui](docs/architecture-invariants.md#deepseek-web-ui) +**DeepSeek web UI** (`POST`/`GET`/`DELETE /api/deepseek/web`, `deepseek-web-server.ts`): the Run menu's "DeepSeek web UI..." entry supervises ONE background `dsh web` child process, deliberately **NOT a shell session**. ⚠️ Every piece is load-bearing: exactly one server (a second click REUSES it, but only for the same starter and while its cookie works), restarted when the browser authority changes (`--trusted-host`, last asker wins), killed on shutdown via `stopDeepSeekWeb()` (the detached child would otherwise outlive Codeman and hold its port), and failures returned to the caller. ⚠️ Never hardcode the port: search from 3080 across 40, detect free ports by BINDING, then wait for the server to really answer. ⚠️ Both `POST` and `DELETE` must stay behind `canUsernameRunPrivilegedCommands` (booting a profile runs its plugin code; the server is shared). ⚠️ The launch token is traded for dsh's session cookie once at startup, and the web-tab proxy presents it on both legs only to the `managed: 'deepseek-web'` tab on the `127.0.0.1` port it was minted for (in multi-user mode, only to a granted owner who started it). → [architecture-invariants#deepseek-web-ui](docs/architecture-invariants.md#deepseek-web-ui) **Case rename** (`POST /api/cases/:name/rename`, `src/case-rename.ts`; `docs/wiki/Core-Concepts.md#case`): a case under the cases dir is its folder name and always moves; a linked case renames its alias and moves its real folder only with `renameFolder`; remote and Docker cases are refused. ⚠️ A folder that sessions have open is the hazard: live sessions at or under it make the route answer `409 requiresStop` with their names, and only `stopSessions: true` ends them (via `ctx.cleanupSession`: closed like a tab close, uploads included, nothing is restarted); the free-target pre-check runs before that and refuses a dangling symlink too (`lstat`, as `moveCaseFolder` does), so no session is ended for a move that cannot happen. `withCaseLock` holds the old and new paths for the whole operation (`isCasePathLocked`; the `Session` constructor throws for a working directory inside a held path, so nothing is constructed mid-move). ⚠️ A create awaits the owner's layout lock and a settings read between `new Session` and the server's map, where the rename looks for open sessions, so the constructor also records the session (`noteCaseSessionStarting`) until `registerSessionWithLayout()` or `stop()` settles it (30 s TTL for one that never registers), and a folder move refuses `409` with `renameCode: "BUSY"` while one is recorded at or under the folder (`isCaseSessionStarting`, checked in the same tick that takes the lock); an alias-only rename is not refused. A create whose path was validated before the move but whose `Session` is constructed after it is not covered (the plain check-then-use race of any create path), `moveCaseFolder` refuses an existing target itself (POSIX `rename` would silently replace an EMPTY directory) and retries `EBUSY`/`EPERM`/`EACCES` before answering `423 LOCKED`. If the registries (`linked-cases.json`, `caseOrder`, `lastUsedCase`, `lastPickedCase`, `caseSettings`) fail after the move, `settings.json` and the folder are put back (a failed move-back says the folder is now at the new path), and an error after `stopSessions` carries `stoppedSessions`. Claude Code keys history by path (`claudeProjectDirName`: every non-alphanumeric becomes `-`), so `/projects/` 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`. @@ -228,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) @@ -334,7 +336,7 @@ One module per domain in `src/web/routes/` (plus a barrel; `ls src/web/routes/` ## State Files -All in `~/.codeman/`: `state.json` (sessions, settings, respawn, orchestrator, cron jobs/runs, owner tab layouts, case default groups), `mux-sessions.json` (tmux recovery), `settings.json` (user prefs), `push-keys.json` + `push-subscriptions.json`, `session-lifecycle.jsonl` (audit log), `update-status.json` (self-updater progress, polled across the service restart), `docker-env-applied.json` (Compose deployment only: sha256 of the Dockerfile + compose file the running container was built from, written by `Start-Codeman.sh`, read by the self-updater's environment gate), `docker-build-source.json` (Compose deployment only: the checkout's HEAD commit and `package-lock.json` hash the `codeman-node-modules`/`codeman-dist` volumes currently reflect, written by both `Start-Codeman.sh` and a successful in-place self-update, compared to detect and refresh a volume left stale by an externally-triggered rebuild), `linked-cases.json`, `webviews.json` (saved web-tab dashboard URLs), `remote-hosts.json` + `remote-cases.json`, `docker-hosts.json` + `docker-cases.json` + `docker-exports/`, `subagent-window-states.json` + `subagent-parents.json` (subagent window layout, GET/PUT `/api/subagent-window-states`/`-parents`), `hook-secret` (per-instance), `users.json` (multi-user, mode 0600) + `admin-audit.jsonl`, `intents.json` (Read My Mind intent profiles, mode 0600), `agent-inbox.json` (agent inbox snapshot, only while `agentInboxPersistEnabled` is on, mode 0600), `edit-history/.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//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/.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//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. diff --git a/README.md b/README.md index 2f71aec8..f6e7ad97 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/README.zh-CN.md b/README.zh-CN.md index d0900772..b7e5d2cd 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -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 里依然好用。没有服务器在跑时,它仍会以仅附着的降级模式启动。 diff --git a/config/mcp-registry/server.json b/config/mcp-registry/server.json index 79fa1ead..18b1f0e6 100644 --- a/config/mcp-registry/server.json +++ b/config/mcp-registry/server.json @@ -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" }, diff --git a/docker/Start-Codeman.sh b/docker/Start-Codeman.sh index 9f94c058..4a8c9f45 100644 --- a/docker/Start-Codeman.sh +++ b/docker/Start-Codeman.sh @@ -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() { diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index cb661430..2ada4b92 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -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 ` 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- 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-`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-`, which writes Esc and the digit into that client's own pane, so a vim `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 ` 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 ` 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- 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-`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-`, which writes Esc and the digit into that client's own pane, so a vim `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`. ### Reverse-proxy base path @@ -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 `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. @@ -267,7 +267,7 @@ Further detail: the `: ` 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×. @@ -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. @@ -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`. @@ -1379,6 +1385,8 @@ Target: 20 sessions, 50 agent windows at 60fps. Limits in `src/config/`: termina ⚠️ Truncation is reported through `onTruncated` rather than silently, with BOTH caps named: a silent depth cap hides a deep tree exactly as effectively as a silent node cap hides a wide one. +⚠️ **A kill never takes pid 0 or 1** (2026-11-25). A bound limits how MUCH a walk collects, not what it is a walk of: the children of pid 0 are init and everything below it, so `killSession()` with pid 0 signalled every process of the account, which took down every session, tmux itself and the systemd user manager (the machine did not reboot, and with the manager gone the server did not come back until the next login). It was reached by a script that drove the real `killSession()` on an empty pane lookup (`Number('')` is 0), but it needs no script. tmux answers `0` for `#{pane_pid}` of a pane without a process (`split-window ''`; measured on 3.4), `parsePaneRows()` keeps that row, and `reconcileSessions()` at server start writes it to `session.pid`, where the last pane of a session wins. The next close read 0 from tmux, fell back to the record, found 0 there too, and walked it. Reproduced on master with the signals logged instead of sent, inside a PID namespace: "Killing session codeman-feed1234 (PID 0)", "Found 15 child processes to kill". So 0 is an ordinary answer and means "nothing to signal". Three layers, all pinned in `test/kill-pid-guard.test.ts`: `killSession()` decides once (`isSignalablePid()`, an integer above 1) and otherwise leaves the close to `tmux kill-session`; `getChildPidsFresh()` walks nothing for such a root; and `signalProcess()`, the only place in `tmux-manager.ts` that sends a signal, refuses it for the group form as well (`kill(-1)` is every process, `kill(0)` is our own group). `collectDescendants()` itself stays a plain walk. A recorded 0 is deliberately left on the record rather than replaced by the older pid: that pid belongs to a process that may have exited since and been reused. + ## Local packages and build artifacts ### xterm-zerolag-input is single-source @@ -1549,3 +1557,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. diff --git a/docs/cli-registry.md b/docs/cli-registry.md index 23c3d684..4ca92ba1 100644 --- a/docs/cli-registry.md +++ b/docs/cli-registry.md @@ -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` diff --git a/docs/deepseek-integration.md b/docs/deepseek-integration.md index 02af1002..e330bd81 100644 --- a/docs/deepseek-integration.md +++ b/docs/deepseek-integration.md @@ -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` diff --git a/docs/discord-bridge.md b/docs/discord-bridge.md index 86210d3e..351aef07 100644 --- a/docs/discord-bridge.md +++ b/docs/discord-bridge.md @@ -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. diff --git a/docs/tui.md b/docs/tui.md index 92244f11..571e0f15 100644 --- a/docs/tui.md +++ b/docs/tui.md @@ -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: diff --git a/docs/web-tabs.md b/docs/web-tabs.md index 0ace6a95..64c8baa4 100644 --- a/docs/web-tabs.md +++ b/docs/web-tabs.md @@ -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 diff --git a/docs/wiki/Input-And-Voice.md b/docs/wiki/Input-And-Voice.md index d15e7864..54b29cfa 100644 --- a/docs/wiki/Input-And-Voice.md +++ b/docs/wiki/Input-And-Voice.md @@ -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 diff --git a/docs/wiki/Remote-Access.md b/docs/wiki/Remote-Access.md index 49e577cb..8c42113a 100644 --- a/docs/wiki/Remote-Access.md +++ b/docs/wiki/Remote-Access.md @@ -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 ``` diff --git a/docs/wiki/Settings-Reference.md b/docs/wiki/Settings-Reference.md index 821d6ab0..5bfd53a2 100644 --- a/docs/wiki/Settings-Reference.md +++ b/docs/wiki/Settings-Reference.md @@ -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. | diff --git a/package-lock.json b/package-lock.json index e3f2f8a0..19e3f6e4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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": [ diff --git a/package.json b/package.json index c80a627c..d9807786 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/plugins/codeman/.claude-plugin/plugin.json b/plugins/codeman/.claude-plugin/plugin.json index 2c30d073..5a6bf380 100644 --- a/plugins/codeman/.claude-plugin/plugin.json +++ b/plugins/codeman/.claude-plugin/plugin.json @@ -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" diff --git a/src/cli.ts b/src/cli.ts index f3a659a9..44c7c2f2 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -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.`)); diff --git a/src/config/cli-registry/stock.ts b/src/config/cli-registry/stock.ts index d62379fd..97e8bf05 100644 --- a/src/config/cli-registry/stock.ts +++ b/src/config/cli-registry/stock.ts @@ -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 diff --git a/src/config/cli-registry/types.ts b/src/config/cli-registry/types.ts index 00cff24d..55023179 100644 --- a/src/config/cli-registry/types.ts +++ b/src/config/cli-registry/types.ts @@ -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 diff --git a/src/cpu-usage.ts b/src/cpu-usage.ts new file mode 100644 index 00000000..03a8d93a --- /dev/null +++ b/src/cpu-usage.ts @@ -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; + }; +} diff --git a/src/deepseek-web-server.ts b/src/deepseek-web-server.ts index 78dbf961..656bf9ce 100644 --- a/src/deepseek-web-server.ts +++ b/src/deepseek-web-server.ts @@ -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)); diff --git a/src/discord-bridge.ts b/src/discord-bridge.ts index a8703371..78560ea6 100644 --- a/src/discord-bridge.ts +++ b/src/discord-bridge.ts @@ -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) { diff --git a/src/discord-reply-dedupe.ts b/src/discord-reply-dedupe.ts new file mode 100644 index 00000000..c17e13cb --- /dev/null +++ b/src/discord-reply-dedupe.ts @@ -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; + } +} diff --git a/src/proc-tree.ts b/src/proc-tree.ts index 8273c3bc..1a7278ec 100644 --- a/src/proc-tree.ts +++ b/src/proc-tree.ts @@ -32,6 +32,23 @@ export const PROC_WALK_MAX_DEPTH = 10; /** Hard ceiling on collected descendants. A backstop, not an expected limit. */ export const PROC_WALK_MAX_NODES = 500; +/** + * Whether a session kill may signal `pid`, or walk the tree below it: a real process of + * the user's, so an integer above 1. + * + * On 2026-11-25 a kill that got pid 0 took down every process of the account: all of the + * user's sessions, tmux itself and the systemd user manager. The children of pid 0 are + * the whole machine, so the bounds above do not help (500 processes are most of one), and + * `kill(-1)` means every process one may signal while `kill(0)` means one's own group. + * + * tmux answers 0 for a pane with no process (`split-window ''`), and that 0 reaches the + * session record through the pane list read at server start. So 0 is an ordinary answer + * here, not a corrupt one, and it means "nothing to signal". + */ +export function isSignalablePid(pid: number | null | undefined): pid is number { + return typeof pid === 'number' && Number.isInteger(pid) && pid > 1; +} + export interface WalkOptions { maxDepth?: number; maxNodes?: number; diff --git a/src/team-watcher.ts b/src/team-watcher.ts index d54d1c69..30809b08 100644 --- a/src/team-watcher.ts +++ b/src/team-watcher.ts @@ -15,7 +15,8 @@ import { join } from 'node:path'; import { watch as chokidarWatch, type FSWatcher as ChokidarWatcher } from 'chokidar'; -import type { TeamConfig, TeamTask, InboxMessage } from './types.js'; +import { getErrorMessage, type TeamConfig, type TeamTask, type InboxMessage } from './types.js'; +import { closeWatcherOnError } from './utils/close-watcher-on-error.js'; import { LRUMap } from './utils/lru-map.js'; import { TEAM_POLL_INTERVAL_MS, MAX_CACHED_TEAMS, MAX_CACHED_TASKS } from './config/team-config.js'; @@ -36,6 +37,8 @@ export class TeamWatcher extends EventEmitter { private sessionToTeam: Map<string, string> = new Map(); private teamsWatcher: ChokidarWatcher | null = null; private tasksWatcher: ChokidarWatcher | null = null; + // Watchers stopped by an error and not yet back for a whole poll: one warning per outage. + private watchersDown = new Set<'teams' | 'tasks'>(); constructor(teamsDir?: string, tasksDir?: string) { super(); @@ -47,11 +50,28 @@ export class TeamWatcher extends EventEmitter { start(): void { if (this.pollTimer) return; this.poll(); - this.pollTimer = setInterval(() => this.poll(), TEAM_POLL_INTERVAL_MS); + this.pollTimer = setInterval(() => { + this.setupFsWatchers(); // re-creates a watcher an error stopped + this.poll(); + }, TEAM_POLL_INTERVAL_MS); this.setupFsWatchers(); } + private watcherStopped(name: 'teams' | 'tasks', err: unknown): void { + if (this.watchersDown.has(name)) return; + this.watchersDown.add(name); + console.warn(`[TeamWatcher] ${name} watcher stopped, relying on polling: ${getErrorMessage(err)}`); + } + + /** Creates each watcher that is not running; one still running since the last call ends its outage. */ private setupFsWatchers(): void { + if (this.teamsWatcher) this.watchersDown.delete('teams'); + else this.setupTeamsWatcher(); + if (this.tasksWatcher) this.watchersDown.delete('tasks'); + else this.setupTasksWatcher(); + } + + private setupTeamsWatcher(): void { try { this.teamsWatcher = chokidarWatch(this.teamsDir, { depth: 2, @@ -66,13 +86,16 @@ export class TeamWatcher extends EventEmitter { this.teamsWatcher.on('change', teamsHandler); this.teamsWatcher.on('unlink', teamsHandler); this.teamsWatcher.on('unlinkDir', teamsHandler); - this.teamsWatcher.on('error', (err) => { - console.warn('[TeamWatcher] chokidar teams watcher error:', err); + closeWatcherOnError(this.teamsWatcher, (err) => { + this.teamsWatcher = null; + this.watcherStopped('teams', err); }); } catch (err) { - console.warn('[TeamWatcher] Failed to set up teams chokidar watcher, relying on polling:', err); + this.watcherStopped('teams', err); } + } + private setupTasksWatcher(): void { try { this.tasksWatcher = chokidarWatch(this.tasksDir, { depth: 1, @@ -84,11 +107,12 @@ export class TeamWatcher extends EventEmitter { this.tasksWatcher.on('add', () => this.pollTasks().catch(() => {})); // Ignore - poll errors are non-fatal, next poll will retry this.tasksWatcher.on('change', () => this.pollTasks().catch(() => {})); // Ignore - poll errors are non-fatal, next poll will retry - this.tasksWatcher.on('error', (err) => { - console.warn('[TeamWatcher] chokidar tasks watcher error:', err); + closeWatcherOnError(this.tasksWatcher, (err) => { + this.tasksWatcher = null; + this.watcherStopped('tasks', err); }); } catch (err) { - console.warn('[TeamWatcher] Failed to set up tasks chokidar watcher, relying on polling:', err); + this.watcherStopped('tasks', err); } } @@ -113,6 +137,7 @@ export class TeamWatcher extends EventEmitter { this.taskMtimes.clear(); this.inboxMtimes.clear(); this.sessionToTeam.clear(); + this.watchersDown.clear(); } /** Get all discovered teams */ diff --git a/src/tmux-manager.ts b/src/tmux-manager.ts index 4b211318..c2fbec55 100644 --- a/src/tmux-manager.ts +++ b/src/tmux-manager.ts @@ -22,7 +22,7 @@ */ import { EventEmitter } from 'node:events'; -import { collectDescendants, descendantsInPaneGroup } from './proc-tree.js'; +import { collectDescendants, descendantsInPaneGroup, isSignalablePid } from './proc-tree.js'; import { foreignViewSessionName, buildForeignDockerViewKillCommand, @@ -3206,6 +3206,8 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { * its process-group and tmux fallbacks. */ private async getChildPidsFresh(pid: number): Promise<number[]> { + // The children of pid 0 or 1 are the whole machine (see isSignalablePid). + if (!isSignalablePid(pid)) return []; let byParent: ReadonlyMap<number, readonly number[]>; try { byParent = await Promise.race([ @@ -3263,6 +3265,19 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { } } + /** + * The one way this class signals a process. Refuses what is not a session's process + * (see {@link isSignalablePid}); a negative `pid` is the process group, so it is judged + * by its absolute value and `-1` (everything) and `-0` (our own group) are refused too. + */ + private signalProcess(pid: number, signal: 'SIGTERM' | 'SIGKILL'): void { + if (!isSignalablePid(Math.abs(pid))) { + console.error(`[TmuxManager] Refusing to send ${signal} to pid ${pid}`); + return; + } + process.kill(pid, signal); + } + // Check if a process is still alive. Signal decisions only: an unreaped zombie // counts here, so its process group still gets the SIGKILL below. The WAITS use // waitForProcessesExit(), which counts a zombie as exited. @@ -3303,7 +3318,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { for (const childPid of [...childPids].reverse()) { if (this.isProcessAlive(childPid)) { try { - process.kill(childPid, 'SIGTERM'); + this.signalProcess(childPid, 'SIGTERM'); } catch { // Process may already be dead } @@ -3318,7 +3333,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { for (const childPid of childPids) { if (this.isProcessAlive(childPid)) { try { - process.kill(childPid, 'SIGKILL'); + this.signalProcess(childPid, 'SIGKILL'); } catch { // Process already terminated } @@ -3329,10 +3344,10 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { // Strategy 2: Kill the entire process group if (this.isProcessAlive(panePid)) { try { - process.kill(-panePid, 'SIGTERM'); + this.signalProcess(-panePid, 'SIGTERM'); await waitForProcessesExit([panePid], { timeoutMs: GRACEFUL_SHUTDOWN_WAIT_MS }); if (this.isProcessAlive(panePid)) { - process.kill(-panePid, 'SIGKILL'); + this.signalProcess(-panePid, 'SIGKILL'); } } catch { // Process group may not exist or already terminated @@ -3468,13 +3483,19 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { // kill-session below runs for it. A blank pid with `#{pane_dead}` still 0 // (tmux 3.8, pty closed, exit not collected yet) keeps the fallback: tmux // has not reaped that process, so its pid cannot have been reused. + // An empty pane has no process either: tmux says 0, and so does the record + // once a server start has read it. Nothing is signalled for pid 0 or 1 + // (isSignalablePid), and only tmux is asked to close the session. const pane = await this.readPaneForKill(session.muxName); - const currentPid = pane.dead ? null : (pane.pid ?? session.pid); + const candidatePid = pane.dead ? null : (pane.pid ?? session.pid); + const currentPid = candidatePid !== null && isSignalablePid(candidatePid) ? candidatePid : null; console.log( - currentPid === null - ? `[TmuxManager] Killing session ${session.muxName} (pane dead, PID ${session.pid} not signalled)` - : `[TmuxManager] Killing session ${session.muxName} (PID ${currentPid})` + currentPid !== null + ? `[TmuxManager] Killing session ${session.muxName} (PID ${currentPid})` + : pane.dead + ? `[TmuxManager] Killing session ${session.muxName} (pane dead, PID ${session.pid} not signalled)` + : `[TmuxManager] Killing session ${session.muxName} (no process, pane pid ${candidatePid})` ); const allPids: number[] = []; @@ -3522,7 +3543,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { // Strategy 4: Direct kill by PID as final fallback if (currentPid !== null && this.isProcessAlive(currentPid)) { try { - process.kill(currentPid, 'SIGKILL'); + this.signalProcess(currentPid, 'SIGKILL'); } catch { // Already dead } diff --git a/src/tmux-prefix-table.ts b/src/tmux-prefix-table.ts index 3af1d7da..90d64c58 100644 --- a/src/tmux-prefix-table.ts +++ b/src/tmux-prefix-table.ts @@ -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 } diff --git a/src/tui/tui-app.ts b/src/tui/tui-app.ts index 6161e83e..bbe39a58 100644 --- a/src/tui/tui-app.ts +++ b/src/tui/tui-app.ts @@ -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, { diff --git a/src/tui/tui-client.ts b/src/tui/tui-client.ts index dcfa0efc..89462694 100644 --- a/src/tui/tui-client.ts +++ b/src/tui/tui-client.ts @@ -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; } diff --git a/src/utils/close-watcher-on-error.ts b/src/utils/close-watcher-on-error.ts new file mode 100644 index 00000000..d3c72a65 --- /dev/null +++ b/src/utils/close-watcher-on-error.ts @@ -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); + }); +} diff --git a/src/web/CLAUDE.md b/src/web/CLAUDE.md index 6932427d..5260666a 100644 --- a/src/web/CLAUDE.md +++ b/src/web/CLAUDE.md @@ -56,7 +56,7 @@ 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) @@ -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. diff --git a/src/web/public/app.js b/src/web/public/app.js index e2b4c68c..94636082 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -4929,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(); } @@ -9379,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 @@ -9432,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 = ''; @@ -9973,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 {} @@ -10024,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 }); @@ -10823,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. @@ -11104,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 {} diff --git a/src/web/public/constants.js b/src/web/public/constants.js index 7421e1c7..ec8a5fe8 100644 --- a/src/web/public/constants.js +++ b/src/web/public/constants.js @@ -112,7 +112,7 @@ const MOBILE_RESIZE_RETRY_MS = 30000; // Small-viewport resize re-send whi const AUTO_CLOSE_NOTIFICATION_MS = 8000; // Auto-close browser notifications const DEFAULT_TOAST_DURATION_MS = 3000; // How long a corner toast stays by default const MIN_NOTIFICATION_DURATION_MS = 1000; // Shortest configurable toast / browser-notification time -const MAX_NOTIFICATION_DURATION_MS = 300000; // General UI throttle delay +const MAX_NOTIFICATION_DURATION_MS = 300000; // Longest configurable toast / browser-notification time const TERMINAL_CHUNK_SIZE = 32 * 1024; // 32KB chunks for terminal buffer loading const TERMINAL_TAIL_SIZE = 1024 * 1024; // 1MB tail for initial load (more scrollback on tab switch) // A shell's automatic loads (tab select, drop recovery, a tile's load) read @@ -130,7 +130,7 @@ const TERMINAL_TAIL_SIZE = 1024 * 1024; // 1MB tail for initial load (more s const SHELL_LOAD_HISTORY_LINES = 10000; const SHELL_LOAD_BASE_QUERY = `full=1&tail=${TERMINAL_TAIL_SIZE}&alt=recording`; const SHELL_LOAD_QUERY = `${SHELL_LOAD_BASE_QUERY}&lines=${SHELL_LOAD_HISTORY_LINES}`; -const SYNC_WAIT_TIMEOUT_MS = 50; // System stats polling +const SYNC_WAIT_TIMEOUT_MS = 50; // Wait timeout for terminal sync const TUI_REDRAW_SETTLE_MS = 400; // Grace for a TUI to redraw after a real resize, before fetching its buffer // Z-index base values for layered floating windows diff --git a/src/web/public/i18n.js b/src/web/public/i18n.js index 923742fe..5b768a14 100644 --- a/src/web/public/i18n.js +++ b/src/web/public/i18n.js @@ -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': '滚轮滚动本地历史', diff --git a/src/web/public/index.html b/src/web/public/index.html index 7d1d1430..0660574f 100644 --- a/src/web/public/index.html +++ b/src/web/public/index.html @@ -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 @@ -2064,6 +2065,13 @@ +
+
+ Input Field: Send on Enter + 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. +
+ +
Extended Keyboard Bar phone diff --git a/src/web/public/input-cjk.js b/src/web/public/input-cjk.js index 4f5420b7..263ce654 100644 --- a/src/web/public/input-cjk.js +++ b/src/web/public/input-cjk.js @@ -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