Compare commits

..
Author SHA1 Message Date
Codeman maintainer 4cedeec529 feat(desktop): server tabs, several Codeman servers open in one window
The Mac app showed one server at a time, and moving to another machine
meant Switch Server and a fresh connect. Now every server gets a tab in
the title bar, and every tab stays live.

- Tab strip: a small bundled page (assets/tabs.html) in its own web view
  across the top of the window, with the traffic lights inset into it.
  Each tab has a colour and a status badge: a red count when sessions
  need you, an amber dot when they are waiting, a blue ring while they
  work, a dashed circle while the server does not answer.
- The status comes from the app, not from the page: one thread per tab
  reads GET /api/sessions every 2 seconds (macOS stalls hidden web
  views), backs off for 60 s on a 429 and stops on 401/403, so a wrong
  password is never retried in a loop.
- + or ⌘T opens the connect screen in a new tab. A server that is
  already open just brings its tab forward instead of opening twice,
  also when two connects race (checked again when the probe ends).
- Double-click or the right-click menu renames a tab; the same menu
  sets the colour, reloads, reconnects, closes, or closes the others.
  Tabs can be dragged. A new Server menu carries ⌘T, ⌘W, ⇧⌘T (reopen
  closed tab, last 10), ⌘0, ⇧⌘[ / ⇧⌘] and ⌘1 to ⌘8 (⌘9 is the last
  tab once there are nine). Close Window moves to ⇧⌘W. Ctrl+Tab and
  Alt+1..9 stay with Codeman's own session switching.
- ⌘0 shows every server at once (assets/overview.html): the ones that
  need you first, up to four sessions each with what they ask, and a
  click on a session opens its tab and selects it.
- Tabs are saved in desktop.json (tabs, activeTab) and come back at
  launch, connecting by themselves when auto-connect is on.
- Logins: each tab keeps its own Basic credentials, and a challenge is
  answered only with the login of the tab whose web view asked
  (macos.rs binds each WKWebView to its tab).
- Cookies: on macOS 14 and later every server gets its own WebKit data
  store (WKWebsiteDataStore dataStoreForIdentifier, with a stable id
  hashed from the server URL), so a server on port 3000 and a beta on
  5000 of the same host cannot log each other out. Before macOS 14 a
  second tab on a host that is already open is refused with a message.
  The server used last before this change keeps the default store, so
  its per-device settings (font size, skin) survive; every other
  server starts those fresh once.
- The lid logo blink watches all open servers, and Keep This Mac Awake
  follows the tab that runs on this Mac.

New pure model in src/tabs.rs (names, colours, order, shortcuts, strip
and overview state) with unit tests; agents.rs reads the per-session
detail for the badges and the overview; policy.rs parses the strip and
overview IPC and refuses it from any other frame. Browser tests drive
both bundled pages (test/desktop-tabs-pages.browser.test.ts) and the
connect page's restored-tab path.

Not yet run in a real window: the Mac mini has no screen session. The
owner checks the traffic-light placement, clicks under the transparent
title bar, window drag and zoom from the strip, keyboard focus after
strip clicks, and two logged-in servers side by side.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 18:36:08 +01:00
91 changed files with 6282 additions and 6043 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"aicodeman": patch
---
**Mac app: server tabs.** The Mac app now keeps several Codeman servers open in one window, one tab each in the title bar, and switches between them with a click or ⌘1 to ⌘8. Every tab shows whether its server needs you, is waiting, is working or is offline, and ⌘0 shows all servers at once with the ones that need you first. ⌘T opens another server, a tab can be renamed, coloured and dragged, ⇧⌘T reopens a closed one, and your tabs come back at the next launch. On macOS 14 and later every server keeps its own login and cookies; before macOS 14 a second tab on the same machine is refused. Behaviour change: only the server you used last keeps its per-device settings (font size, skin); every other server starts those fresh once.
+1 -1
View File
@@ -10,7 +10,7 @@
"name": "codeman",
"source": "./plugins/codeman",
"description": "Drive Codeman from inside a Claude Code session: spawn worker sessions, prompt them, wait for them, read their answers, clean up. Acts inside a Codeman-managed session; outside one it only reads saved Codex conversations offline.",
"version": "1.51.1",
"version": "1.51.0",
"author": {
"name": "Ark0N",
"url": "https://github.com/Ark0N"
-38
View File
@@ -1,43 +1,5 @@
# aicodeman
## 1.51.1
### Patch Changes
- 1d33220: ### Thanks
- @kkalisz for Send on Enter in the phone's input field (#820), `codeman tui <name>` (#834), and a password-protected Codeman that installs as an app (#826).
- @ArizeSky for web tabs that render the DeepSeek Harness web UI and Vite dashboards (#825), and for closing a session-cookie leak on the web tab's WebSocket leg (#827).
- @JDProfresh for tracking a 174 GiB log flood down to a chokidar retry loop and fixing it (#818), and for wheel forwarding that any CLI entry can ask for (#831).
- @aakhter for the tmux 3.7 key-table fix (#821) and for Start-Codeman.sh on WSL (#822).
- @ludovicfourrage for the report and the fix that makes the header's CPU reading real CPU use (#823, #824).
- @johoja12 for Discord replies that are typed once, however often the gateway replays them (#832).
- @shenlvkang-collab for the report in #701 that led to answers on a relocated Claude config folder (#812).
**Phone: Send on Enter for the input field (#820).** A new per-device setting next to CJK Input, Input Field: Send on Enter. With both on, the field above the keyboard works like a chat box: your text stays there while you scroll the terminal to reread a question, Enter sends it, Shift+Enter adds a line and Esc clears it. The phone keyboard layout is sturdier for everyone too: a swipe on the live screen no longer closes the field's keyboard, and on iOS the bars sit on the keyboard the first time it opens.
**The terminal dashboard attaches by session name (#834).** `codeman tui <name>` attaches to a live session by its exact name as well as by its list number, so getting back into the same session over SSH no longer depends on where it sits in the list.
**Web tabs render the DeepSeek Harness web UI and Vite dashboards (#825).** The DeepSeek Harness web tab opened on a blank 401 page since `dsh web` started asking for a one-time launch token. Codeman now trades that token for dsh's session cookie and presents it only to that tab. Dashboards that ship a relative `<base href>` (what Vite and SvelteKit builds emit) and ones that load modules with `import("/...")` render through the web tab proxy too.
**Local model: Muse Glimmer 30B as its MLX build (#803).** On a Mac with 48 GB or more, Run a model on this Mac offers the MLX build of Muse Glimmer 30B. On an M5 Pro with 48 GB it wrote twice as many tokens a second as the GGUF build on the same request, and finished an OpenCode turn the GGUF build never answered. Macs with 32 or 36 GB keep the GGUF row as it was.
**Fixes.**
- **A failing file watcher no longer floods the log (#818).** When Linux ran out of inotify instances, a watcher whose `fs.watch` failed retried on each parent folder up to `/` and then forever, writing about 112,000 log lines a second until the disk filled. It now logs one warning and keeps working by polling, and the agent-teams watcher switches its live watcher back on once watching works again.
- **A password-protected Codeman installs as an app (#826).** The browser fetched the app manifest without the login cookie and got a 401, so Chrome's Install app refused. The manifest request now carries the cookie.
- **A trusted web tab's WebSocket no longer sends Codeman's session cookie to the dashboard (#827).** The HTTP leg already stripped it.
- **Answers come back for a session on its own Claude config folder (#701, #812).** A session started with `CLAUDE_CONFIG_DIR` (a second Claude account) showed "No response yet" in the response viewer, and `codeman agent read` and the Discord bridge's last message came back empty. They now read the transcript from that session's own folder.
- **tmux 3.7 to 3.7c: the prefix table and `codeman tui` keys read right (#821).** Those releases print nothing for a key table with exactly one binding, so Codeman reset its already reduced prefix table on every new session and `codeman tui` took a bound key for a free one.
- **`docker/Start-Codeman.sh` no longer hangs on WSL (#822).** Each free-port check gives up after about a second instead of waiting out the kernel's connect timeout.
- **The header CPU reading is CPU use (#823, #824).** It showed the load average per core, which read 100% on a host whose cores were mostly idle. Behaviour change: on such a host the figure is now much lower.
- **Discord: a replayed reply is typed once (#832).** A gateway replay, also after a restart, could type the same reply into a session twice. If the small store that prevents it fails, the reply is still typed.
- **A custom full-screen CLI can get the mouse wheel (#831).** The wheel went only to a fixed list of CLIs. It now follows each entry's `wheelForward` rule, so a `clis.json` entry can ask for it; stock CLIs behave as before.
**Fixes applied while landing.** The web tab proxy filters Codeman's session cookie off the WebSocket leg whether or not the dsh cookie is added, and a dsh tab created in multi-user mode still gets its cookie after a switch back to single-user mode (#825, #827). The CPU fallback no longer divides by a core count of 0 (#824). A watcher that a restart finds still failing warns again, and the watcher tests skip on macOS, where chokidar never calls `fs.watch` (#818). The Discord reply store has a test for a planted symlink at its path (#832).
**Docs and tests.** The docs name the tmux releases with the blank key-table answer, the DeepSeek web cookie rules and how a custom full-screen CLI asks for the wheel.
About 8,900 lines of code nothing reached are gone, among them the Ralph plan wizard that no button opened any more and the Agent Teams terminal windows; no route, setting or SSE event was removed. `npm run check:frontend-dead` lists frontend code nothing references.
## 1.51.0
### Minor Changes
+6 -8
View File
@@ -52,7 +52,7 @@ Uses [Semantic Versioning](https://semver.org/) (`MAJOR.MINOR.PATCH`) via `@chan
When the user says **COM** (`COM` = patch, `COM minor`, `COM major`): **Read [`docs/releasing.md`](docs/releasing.md) and follow every step in order**; never improvise a release from memory. It covers the changeset, `npm run version-packages`, the `**Version**` line below, the branch check and explicit-path commit, deploy, the getcodeman.com badge, watching BOTH CI workflows, the MCP registry publish, and the Discussions announcement.
**Version**: 1.51.1 (must match `package.json`)
**Version**: 1.51.0 (must match `package.json`)
## Project Overview
@@ -64,7 +64,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
**Requirements**: Node.js 22+, Claude CLI, tmux
**Git**: Main branch is `master`. Terminal session dashboard: `codeman tui` (`--list` to list, `codeman tui <n>` or `codeman tui <name>` to attach).
**Git**: Main branch is `master`. Terminal session dashboard: `codeman tui` (`--list` to list, `codeman tui <n>` 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`. An allowed reply is claimed by message ID before rate-limit or exited-agent checks, attachments or typing; a store failure never costs a reply. A file that could not be read is never overwritten. ⚠️ Guards that live in code and tests pin: only `allowedUserIds`, in `guildId`, inside a thread the bridge created, are acted on, everything else is dropped unread; a reply is one printable line plus Enter (a lone digit while a permission or question is pending goes as the key alone, since the dialog acts on it), capped and rate limited, and `discord-notify` is a per-session token bucket (6 a minute, 429 `RATE_LIMITED`; `fileProblem` probes the folder with the bounded probe first); posts send `allowed_mentions` limited to the allowlisted ids; received files go only from Discord's own HTTPS hosts (max 5 x 8 MB, names reduced to `[A-Za-z0-9._-]`) into `<tab folder>/.codeman-discord/`, and a sent file's REAL path must lie inside the tab's folder (`fileProblem`, symlinks followed); a Discord failure never reaches a session; the alert tail is a function the bridge calls only once it will post (no tmux exec per event while off); a delete reaches the bridge from the cleanup path with `killMux` true, never from `session:deleted`, which a detach also fires; `.codeman-discord/` is probed with the bounded probe, refused if a symlink, and ignores itself with a `.gitignore` of `*`; a config restore of `discord.json` reloads the running bridge (`afterRestore`). The startup hint ("how to reach the user") rides the CLI registry as the engine value `appendSystemPrompt` (Claude's `--append-system-prompt`, undefined unless the bridge and `startupHint` are on, so every other launch is byte-identical) No other CLI is told. `codeman notify "<message>" [--urgent] [--file <path>]` wraps `POST /api/sessions/:id/discord-notify`, which accepts a unique 8-character id prefix (a Docker case exports it cut). → `docs/discord-bridge.md`, `docs/wiki/Discord-Bridge.md`, `docs/api-reference.md`
**Discord bridge (`src/discord-bridge.ts`, `src/web/routes/discord-routes.ts`, `src/cli-notify.ts`)**: opt-in two-way Discord (a bot, not the one-way webhook), one thread per tab. Split like `webhook-notify.ts`: pure helpers, a 0600 store (`discord.json` holds the bot token, is never returned by these routes and is on the sensitive-path list; `discord-bridge.json` maps sessionId to thread id), then IO (`DiscordApi` REST with injected fetch, `DiscordGateway` inbound WebSocket with injected socket, `DiscordBridge` rules). Outbound hangs off `WebServer.sendPushNotifications` beside the webhook (so it works with zero push subscriptions) and tab events off `WebServer.broadcast` (`bridgeSessionEvent`); a finished turn (Claude's idle and stop hooks, DeepSeek's stop; the other CLIs raise no turn end, so theirs arrive with an error, a blocked respawn, a crash loop or `codeman notify`) or an error posts the CLI's WHOLE last message as markdown, read from its transcript through the response viewer's reader (`WebServer.lastResponseFor`, set by the session routes: the CLI's own transcript, or the pane segmented into turns for the CLIs that keep none; never for a shell), split over posts of at most 1900 characters and not posted twice (keyed on the text plus its turn, recorded only after the first post succeeds), while a dialog and every CLI without a transcript post the RENDERED tmux screen (`screenTail`, with the composer row and the status lines under it cut), never the raw stream, which a full-screen UI repaints in place; `staleThreads` (default `keep`) archives or deletes threads the bot owns that no tab maps to, after boot and then daily, never one under an hour old, never with an empty map and at most 25 per run. Inbound replies are typed through `session.writeViaMux`. ⚠️ Guards that live in code and tests pin: only `allowedUserIds`, in `guildId`, inside a thread the bridge created, are acted on, everything else is dropped unread; a reply is one printable line plus Enter (a lone digit while a permission or question is pending goes as the key alone, since the dialog acts on it), capped and rate limited, and `discord-notify` is a per-session token bucket (6 a minute, 429 `RATE_LIMITED`; `fileProblem` probes the folder with the bounded probe first); posts send `allowed_mentions` limited to the allowlisted ids; received files go only from Discord's own HTTPS hosts (max 5 x 8 MB, names reduced to `[A-Za-z0-9._-]`) into `<tab folder>/.codeman-discord/`, and a sent file's REAL path must lie inside the tab's folder (`fileProblem`, symlinks followed); a Discord failure never reaches a session; the alert tail is a function the bridge calls only once it will post (no tmux exec per event while off); a delete reaches the bridge from the cleanup path with `killMux` true, never from `session:deleted`, which a detach also fires; `.codeman-discord/` is probed with the bounded probe, refused if a symlink, and ignores itself with a `.gitignore` of `*`; a config restore of `discord.json` reloads the running bridge (`afterRestore`). The startup hint ("how to reach the user") rides the CLI registry as the engine value `appendSystemPrompt` (Claude's `--append-system-prompt`, undefined unless the bridge and `startupHint` are on, so every other launch is byte-identical) No other CLI is told. `codeman notify "<message>" [--urgent] [--file <path>]` wraps `POST /api/sessions/:id/discord-notify`, which accepts a unique 8-character id prefix (a Docker case exports it cut). → `docs/discord-bridge.md`, `docs/wiki/Discord-Bridge.md`, `docs/api-reference.md`
**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`.
@@ -160,8 +160,6 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
**Process-tree walks are bounded** (`proc-tree.ts`, pure): `collectDescendants(pid, byParent)` is the ONE descendant traversal, fed by one cached `ps -eo pid=,ppid=` snapshot (`refreshProcSnapshot()` in tmux-manager.ts: async, in-flight-shared, and ANY error discards the result rather than caching a truncated `ps`). ⚠️ Never walk a process tree with per-node `pgrep` or unbounded recursion (the unbounded version took a machine down): the walk must terminate on cycles, cap depth (`PROC_WALK_MAX_DEPTH`) and node count (`PROC_WALK_MAX_NODES`), and never spawn anything. ⚠️ Keep it in its own module so the test exercises the shipped code, and report truncation through `onTruncated` naming both caps, never silently. → [architecture-invariants#process-tree-walks-are-bounded](docs/architecture-invariants.md#process-tree-walks-are-bounded)
**A `persistent: false` chokidar watcher stops on its first error**: ⚠️ its `'error'` handler goes through `closeWatcherOnError()` (`utils/close-watcher-on-error.ts`), never a bare log or `close()`. chokidar 3 retries a failed `fs.watch` (EMFILE once the inotify instances are used up, ENOSPC once the watches are) on the parent directory up to `/` forever, logging every pass (one server wrote 174 GiB of log that way); a bare `close()` turns the follow-up TypeError into an unhandled rejection, and a callback already in flight can reopen it through `add()`. The watcher's own poll must cover what it watched and create it again on a later tick (`TeamWatcher`, `WorkflowRunWatcher`): chokidar 3 reports a one-off ENOENT race (a new file gone between its `stat` and `watch`) through the same TypeError, so a watcher that stayed closed would end live updates until a restart. Tests: `test/watcher-fs-watch-failure.test.ts`.
**Auto-resume on usage limit** (opt-in per session, top of the Respawn tab): when Claude halts on a subscription limit, `usage-limit-patterns.ts` (pure, unit-tested) parses the reset time and `SessionAutoOps` arms a timer for reset+2min, then sends Esc + `continue`. ⚠️ Respawn cycles are blocked while paused (`isLimitPaused` guard in `onIdleDetected`), which is what prevents `/clear` from wiping the paused conversation. Claude-mode only. → [architecture-invariants#auto-resume-on-usage-limit](docs/architecture-invariants.md#auto-resume-on-usage-limit)
**Auto-compact and auto-clear** (opt-in per session, Respawn tab; `session-auto-ops.ts`, pure decision `decideAutoThreshold()`): for a Claude session the size compared with the threshold is the context Claude Code reports on its statusline (`context_window.total_input_tokens`, cache reads included, handed over by `POST /api/status-telemetry` through `Session.noteContextReport()`); the session's token counter never sees the cached context and is only the fallback for a launch without the exporter. Thresholds go up to the reported window (`contextWindowSize`, 1M while unknown). ⚠️ After a `/compact` or `/clear` the report from before the command is ignored by VALUE, never for a length of time (a 601k compact took 39 s). ⚠️ The decision is made AGAIN when the command goes out (`_decideAtSend()`): a report fires the trigger in the middle of a turn, and the wait for that turn to end can outlast a compaction by Claude Code itself, so a `/clear` sent on the old answer would wipe a conversation that is small again. A skipped command stamps nothing. ⚠️ Nothing is sent into a usage-limit pause (`_heldByLimit()`, until auto-resume's `continue` went out), or that `continue` is typed into an empty conversation. → [architecture-invariants#auto-compact-and-auto-clear-thresholds](docs/architecture-invariants.md#auto-compact-and-auto-clear-thresholds)
@@ -190,7 +188,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, 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)
**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)
**Case rename** (`POST /api/cases/:name/rename`, `src/case-rename.ts`; `docs/wiki/Core-Concepts.md#case`): a case under the cases dir is its folder name and always moves; a linked case renames its alias and moves its real folder only with `renameFolder`; remote and Docker cases are refused. ⚠️ A folder that sessions have open is the hazard: live sessions at or under it make the route answer `409 requiresStop` with their names, and only `stopSessions: true` ends them (via `ctx.cleanupSession`: closed like a tab close, uploads included, nothing is restarted); the free-target pre-check runs before that and refuses a dangling symlink too (`lstat`, as `moveCaseFolder` does), so no session is ended for a move that cannot happen. `withCaseLock` holds the old and new paths for the whole operation (`isCasePathLocked`; the `Session` constructor throws for a working directory inside a held path, so nothing is constructed mid-move). ⚠️ A create awaits the owner's layout lock and a settings read between `new Session` and the server's map, where the rename looks for open sessions, so the constructor also records the session (`noteCaseSessionStarting`) until `registerSessionWithLayout()` or `stop()` settles it (30 s TTL for one that never registers), and a folder move refuses `409` with `renameCode: "BUSY"` while one is recorded at or under the folder (`isCaseSessionStarting`, checked in the same tick that takes the lock); an alias-only rename is not refused. A create whose path was validated before the move but whose `Session` is constructed after it is not covered (the plain check-then-use race of any create path), `moveCaseFolder` refuses an existing target itself (POSIX `rename` would silently replace an EMPTY directory) and retries `EBUSY`/`EPERM`/`EACCES` before answering `423 LOCKED`. If the registries (`linked-cases.json`, `caseOrder`, `lastUsedCase`, `lastPickedCase`, `caseSettings`) fail after the move, `settings.json` and the folder are put back (a failed move-back says the folder is now at the new path), and an error after `stopSessions` carries `stoppedSessions`. Claude Code keys history by path (`claudeProjectDirName`: every non-alphanumeric becomes `-`), so `<claude config>/projects/<old>` is renamed too, or merged entry by entry, never overwriting, into one already at the new key (case delete never removes history, so an earlier case of the new name leaves one); other CLIs' history, Docker bind mounts, `git worktree` links, cron jobs' `workingDir`, Claude history of subfolder sessions and Claude Code's per-project entry in `~/.claude.json` (local-scope `mcpServers`, `allowedTools`, trust; writing another CLI's config is the opt-in MCP sync's job) are NOT migrated. The history scanner prefers the decoded project key over a transcript's `cwd` that no longer exists, so Resume follows a rename. Only an admin's rename touches the server-wide `settings.json` (`caseOrder`, `lastUsedCase`, `lastPickedCase`, `caseSettings`); the owner's default session group is carried across with `TabLayoutService`. `settings.json` is written before `linked-cases.json`, so a failed or refused registry write puts `settings.json` back and leaves the registry as it was. ⚠️ Every write to `linked-cases.json` (link, unlink, rename, and a create or clone into a custom folder) goes through `mutateLinkedCases()` (`src/web/linked-cases-writer.ts`: serialized, temp file + rename, and a file that does not parse is refused, never read as `{}`; the one direct writer is config-backup restore, `restoreConfigBackup()`, which must work on such a file), and a check that must still hold when the entry is written (the name is free; for a rename, the old entry still names the folder) runs INSIDE its callback: two clones that claimed one name used to both pass a re-read made outside it and both answer success. Pinned by `test/linked-cases-writer.test.ts`, and for a rename by `test/routes/case-rename-routes.test.ts`.
@@ -230,7 +228,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**. 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)
**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)
**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)
@@ -336,7 +334,7 @@ One module per domain in `src/web/routes/` (plus a barrel; `ls src/web/routes/`
## State Files
All in `~/.codeman/`: `state.json` (sessions, settings, respawn, orchestrator, cron jobs/runs, owner tab layouts, case default groups), `mux-sessions.json` (tmux recovery), `settings.json` (user prefs), `push-keys.json` + `push-subscriptions.json`, `session-lifecycle.jsonl` (audit log), `update-status.json` (self-updater progress, polled across the service restart), `docker-env-applied.json` (Compose deployment only: sha256 of the Dockerfile + compose file the running container was built from, written by `Start-Codeman.sh`, read by the self-updater's environment gate), `docker-build-source.json` (Compose deployment only: the checkout's HEAD commit and `package-lock.json` hash the `codeman-node-modules`/`codeman-dist` volumes currently reflect, written by both `Start-Codeman.sh` and a successful in-place self-update, compared to detect and refresh a volume left stale by an externally-triggered rebuild), `linked-cases.json`, `webviews.json` (saved web-tab dashboard URLs), `remote-hosts.json` + `remote-cases.json`, `docker-hosts.json` + `docker-cases.json` + `docker-exports/`, `subagent-window-states.json` + `subagent-parents.json` (subagent window layout, GET/PUT `/api/subagent-window-states`/`-parents`), `hook-secret` (per-instance), `users.json` (multi-user, mode 0600) + `admin-audit.jsonl`, `intents.json` (Read My Mind intent profiles, mode 0600), `agent-inbox.json` (agent inbox snapshot, only while `agentInboxPersistEnabled` is on, mode 0600), `edit-history/<id>.json` (Edit history panel, one store per session, every diff an agent wrote, mode 0600), `webhook.json` (webhook notifications: enabled/service/scope plus the ntfy/Slack/Discord URL, a bearer secret, so mode 0600, kept out of `settings.json` and never returned by `/api/webhook`, which is admin-only in multi-user mode), `discord.json` (Discord bridge: bot token, a bearer secret, so mode 0600, never returned by `/api/discord`, admin-only in multi-user mode) + `discord-bridge.json` (sessionId to Discord thread id) + `discord-reply-dedupe.json` (replayed-reply guard: at most 2,048 Discord message IDs with timestamps, kept 7 days, mode 0600; a file that could not be read is never overwritten), `local-model.json` (local model install: state, step, model, port, pid, digest, the checked models of the library, the previous `customModelEndpointsEnabled` value; mode 0600, holds no path, not part of a config backup) + `local-model/` (the pinned runtime, the model store and the runtime's private HOME, removed by `DELETE /api/local-model`), `agent-skill-default-migrated.json` (written once by the 1.50.0 boot migration of `agentSkillEnabled`; while it exists the migration never runs again, so deleting it would switch a stored off on at the next start; never tracked or restored), `config-backup-id` (the random id config backups record as each manifest's `origin`, so instances sharing a backup folder keep to their own snapshots; mode 0600, never tracked or restored, and deleting it unlists this instance's earlier snapshots), `backups/config/` (the default config-backup folder, moved by `configBackupDir`: `cfg-YYYYMMDD-HHMMSS/` snapshots, 0700 with 0600 files, each with a `manifest.json` of SHA-256s, the origin and the retention in force (`keepCount`/`keepDays`), which a pass falls back to when `settings.json` lacks a retention key), `certs/` (self-signed TLS for `--https`), `.env` (CODEMAN_USERNAME/PASSWORD fallback for the `codeman attach` CLI), `install.log` (installer step output, written by `install.sh`'s `run_step`) `tailscale-rename` (the node name before `install.sh` renamed it, so uninstall can offer it back), `cli-installed` (empty, touched by `install.sh` when it installs a CLI: a running server reads only its mtime, and a change ends that CLI's negative-cache backoff) and `runtime/` (the Node.js and tmux `install.sh` downloaded on its no-admin route, linked from `~/.local/bin`; all four installer-route only). Transient: `self-update-runner.sh`. Multi-user case spaces live OUTSIDE the data dir at `~/codeman-users/<username>/cases` (shared across instances like `~/codeman-cases`, override `CODEMAN_USER_SPACES_DIR`).
All in `~/.codeman/`: `state.json` (sessions, settings, respawn, orchestrator, cron jobs/runs, owner tab layouts, case default groups), `mux-sessions.json` (tmux recovery), `settings.json` (user prefs), `push-keys.json` + `push-subscriptions.json`, `session-lifecycle.jsonl` (audit log), `update-status.json` (self-updater progress, polled across the service restart), `docker-env-applied.json` (Compose deployment only: sha256 of the Dockerfile + compose file the running container was built from, written by `Start-Codeman.sh`, read by the self-updater's environment gate), `docker-build-source.json` (Compose deployment only: the checkout's HEAD commit and `package-lock.json` hash the `codeman-node-modules`/`codeman-dist` volumes currently reflect, written by both `Start-Codeman.sh` and a successful in-place self-update, compared to detect and refresh a volume left stale by an externally-triggered rebuild), `linked-cases.json`, `webviews.json` (saved web-tab dashboard URLs), `remote-hosts.json` + `remote-cases.json`, `docker-hosts.json` + `docker-cases.json` + `docker-exports/`, `subagent-window-states.json` + `subagent-parents.json` (subagent window layout, GET/PUT `/api/subagent-window-states`/`-parents`), `hook-secret` (per-instance), `users.json` (multi-user, mode 0600) + `admin-audit.jsonl`, `intents.json` (Read My Mind intent profiles, mode 0600), `agent-inbox.json` (agent inbox snapshot, only while `agentInboxPersistEnabled` is on, mode 0600), `edit-history/<id>.json` (Edit history panel, one store per session, every diff an agent wrote, mode 0600), `webhook.json` (webhook notifications: enabled/service/scope plus the ntfy/Slack/Discord URL, a bearer secret, so mode 0600, kept out of `settings.json` and never returned by `/api/webhook`, which is admin-only in multi-user mode), `discord.json` (Discord bridge: bot token, a bearer secret, so mode 0600, never returned by `/api/discord`, admin-only in multi-user mode) + `discord-bridge.json` (sessionId to Discord thread id), `local-model.json` (local model install: state, step, model, port, pid, digest, the checked models of the library, the previous `customModelEndpointsEnabled` value; mode 0600, holds no path, not part of a config backup) + `local-model/` (the pinned runtime, the model store and the runtime's private HOME, removed by `DELETE /api/local-model`), `agent-skill-default-migrated.json` (written once by the 1.50.0 boot migration of `agentSkillEnabled`; while it exists the migration never runs again, so deleting it would switch a stored off on at the next start; never tracked or restored), `config-backup-id` (the random id config backups record as each manifest's `origin`, so instances sharing a backup folder keep to their own snapshots; mode 0600, never tracked or restored, and deleting it unlists this instance's earlier snapshots), `backups/config/` (the default config-backup folder, moved by `configBackupDir`: `cfg-YYYYMMDD-HHMMSS/` snapshots, 0700 with 0600 files, each with a `manifest.json` of SHA-256s, the origin and the retention in force (`keepCount`/`keepDays`), which a pass falls back to when `settings.json` lacks a retention key), `certs/` (self-signed TLS for `--https`), `.env` (CODEMAN_USERNAME/PASSWORD fallback for the `codeman attach` CLI), `install.log` (installer step output, written by `install.sh`'s `run_step`) `tailscale-rename` (the node name before `install.sh` renamed it, so uninstall can offer it back), `cli-installed` (empty, touched by `install.sh` when it installs a CLI: a running server reads only its mtime, and a change ends that CLI's negative-cache backoff) and `runtime/` (the Node.js and tmux `install.sh` downloaded on its no-admin route, linked from `~/.local/bin`; all four installer-route only). Transient: `self-update-runner.sh`. Multi-user case spaces live OUTSIDE the data dir at `~/codeman-users/<username>/cases` (shared across instances like `~/codeman-cases`, override `CODEMAN_USER_SPACES_DIR`).
**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.
-1
View File
@@ -744,7 +744,6 @@ A full-screen dashboard for your sessions, in the terminal. Same states as the w
codeman tui # the dashboard
codeman tui --list # numbered session list, then exit (scriptable)
codeman tui 2 # attach straight to session 2 of that list
codeman tui api-docs # attach straight to the live session named api-docs
```
Sessions are grouped **NEEDS YOU → WORKING → IDLE → RECENT**, longest-waiting first. `↑↓`/`j`/`k` select, `1`-`9` and `[`/`]` switch between sessions, `Enter` attaches into the tmux pane (**`F1`** to come back). Inside a pane the bar across the top keeps the session strip visible and `Alt+1`-`Alt+9` switch without leaving. `y`/`n`/digit answer a pending permission dialog right from the list, `p` sends a one-line prompt, `n` starts a session and opens straight into it, `x` kills one (`y` confirms), `/` searches, `g` shows the away digest, `?` is help, `q` quits. Below 72 columns it drops the preview pane and becomes a single-column list, so it stays usable in Termius on a phone. With no server running it still starts in attach-only degraded mode.
-1
View File
@@ -741,7 +741,6 @@ Codeman 默认用 `--dangerously-skip-permissions` 启动会话,因此 Web UI
codeman tui # 仪表盘
codeman tui --list # 带编号的会话列表,随即退出(可用于脚本)
codeman tui 2 # 直接附着到列表里的第 2 个会话
codeman tui api-docs # 直接附着到名为 api-docs 的活动会话
```
会话按 **NEEDS YOU → WORKING → IDLE → RECENT** 分组,等得最久的排最前。`↑↓`/`j`/`k` 选择,`1`-`9` 与 `[`/`]` 切换会话,`Enter` 附着进 tmux 面板(按 **`F1`** 回来)。在面板里,顶部的横条会一直显示会话条,`Alt+1`-`Alt+9` 不用离开就能切换。`y`/`n`/数字可以直接在列表里回答待处理的权限对话框,`p` 发送一行提示,`n` 新建会话并直接进入,`x` 杀掉一个(`y` 确认),`/` 搜索,`g` 显示离开摘要,`?` 是帮助,`q` 退出。窄于 72 列时它会去掉预览面板、变成单列列表,所以在手机上的 Termius 里依然好用。没有服务器在跑时,它仍会以仅附着的降级模式启动。
+2 -2
View File
@@ -3,7 +3,7 @@
"name": "io.github.Ark0N/codeman",
"title": "Codeman",
"description": "Start, prompt and read AI coding agent sessions (Claude Code, Codex, Gemini CLI and more) in Codeman",
"version": "1.51.1",
"version": "1.51.0",
"websiteUrl": "https://getcodeman.com",
"repository": {
"url": "https://github.com/Ark0N/Codeman",
@@ -13,7 +13,7 @@
{
"registryType": "npm",
"identifier": "aicodeman",
"version": "1.51.1",
"version": "1.51.0",
"transport": {
"type": "stdio"
},
+1
View File
@@ -63,6 +63,7 @@ export const BROWSER_TEST_GLOBS = [
'test/terminal-touch-swipe-axis.browser.test.ts',
'test/phone-press-feedback.browser.test.ts',
'test/desktop-connect-page.browser.test.ts', // no server: the page is served by request interception
'test/desktop-tabs-pages.browser.test.ts', // no server: the pages are served by request interception
'test/local-model-ui.browser.test.ts',
'test/home-breakpoint-swap.browser.test.ts',
'test/log-viewer-reconnect.browser.test.ts',
+1 -24
View File
@@ -156,33 +156,10 @@ 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() {
port_answers 127.0.0.1 "$1" || port_answers ::1 "$1"
(exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null || (exec 3<>"/dev/tcp/::1/$1") 2>/dev/null
}
first_free_port() {
+5 -15
View File
@@ -18,7 +18,7 @@ Implementation detail extracted from `CLAUDE.md` so that file stays small enough
### The prefix table on Codeman's socket holds only send-prefix
**Browser tabs are tmux clients, so tmux's prefix table must not reach `switch-client`** (`src/tmux-prefix-table.ts`, called from `createSession` before `respawn-pane`, and from `reconcileSessions()` at boot whenever the socket lists a pane, so sessions that survived an upgrade are covered). Every keystroke typed into a browser terminal reaches the `tmux attach-session` client behind it, and app.js deliberately lets Ctrl+B through to the terminal (readline, Claude Code's "ctrl+b ctrl+b"). With tmux's stock prefix table, Ctrl+B then `(` `)` `L` `s` `w` moved that client onto ANOTHER session, which the tab then showed and typed into under the original's label; `d` detached it, `$` renamed the session, `:` opened tmux's prompt. So the table is reduced to `<prefix> send-prefix` (the socket's configured prefix, read with `show-options -gv prefix`), once per tmux server in practice: the reset only runs while `list-keys -T prefix` shows anything else. A blank answer there is read from the full `list-keys` listing instead (its `-T prefix` lines only): tmux 3.7 through 3.7c (tmux commit 09bd686327, fixed in 3.8 by 7ec94fda08) print nothing on stdout for `list-keys -T <table>` when the table holds exactly one binding (the line goes to a status message instead), which is the reduced shape, so the reduced table read as needing a reset on every call. `codeman tui` reads its key tables the same way (`listKeyTable` in `src/tui/tui-client.ts`), or a bound key there reads as free. The same reduction is applied when Codeman creates the nested tmux behind a Docker case (`-L codeman-docker`) or an owned remote session (`-L codeman-remote`). Those servers set `prefix C-q` and used to keep tmux's stock prefix table, so inside the pane Ctrl+Q then `)` `(` `s` `w` or `L` ran `switch-client` / `choose-tree` on the inner server and moved its client onto a sibling session. `nestedPrefixTableResetCommands()` (bind `C-q send-prefix`, then `unbind-key -a -T prefix`, then bind it again, so a user config that left the prefix table empty cannot make `unbind-key -a` abort the `\;` chain) is appended to both create chains, before `remain-on-exit failed` on the remote chain so a remote tmux that rejects `failed` cannot drop it. Those sockets are dedicated to Codeman, so the server-global table is the right scope. A non-owned remote attach joins another Codeman's `-L codeman` and does not run it. ⚠️ Keep `send-prefix`: Claude Code inside tmux backgrounds a command with "ctrl+b ctrl+b". ⚠️ Never touch the `root` table, and tolerate (and re-bind after a reset) `C-<letter> detach-client`: `codeman tui`'s attach claims F1 and Alt+1..9 in `root` and the held-Ctrl alias `C-d` in `prefix` (`beginAttachHandoff`), and a session created mid-attach must not take that way out away. ⚠️ Key tables are server-wide. F1 and the held-Ctrl `C-d` still detach every client for the length of an attach (a way out, not a session move). **`M-1`..`M-9` do not move other clients.** `bindSwitchKey` binds them to `if-shell -F` (`tuiSwitchGuard`) so `switch-client` runs only when `#{client_tty}` is the TUI's terminal and `#{client_pid}` equals `@codeman-tui-pid`. A one-shot `client-attached[90]` hook (`tuiSwitchAttachHook`) sets that option as the TUI's client attaches, then removes itself. It is armed as the handoff's last tmux call before `spawnSync`, after the keys and the per-session bars, so only a TUI killed during the attach's own startup can leave that hook armed for its tty. A browser tab does not match, including Esc followed by a digit within `escape-time` (500 ms on tmux 3.4), which arrives as the same `M-<digit>`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-<digit>`, which writes Esc and the digit into that client's own pane, so a vim `<Esc>2j` in a browser tab is not eaten by the root binding. If the TUI is killed before `restore()`, the binding can remain, but the stored pid is the dead client and the hook will not re-arm a pty that reuses the number, so the key never switches and every client gets it in its pane through the else branch. `restore()` removes the keys only while they still name this tty, and the next attach that claims the strip releases any of these bindings first. A second TUI attach replaces the keys (one binding per key). Escape-time on Codeman's socket stays at tmux's default: lowering it would change Esc delivery for every pane, and the guard already refuses other clients. ⚠️ The consequence for every terminal attach: `Ctrl+B d` does not exist on this socket. Anything that attaches a user's terminal claims its own way out for the attach, as `beginAttachHandoff` and `scripts/tmux-manager.sh` (F1 in `root`) do, and never advertises tmux's stock chord. Tests: `test/tmux-prefix-table.test.ts` (real tmux on a private socket, driven through a pty attach client, including the nested `C-q` table), `test/tui/tui-switch-guard.test.ts` (the guarded Alt keys against a second client),Line truncated
**Browser tabs are tmux clients, so tmux's prefix table must not reach `switch-client`** (`src/tmux-prefix-table.ts`, called from `createSession` before `respawn-pane`, and from `reconcileSessions()` at boot whenever the socket lists a pane, so sessions that survived an upgrade are covered). Every keystroke typed into a browser terminal reaches the `tmux attach-session` client behind it, and app.js deliberately lets Ctrl+B through to the terminal (readline, Claude Code's "ctrl+b ctrl+b"). With tmux's stock prefix table, Ctrl+B then `(` `)` `L` `s` `w` moved that client onto ANOTHER session, which the tab then showed and typed into under the original's label; `d` detached it, `$` renamed the session, `:` opened tmux's prompt. So the table is reduced to `<prefix> send-prefix` (the socket's configured prefix, read with `show-options -gv prefix`), once per tmux server in practice: the reset only runs while `list-keys -T prefix` shows anything else. The same reduction is applied when Codeman creates the nested tmux behind a Docker case (`-L codeman-docker`) or an owned remote session (`-L codeman-remote`). Those servers set `prefix C-q` and used to keep tmux's stock prefix table, so inside the pane Ctrl+Q then `)` `(` `s` `w` or `L` ran `switch-client` / `choose-tree` on the inner server and moved its client onto a sibling session. `nestedPrefixTableResetCommands()` (bind `C-q send-prefix`, then `unbind-key -a -T prefix`, then bind it again, so a user config that left the prefix table empty cannot make `unbind-key -a` abort the `\;` chain) is appended to both create chains, before `remain-on-exit failed` on the remote chain so a remote tmux that rejects `failed` cannot drop it. Those sockets are dedicated to Codeman, so the server-global table is the right scope. A non-owned remote attach joins another Codeman's `-L codeman` and does not run it. ⚠️ Keep `send-prefix`: Claude Code inside tmux backgrounds a command with "ctrl+b ctrl+b". ⚠️ Never touch the `root` table, and tolerate (and re-bind after a reset) `C-<letter> detach-client`: `codeman tui`'s attach claims F1 and Alt+1..9 in `root` and the held-Ctrl alias `C-d` in `prefix` (`beginAttachHandoff`), and a session created mid-attach must not take that way out away. ⚠️ Key tables are server-wide. F1 and the held-Ctrl `C-d` still detach every client for the length of an attach (a way out, not a session move). **`M-1`..`M-9` do not move other clients.** `bindSwitchKey` binds them to `if-shell -F` (`tuiSwitchGuard`) so `switch-client` runs only when `#{client_tty}` is the TUI's terminal and `#{client_pid}` equals `@codeman-tui-pid`. A one-shot `client-attached[90]` hook (`tuiSwitchAttachHook`) sets that option as the TUI's client attaches, then removes itself. It is armed as the handoff's last tmux call before `spawnSync`, after the keys and the per-session bars, so only a TUI killed during the attach's own startup can leave that hook armed for its tty. A browser tab does not match, including Esc followed by a digit within `escape-time` (500 ms on tmux 3.4), which arrives as the same `M-<digit>`. A client that fails the guard gets the key back: the `if-shell` else argument is `send-keys M-<digit>`, which writes Esc and the digit into that client's own pane, so a vim `<Esc>2j` in a browser tab is not eaten by the root binding. If the TUI is killed before `restore()`, the binding can remain, but the stored pid is the dead client and the hook will not re-arm a pty that reuses the number, so the key never switches and every client gets it in its pane through the else branch. `restore()` removes the keys only while they still name this tty, and the next attach that claims the strip releases any of these bindings first. A second TUI attach replaces the keys (one binding per key). Escape-time on Codeman's socket stays at tmux's default: lowering it would change Esc delivery for every pane, and the guard already refuses other clients. ⚠️ The consequence for every terminal attach: `Ctrl+B d` does not exist on this socket. Anything that attaches a user's terminal claims its own way out for the attach, as `beginAttachHandoff` and `scripts/tmux-manager.sh` (F1 in `root`) do, and never advertises tmux's stock chord. Tests: `test/tmux-prefix-table.test.ts` (real tmux on a private socket, driven through a pty attach client, including the nested `C-q` table), `test/tui/tui-switch-guard.test.ts` (the guarded Alt keys against a second client), the wiring in `test/tmux-manager.test.ts`, the script in `test/tmux-manager-script-attach.test.ts`.
### 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 `<Mode>Config` wire field is a separate namespace, bridged only by `launch.legacyConfigAliases`. Getting `privilegedParams[].param` wrong is SILENT — it is the multi-user bypass clamp's only handle on a CLI's privilege switch, and a wrong name clamps nothing with no load error and no failing test — so `schema.ts` rejects an entry naming a param it never declared. Codex is the entry where the two names differ (`bypassApprovals` vs `dangerouslyBypassApprovals`) and therefore the one that catches a regression.
⚠️ 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.)
⚠️ 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.)
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 `<prefix>: <title>` form (`w3-myapp: fix the login redirect`
⚠️ **What a mouse-DECSET strip (full or mouse) removes, it must REMEMBER.** Stripping the mouse DECSETs means xterm's `modes.mouseTrackingMode` is permanently `'none'` for those modes, so the browser hand-encodes click reports to compensate (`_sendSyntheticSgrTap`). With no state to consult it did that on EVERY click, which delivered mouse reports to programs that never asked for them: the same pane runs a plain shell whenever the CLI has exited or a `shell` was started inside a claude-mode session, and a shell prints the report as literal text (`[<0;88;20M`), garbling the next line typed. `_recordStrippedMouseMode()` therefore records each stripped sequence as it goes and publishes `cliMouseTracking` through `toState()`, and `_shouldReportMouseToCli()` requires it. ⚠️ Only the TRACKING modes count (1000/1001/1002/1003): 1005/1006 select an ENCODING and 1007 is alt-scroll, and counting those would put the stray reports straight back. ⚠️ The change broadcasts IMMEDIATELY rather than through `broadcastSessionStateDebounced`, because the flag flips when a dialog opens and the user can click that dialog inside the 500ms debounce window. Measured on a live claude 2.x: the CLI holds a tracking mode on continuously in fullscreen (so clicks keep being reported exactly as before; the default inline renderer holds none, measured on 2.1.283 even with `/model` open), while a bash prompt in the same stripped mode reports nothing. Fails toward silence: after a server restart the flag is false until the CLI re-emits, which tmux does at client attach.
**Wheel forwarding requires observed mouse tracking: Claude ≥ 2.1.187, tracked Codex, tracked Copilot or tracked Pi** (`terminal-ui.js:_shouldForwardWheelToApp`). The original #227 measurement remains valid for **Codex 0.147.0 inline**: `alternate_on=0`, `mouse_any_flag=0`, growing tmux history, and SGR wheel reports do nothing. Claude 2.1.280 inline similarly reports `alternate_on=0`, `mouse_any_flag=0`; forwarding there swallows gestures, so it keeps local scrollback. Fullscreen Claude (`CLAUDE_CODE_NO_FLICKER=1` or `"tui": "fullscreen"`) enables mouse tracking and accepts reports. **Fresh Codex 0.163.0 fullscreen measurement (2026-10-18, isolated local tmux pane)**: `alternate_on=1`, `mouse_any_flag=1`; one `\x1b[<64;10;10M` report moves the transcript one row upward, and `\x1b[<65;10;10M` restores the original screen. This is capability evidence, not a minimum-version promise: untracked Codex (including a 0.162.0 measurement (2026-10) with `mouse_any_flag=0`) keeps local history or the hollow-pane paging fallback. Codex does not publish the Claude-only CLI version field, so its gate requires the observed flag rather than a Claude version. The registry records this as `wheelForward.mode: 'always'` (observed mouse tracking is still required); Claude remains `version-gated`. 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.
**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.
**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,8 +682,6 @@ 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×.
@@ -1141,9 +1139,7 @@ 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, 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`.
**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.
**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.
@@ -1273,7 +1269,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 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.
⚠️ **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.
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.
@@ -1303,8 +1299,6 @@ 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`.
@@ -1555,7 +1549,3 @@ 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.
+1 -5
View File
@@ -300,7 +300,7 @@ This matters because it is invisible when it is wrong. `capabilities.privilegedP
## Fields declared for later
`accent`, `capabilities.echo`, `capabilities.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.
`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.
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,10 +308,6 @@ Treat those values as **transcribed, not authoritative** — nothing enforces th
Everything else in the interface is live, including `overlays.remote` / `overlays.docker`, which back `defaultRemoteCommandForMode()` and `defaultDockerCommandForMode()` directly. Those two used to be hardcoded `Record<…CommandMode, string>` tables duplicating the registry with nothing keeping the two in step; `test/location-overlay-commands.test.ts` pins every resulting command as a literal string.
### Wheel forwarding for a custom full-screen CLI
`capabilities.wheelForward` reaches the browser as `window.__codemanWheelForward` (id to rule, every CLI whose mode is not `never`, disabled ones included, since disabling a CLI leaves its running sessions open), and `_shouldForwardWheelToApp` in terminal-ui.js reads only that map, so a custom entry gets the same wheel as a stock one under its own id. A full-screen TUI that turns mouse tracking on itself (a wrapper around pi, for example) needs two values in its `clis.json` entry, the ones stock pi carries: `"altScreen": "strip-mux-and-mouse"` (the server strips its mouse DECSETs and publishes `cliMouseTracking`, and a drag selects locally) and `"wheelForward": { "mode": "always" }` (the wheel goes to the CLI as SGR reports while that flag is on). With the custom-entry defaults (`strip-mux-only`, `never`) the DECSETs reach xterm, which handles the wheel only until a tab switch or reload replays the pane without them; from then on the wheel scrolls an empty local buffer. Use `always` rather than `version-gated` for such an entry: a `version-gated` rule forwards only when the session has a `cliVersion`, and the server probes one only for an entry that declares `capabilities.gates` (`cliNeedsVersionProbe` in `session.ts`), so a custom entry with `version-gated` and no gates never forwards, and nothing says why. ⚠️ Saving the entry from the Settings form rebuilds its capabilities from those defaults, so both values have to be set again in the file after an edit there.
## Consumers outside the server
Two things need the catalogue but cannot import TypeScript, so `npm run generate:cli-catalog`
-33
View File
@@ -288,39 +288,6 @@ dsh fences its `/api` behind a browser-trust check on the request authority, and
Codeman web tab reaches it through Codeman's own origin via the webview proxy, not
directly. Without it the page renders and every API call fails.
Since dsh's browser-auth gate, the index is not public either: boot prints
`dsh web: http://127.0.0.1:<port>/?token=<one-time token>` and only a request
carrying that token is answered with the `dsh-auth-*` cookie that authorizes
everything after it. The saved tab deliberately keeps the clean URL, so the
browser can never present that token, and the tab used to open on dsh's 401 page.
`src/deepseek-web-server.ts` now reads the token out of the captured boot output,
trades it for the cookie once at startup, and `webview-routes.ts` presents that
cookie on both the HTTP and WebSocket legs — scoped to the exact loopback
authority it was minted for, so a repointed or stale tab cannot carry it
elsewhere. The reader scans every `dsh web:` line (dsh prints diagnostics such as
`dsh web: loading profiles` under the same prefix before the banner) and only
complete lines, so a banner split across two output chunks is waited for rather
than parsed truncated. Before the token URL is fetched it must name `127.0.0.1`
on the port the supervisor just spawned, so a banner cannot aim the server-side
request at another host or local service. A dsh without the gate prints a
token-less banner and keeps working unchanged. If a token is printed but the
exchange still fails, the server keeps running (its page serves, just 401) and is
marked unusable for reuse: the next start request stops and respawns it, which is
the "restart `dsh web`" the warning asks the user to perform.
The cookie is also bound to a person, not to a URL. `managed` is accepted from the
client on `POST/PATCH /api/webviews` and `GET /api/deepseek/web` publishes the live
port, so a saved record pointing at that port is not an entitlement by itself: the
proxy presents the cookie only when the tab's owner holds the same
privileged-commands grant `POST /api/deepseek/web` requires, and in multi-user mode
only to the owner whose request started that process. A different owner's start
request restarts the server rather than reusing a cookie that is not theirs, which
is why the shared instance is effectively single-user at a time. On a trusted
managed tab the cookie is sent ahead of whatever cookies dsh itself set in the
browser, rather than replacing them; leading matters because a `Cookie` header can
name the same cookie twice and the first value is the one the dashboard parses, so
a stale browser copy must not shadow the one the running process minted.
## 7. Docker and remote cases
Docker cases work: the agent image installs `dsh` and bootstraps a `dsh-tui`
-6
View File
@@ -135,9 +135,3 @@ 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.
-10
View File
@@ -18,7 +18,6 @@ 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.
@@ -85,15 +84,6 @@ 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:
+2 -24
View File
@@ -144,21 +144,9 @@ 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. 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.
1. `<base href>` handles relative URLs in the markup.
2. Attribute rewriting handles root-absolute `src`/`href`/`action` in the page the
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.
proxy serves.
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
@@ -202,16 +190,6 @@ then every API call fails, which looks like the dashboard being broken.
EventSource, normal markup, the DOM sinks a page uses to build markup at runtime,
and `url()` inside stylesheets. Something that constructs requests by an unusual
route can still slip through. Symptom: the page renders but a panel stays empty.
- **Root-absolute URLs the proxy never sees.** Only the HTML is rewritten, and only
literal `/`-rooted specifiers in it. Still escape: an `import()` built at runtime
(`import('/' + name)`), an import written inside an external `.js`, a static
`import x from "/x"` in an inline script, `navigator.serviceWorker.register("/sw.js")`,
and `url(/img.png)` inside an external stylesheet. They cannot be relayed either —
the masked frame's `Referer` carries no capability — so the failure is quiet: a
blank page, or a spinner that never resolves. Codeman now logs
`[Webview] <path> escaped the proxy` (once per path per five minutes) when such a
request reaches its 404, which is the fastest way to tell this class apart from a
dashboard that is genuinely broken.
- **A root-absolute `url()` inside an inline `<style>` is not rescued.** Masking the
page's URL (layer 5) trades away the `Referer` safety net of layer 4 for
requests the shim cannot see, and only HTML is rewritten server-side. An
-16
View File
@@ -67,22 +67,6 @@ 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
-1
View File
@@ -255,7 +255,6 @@ works well in SSH clients like Termius or Blink:
```bash
codeman tui # the dashboard
codeman tui 2 # attach straight to session 2
codeman tui api-docs # attach to the live session named api-docs
codeman tui --list # numbered list, then exit
```
-1
View File
@@ -48,7 +48,6 @@ 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. |
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "aicodeman",
"version": "1.51.1",
"version": "1.51.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "aicodeman",
"version": "1.51.1",
"version": "1.51.0",
"hasInstallScript": true,
"license": "MIT",
"workspaces": [
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "aicodeman",
"version": "1.51.1",
"version": "1.51.0",
"description": "Self-hosted mission control for AI coding agents: run Claude Code, Codex, OpenCode, Gemini, DeepSeek, Grok and more 24/7 in tmux, from any device.",
"mcpName": "io.github.Ark0N/codeman",
"type": "module",
+6 -2
View File
@@ -35,8 +35,8 @@ security-framework = "3"
# Ignoring signals in the logo blinker (src/logo.rs). Already in the tree
# through wry and tao, so no new crate is added.
libc = "0.2"
# JavaScript dialogs, HTTP Basic challenges, clearing cookies and the window's
# content size (src/macos.rs). The versions wry already pulls in, so no new
# JavaScript dialogs, HTTP Basic challenges, clearing one server's cookies and
# the window's content size (src/macos.rs). The versions wry already pulls in, so no new
# crate is added.
objc2 = { version = "0.6.5", default-features = false, features = ["std"] }
block2 = { version = "0.6.2", default-features = false, features = ["std"] }
@@ -44,10 +44,12 @@ objc2-foundation = { version = "0.3.2", default-features = false, features = [
"std",
"objc2-core-foundation",
"block2",
"NSArray",
"NSBundle",
"NSDate",
"NSDictionary",
"NSGeometry",
"NSHTTPCookie",
"NSObject",
"NSOperation",
"NSProcessInfo",
@@ -61,6 +63,7 @@ objc2-foundation = { version = "0.3.2", default-features = false, features = [
"NSURLRequest",
"NSURLResponse",
"NSURLSession",
"NSUUID",
"NSValue",
] }
objc2-app-kit = { version = "0.3.2", default-features = false, features = [
@@ -80,6 +83,7 @@ objc2-web-kit = { version = "0.3.2", default-features = false, features = [
"block2",
"objc2-app-kit",
"WKFrameInfo",
"WKHTTPCookieStore",
"WKNavigationDelegate",
"WKSecurityOrigin",
"WKUIDelegate",
+38 -9
View File
@@ -3,7 +3,8 @@
A small native app that opens Codeman in its own window. Double-click it, and
it runs Codeman on this Mac (installing it first if it is not there) or
connects to Codeman on another machine (installing it there over SSH if
needed), and Codeman fills the window. `⌃⌘F` puts it in full screen.
needed), and Codeman fills the window. Several servers open side by side as
tabs in the title bar, one click apart. `⌃⌘F` puts it in full screen.
macOS first: the app runs on 11.3 or later, and Codeman's own page needs the
WebKit of Safari 16.4 (see Known limits). The same code is meant to build for
@@ -28,20 +29,21 @@ cannot do.
| | |
| --- | --- |
| **Server tabs** | One tab per Codeman server, in a strip that takes the place of the title bar (the traffic lights sit at its left end, so the strip costs about 10 points over a plain title bar and stays in full screen). A click switches tabs, and every tab stays loaded, so a switch is instant: no reload, no new login. Each tab shows what its server's agents do: a red count for sessions that need a permission or an answer, an amber dot when one finished and waits for you, a blue ring while agents work, a dashed circle when the server does not answer. The app reads that itself from each server every two seconds (`api/sessions` and `api/approvals`, the reader the Apple logo uses), because WebKit stalls a hidden page. Each tab has a colour of its own, as a stripe on the tab in front, so you do not type into the wrong machine. `+` (or `⌘T`) opens the connect screen in a new tab; a server that is already open in a tab is not opened twice, its tab comes to the front instead. A double-click on a name, or **Rename Tab…** in the right-click menu, renames it; the right-click menu also picks the colour, reloads, connects the tab to another server and closes tabs. Drag a tab to reorder. Closing a tab only closes the window onto that server: its sessions keep running there, and `⇧⌘T` opens it again. The tabs of a server come back at the next launch, and connect by themselves when *Connect automatically when the app opens* is on. **All Servers** (`⌘0`, or the grid button left of the tabs) shows every server at once, the ones that need you first, with their sessions most urgent first; a click on a session opens its tab and selects it. |
| **This Mac** | The connect screen's first tab looks for Codeman on this Mac and offers what fits: *Open Codeman* when it runs, *Start Codeman* when it is installed but stopped, *Install Codeman on this Mac* when it is not there. The address comes from Codeman's LaunchAgent (port, sub-path, HTTPS). The tab also finds every Codeman server of yours that already runs on this Mac (with `ps` and `lsof`: a `codeman web --port 4000` in a terminal, a beta instance beside the installed one) and recommends connecting to it. Each one's address is worked out from its listening socket and its command line (`127.0.0.1` for a bind to loopback or to every interface, its own address for a bind to one, `https` with `--https`, the path of `--base-url`), and each is asked once whether Codeman answers there. When nothing answers at the usual address (the LaunchAgent's, or `http://127.0.0.1:3000` without one), *Open Codeman* is for the first found server that does; when none of them can be opened, the tab says *Codeman is already running on this Mac* and lists them. Next to a Codeman that answers, the others are listed under *Also running on this Mac*. A row shows the address, the version, and a *Connect* button, or the reason the app cannot open that one (HTTPS with Codeman's own certificate, no answer). *Connect* is the connect of the Another machine tab with that address filled in: the same check, the login saved for it, the same entry under recent servers. Finding a server connects to nothing by itself. The tab never offers to start a second server, which would take over the first one's sessions, and Start refuses while one runs. A server that runs but listens nowhere yet (the first seconds after login, a restart) shows as *starting*: the tab looks again every second and, when a connect to this Mac had just been refused, opens Codeman once it is up. Start asks launchd to run the LaunchAgent (`kickstart`, or `bootstrap` when it is not loaded), so the server keeps its own settings and supervision; without a LaunchAgent it runs `codeman web -d`. The login comes from where Codeman keeps it: the LaunchAgent's `CODEMAN_USERNAME`/`CODEMAN_PASSWORD`, else `~/.codeman/.env` (what Codeman's command-line clients read), `admin` by default. It goes only to `127.0.0.1` on that Codeman's port, only while one of your own Codeman processes holds that port, is never saved to the Keychain, and never reaches the page. Whether Codeman is installed is looked up in its files and processes, then the login shell; the interactive profile (nvm in `.zshrc`, say) only on *Check again*. Install sets Codeman up from the app itself, with no Terminal and no password (see Decisions). It fetches the installer, asks it what is on this Mac, then asks two things: which coding agent to install, only when this Mac has none (the list comes from the installer, and *Skip for now* is there), and who can reach Codeman (this Mac only, or the local network with a password). A checklist follows the install, the installer's output is one click away, and Cancel stops it; installing again picks up where it stopped. Codeman runs as a LaunchAgent, so it keeps running when the app quits and starts at login. Port 3000 is used unless something else answers there, then the next free one. Closing the app does not stop an install: it runs on its own, and the app picks it up when it opens again. When it is done the app looks every 3 seconds and opens Codeman as soon as it answers; it stops looking after the first answer, after 30 minutes, or 90 seconds after a finished install whose server never answered (then it offers Start). *Install in Terminal instead* runs the installer in a Terminal window, for what the app cannot do (see Known limits): it may ask for the Mac password (Homebrew) and asks its own questions there. The app offers it by itself on a Mac where the graphical install cannot finish. An install still running in Terminal is recognized by its process, so the tab waits for it instead of offering Install twice. *Add a coding agent*, on this tab and in the app menu whenever Codeman is on this Mac, is the same chooser after the install: pick one agent, watch it install, open Codeman. It needs no password, leaves a running Codeman alone, and can be cancelled or left running like an install. After *Skip for now* the app says Codeman has no agent yet and offers this before it opens Codeman. |
| **Another machine** | The second tab connects to a server by address (below). *Codeman is not installed there yet?* opens Terminal, connects with `ssh -t` and runs Codeman's installer on that machine, which asks its questions there; the app then suggests `http://<host>:3000` and the installer prints the real address at the end. The SSH login is checked to the characters of a user and host name (no option can be slipped in) and may carry a `:port`. The remote command runs under `bash -o pipefail`, so a failed download fails the install instead of reporting success. The same tab shows the one-line install command, with a Copy button, to run on a machine by hand. |
| **Connect screen** | Server address, recent servers, a login for password-protected servers (password kept in the macOS Keychain), auto-connect at launch. An address typed without `http://` or `https://` gets `http://`, except a tailnet name with no port (`machine.tailnet.ts.net`, which is `tailscale serve`), which gets `https://`. It explains each failure: nothing listening; wrong password; too many failed logins (the password field stays open, since a single-user Codeman accepts the right password even then); unknown host name; an address this Mac cannot reach (with a pointer to the Local Network setting); an `http://` address on a port that only speaks HTTPS; an untrusted certificate; a redirect, with a button for the suggested `https://` address; not a Codeman server. A multi-user account that must change its password connects, and Codeman's own dialog asks for the new one. If the server page has not started showing within 15 seconds, or you press Cancel while it opens, the connect screen comes back with a notice. A login that would cross the network over plain `http://` to another machine says so. Return opens or starts the Codeman on this Mac (or connects to the one found here, when that is the tab's main button) and Esc cancels a connect, as in a Mac dialog (Install always takes a click). On a Mac whose WebKit is too old for Codeman it says so and Connect stays off (see Known limits). |
| **Start Codeman** | On the This Mac tab, and when `http://127.0.0.1:<port>` or `http://localhost:<port>` answers nothing, one click runs `codeman web -d` (or `~/.codeman/app`) with your login shell's environment, so the server gets your real PATH (Homebrew, nvm) for the agents it spawns. zsh, bash and other POSIX shells run the start themselves; fish, nu, xonsh, tcsh and other shells only report their environment, and the start runs under `/bin/sh` with it. Offered for those two addresses only: `codeman web -d` listens on 127.0.0.1. |
| **Login** | The app answers the server's HTTP Basic login requests itself, with the login you connected with, so the page keeps working after the server restarts (a restart forgets every session cookie). It answers only for Codeman's own pages under the server's base path: a web tab or a rendered HTML file that asks for a Basic login of its own is left to WebKit and never gets your Codeman password. WebKit keeps no copy of the login, so every request for it gets the current one. Each connect first clears the app's cookies, so connecting to the same server as another user really switches users (local storage, where Codeman keeps its per-device settings, stays; a dashboard in a web tab that keeps its own login in a cookie may ask for it again). A page that still gets a 401 reloads once. If the server refuses the login (the password was changed, say), the app does not keep sending it: it checks it with a single probe, and only if the server refuses that too does the connect screen come back with a notice. That does not take focus from the app you are in: if Codeman is in the background, its Dock icon bounces. |
| **Login** | The app answers the server's HTTP Basic login requests itself, with the login you connected that tab with (each tab answers for its own server only), so the page keeps working after the server restarts (a restart forgets every session cookie). It answers only for Codeman's own pages under the server's base path: a web tab or a rendered HTML file that asks for a Basic login of its own is left to WebKit and never gets your Codeman password. WebKit keeps no copy of the login, so every request for it gets the current one. Each connect first clears that server's cookies, so connecting to the same server as another user really switches users (local storage, where Codeman keeps its per-device settings, stays; a dashboard in a web tab that keeps its own login in a cookie may ask for it again). On macOS 14 and later each server's pages keep their cookies and local storage in a data store of their own (see Decisions); before macOS 14 two servers on one machine (a Codeman on port 3000 and a beta on 5000) cannot be open in two tabs at once, since they would share one login cookie, and the app says so. A page that still gets a 401 reloads once. If the server refuses the login (the password was changed, say), the app does not keep sending it: it checks it with a single probe, and only if the server refuses that too does the connect screen come back with a notice. That does not take focus from the app you are in: if Codeman is in the background, its Dock icon bounces. |
| **Dialogs** | Codeman's `confirm()`, `prompt()` and `alert()` (Delete case, Kill all sessions, Update Codeman, discarding unsaved edits, ...) show as native macOS dialogs. wry implements none of them, and without them WKWebView answers Cancel without showing anything. Each dialog's first line names the page it comes from, and says so when that is an embedded frame (a web tab, a rendered HTML preview), so a frame cannot pass its text off as Codeman's. |
| **Full screen** | `⌃⌘F` or the green button. The last state is restored at launch; *Always Open in Full Screen* forces it. Leaving full screen returns to the saved window size and position. |
| **Menus** | A real Edit menu (without one, `⌘C`/`⌘V` do nothing in a WKWebView), Reload `⌘R`, Switch Server `⇧⌘O`, Developer Tools `⌥⌘I`. The page sees every key first, so Codeman's own shortcuts keep working. If the main window ends up showing a raw file instead of Codeman, `⌘R` takes it back to Codeman. |
| **Menus** | A real Edit menu (without one, `⌘C`/`⌘V` do nothing in a WKWebView), Reload `⌘R`, Developer Tools `⌥⌘I`, and a Server menu: New Server Tab `⌘T` (Switch Server `⇧⌘O` does the same), Close Tab `⌘W` (Close Window is `⇧⌘W`), Reopen Closed Tab `⇧⌘T`, Show All Servers `⌘0`, Show Previous and Next Tab `⇧⌘[` and `⇧⌘]`, and one item per tab, `⌘1` to `⌘8` (from nine tabs on, `⌘9` is the last one). `⌃Tab` and `⌥1` to `⌥9` stay Codeman's own (they switch sessions inside the server you are on). The page sees every key first, so Codeman's own shortcuts keep working. If the main window ends up showing a raw file instead of Codeman, `⌘R` takes it back to Codeman. |
| **Pop-outs** | Implements Codeman's existing native-wrapper bridge, `window.CodemanHost` (`openInHostWindow` in `src/web/public/app.js`), so popping out a session or a file preview opens a real app window, and the pop-out icon is on by default. Session and rendered-HTML pop-outs come only from Codeman's own pop-out button. A `window.open` from page script opens only Codeman's file and download windows, without taking keyboard focus, at most 3 at once and then 1 per second. Only Codeman's own pop-out pages become app windows (see Decisions); when the app refuses one, Codeman shows a toast. Each pop-out opens a step down and to the right of the window in use, never exactly on top of another one. A web tab's *Open in new tab* opens the dashboard in your default browser, as it would from a browser tab. |
| **Links** | On Codeman's own pages (the dashboard and session windows), a link to another site opens in your default browser, also on `⌘`-click or a middle click. Pages can send at most 3 links to the browser at once, then 1 per second. Inside a rendered HTML preview or a web tab, a plain link to another site does nothing, while one that asks for a new window (`target="_blank"`, `window.open`) opens in your default browser within the same budget (see Known limits). |
| **Downloads** | Codeman's Download links, and downloads Codeman opens in a new window, save the file to `~/Downloads` whatever its type, and a toast in Codeman names the file. Files the web view cannot display are saved the same way. |
| **A page that stops** | When the web content process of a window ends (a WebKit crash, or macOS taking the process back under memory pressure), the window loads its page again instead of staying blank. A second time within 30 seconds, the main window goes back to the connect screen and a pop-out closes, so a page that cannot stay up never becomes a reload loop. |
| **Apple logo** | On a MacBook Pro with a PROLED XDR display, the lit Apple logo on the lid says what the agents are doing. **View > Blink Apple Logo** is the one switch, off until you turn it on. The more the logo moves, the more it needs you: it breathes (a slow fade out and back in) while agents work, blinks every two seconds for a yellow tab and flashes three times, then rests, for a red one. Each state can take another style under **View > Apple Logo Blink Styles**: Off, Breathe, Calm, Slow, Wink, Heartbeat, Fast, or Alarm. Picking a style turns the switch on, and turning the switch on with every state off brings back the recommended three (Breathe, Calm, Alarm). When several states hold, the most urgent one with a style shows: red, then yellow, then work. Styles chosen in 1.50.0 are kept, with the switch on if any of them was. The menu only exists on a Mac with that logo. No password is needed. Shell tabs do not count. The app asks the server every two seconds, and a change has to hold for three seconds before the logo follows it, so an agent between two turns does not flicker it. It keeps working while the window is hidden, and with any Codeman server. The logo moves on its own hardware fades, the ones [LogoLight](https://github.com/Ark0N/LogoLight) uses, so a blink writes no setting, and a logo you switched off yourself stays off. LogoLight (1.3 or later) steps aside while Codeman shows its agents on the logo, and takes the logo back afterwards, with whatever it showed before; while an older LogoLight runs, Codeman leaves the logo to it. While the app is closed nothing blinks. With the lid closed it just goes on while the Mac stays awake on its power adapter (**Keep This Mac Awake > With the Lid Closed**, or an external display): macOS keeps the logo dark under a closed lid, so the app tells the logo the lid is open and the keyboard that it is closed, which stays dark, as LogoLight's *Lit with Lid Closed* does. The light sensor is covered then, so the logo glows as it would in a dark room. The line under **Apple Logo Blink Styles** says what the closed lid did last (blinking, or why not). On battery, and while the display only sleeps with the lid open, the blink pauses and writes nothing. |
| **Keep awake** | **Codeman > Keep This Mac Awake** keeps the Mac from going to sleep while Codeman's agents work on it: **While Agents Work** (an agent at work, and for 5 minutes after the last one stopped, so the gap between two turns or a reply from your phone does not let it drop off), or **Always** (while the app is open). Off until you choose. Only for a Codeman on this Mac (`127.0.0.1`, `localhost`, or one of this Mac's own addresses); for a server on another machine the menu says so. The display still sleeps. No password is needed anywhere: the app holds a power assertion of its own, which macOS shows in Activity Monitor and in `pmset -g assertions` as *Codeman keeps this Mac awake while its agents work*, and which ends with the app, a crash or a Force Quit included. On a MacBook, **Only When Plugged In** (on by default) pauses it on battery, and **With the Lid Closed** keeps a closed MacBook awake as well: while it holds, the app has macOS's sleep-on-lid-close turned off (see Decisions), and turns it back on when it lets go, quits or crashes. The lid is never kept awake on battery, whatever the settings: unplugged with the lid closed, the Mac goes to sleep. A line at the bottom of the menu says what it does right now: whether the lid is covered, that it is left to macOS while an external display is connected (a docked MacBook stays awake with its lid closed by macOS's own doing), and if the Mac slept under the lid all the same, until when. Codeman 1.50.1 kept the lid awake through a small root helper, behind the administrator password. Nothing uses that helper any more, and where it is still installed the menu has **Remove the Old Lid Helper…** (the one item that asks for the password). It lives in the app, so it ends when the app quits: Codeman keeps running as a LaunchAgent, but nothing keeps the Mac awake then. That is why, while it watches a Codeman on this Mac, closing the Codeman window hides the app instead of quitting it, as Cmd+H does, also while it is paused (on battery, say), since it carries on by itself: a click on its Dock icon brings it back, and only Cmd+Q (or Quit from the Dock) ends it. With no server open, or one on another machine, closing the window quits. |
| **Apple logo** | On a MacBook Pro with a PROLED XDR display, the lit Apple logo on the lid says what the agents are doing. **View > Blink Apple Logo** is the one switch, off until you turn it on. The more the logo moves, the more it needs you: it breathes (a slow fade out and back in) while agents work, blinks every two seconds for a yellow tab and flashes three times, then rests, for a red one. Each state can take another style under **View > Apple Logo Blink Styles**: Off, Breathe, Calm, Slow, Wink, Heartbeat, Fast, or Alarm. Picking a style turns the switch on, and turning the switch on with every state off brings back the recommended three (Breathe, Calm, Alarm). When several states hold, the most urgent one with a style shows: red, then yellow, then work. Styles chosen in 1.50.0 are kept, with the switch on if any of them was. The menu only exists on a Mac with that logo. No password is needed. Shell tabs do not count. The app asks the server every two seconds, and a change has to hold for three seconds before the logo follows it, so an agent between two turns does not flicker it. It keeps working while the window is hidden, and with any Codeman server: with several tabs open it shows the most urgent state of all of them together, so a red tab on any server flashes it. The logo moves on its own hardware fades, the ones [LogoLight](https://github.com/Ark0N/LogoLight) uses, so a blink writes no setting, and a logo you switched off yourself stays off. LogoLight (1.3 or later) steps aside while Codeman shows its agents on the logo, and takes the logo back afterwards, with whatever it showed before; while an older LogoLight runs, Codeman leaves the logo to it. While the app is closed nothing blinks. With the lid closed it just goes on while the Mac stays awake on its power adapter (**Keep This Mac Awake > With the Lid Closed**, or an external display): macOS keeps the logo dark under a closed lid, so the app tells the logo the lid is open and the keyboard that it is closed, which stays dark, as LogoLight's *Lit with Lid Closed* does. The light sensor is covered then, so the logo glows as it would in a dark room. The line under **Apple Logo Blink Styles** says what the closed lid did last (blinking, or why not). On battery, and while the display only sleeps with the lid open, the blink pauses and writes nothing. |
| **Keep awake** | **Codeman > Keep This Mac Awake** keeps the Mac from going to sleep while Codeman's agents work on it: **While Agents Work** (an agent at work, and for 5 minutes after the last one stopped, so the gap between two turns or a reply from your phone does not let it drop off), or **Always** (while the app is open). Off until you choose. It watches the Codeman on this Mac among the open tabs (the tab in front when that is one). Only for a Codeman on this Mac (`127.0.0.1`, `localhost`, or one of this Mac's own addresses); for a server on another machine the menu says so. The display still sleeps. No password is needed anywhere: the app holds a power assertion of its own, which macOS shows in Activity Monitor and in `pmset -g assertions` as *Codeman keeps this Mac awake while its agents work*, and which ends with the app, a crash or a Force Quit included. On a MacBook, **Only When Plugged In** (on by default) pauses it on battery, and **With the Lid Closed** keeps a closed MacBook awake as well: while it holds, the app has macOS's sleep-on-lid-close turned off (see Decisions), and turns it back on when it lets go, quits or crashes. The lid is never kept awake on battery, whatever the settings: unplugged with the lid closed, the Mac goes to sleep. A line at the bottom of the menu says what it does right now: whether the lid is covered, that it is left to macOS while an external display is connected (a docked MacBook stays awake with its lid closed by macOS's own doing), and if the Mac slept under the lid all the same, until when. Codeman 1.50.1 kept the lid awake through a small root helper, behind the administrator password. Nothing uses that helper any more, and where it is still installed the menu has **Remove the Old Lid Helper…** (the one item that asks for the password). It lives in the app, so it ends when the app quits: Codeman keeps running as a LaunchAgent, but nothing keeps the Mac awake then. That is why, while it watches a Codeman on this Mac, closing the Codeman window hides the app instead of quitting it, as Cmd+H does, also while it is paused (on battery, say), since it carries on by itself: a click on its Dock icon brings it back, and only Cmd+Q (or Quit from the Dock) ends it. With no server open, or one on another machine, closing the window quits. |
| **Window** | Size, position and full-screen state are remembered. A saved window that hangs off the screen it opens on (it was last on a larger display that is gone, say) is pulled back on and shrunk to fit; one whose title bar is on no screen at all opens at the default size instead. Clicking the Dock icon brings back a minimized window. |
## Build (on a Mac)
@@ -73,7 +75,8 @@ the macOS version in `macos/Info.plist` (`LSMinimumSystemVersion`, 11.3), and
takes the binary from where cargo says it wrote it, so `CARGO_TARGET_DIR` and a
cargo config's `build.target-dir` work.
Settings live in `~/Library/Application Support/Codeman/desktop.json`; passwords
Settings live in `~/Library/Application Support/Codeman/desktop.json` (with the
tabs to open again: their servers, names, colours and which was in front); passwords
in the Keychain under *Codeman Desktop*, one item per username and server. A
`desktop.json` the app cannot read or parse is moved aside, never overwritten:
to `desktop.json.corrupt`, or to the first free name of `desktop.json.corrupt.1`
@@ -99,6 +102,29 @@ the page logged in. Using the crates directly is also smaller.
the JavaScript dialog methods and the authentication-challenge method to the
classes of wry's own delegates, so wry stays an unmodified crates.io dependency.
**One window, a web view per tab.** The tab strip (`assets/tabs.html`) is a
web view of its own across the top of the window, and each tab's pages sit
below it, the one in front visible and the others hidden but loaded
(`src/tabs.rs` holds the pure half: names, colours, order, the state the strip
and the overview are sent). A tab shows the connect page until its server's
page commits: that page loads in a second, hidden web view behind it, so the
connect page keeps its status line and Cancel while the server loads, and the
load can be abandoned without a blank tab. The strip and the overview listen to
their own page only (`policy::parse_strip_ipc`, `parse_overview_ipc`) and
navigate nowhere else, and a session id from the overview goes into Codeman's
page only when it is made of the characters Codeman's ids are.
**A data store per server.** Codeman's login cookie has the same name on every
port, and cookies are not told apart by port, so two servers on one machine in
one store would keep logging each other out. On macOS 14 and later each
server's pages (its tab and its pop-outs) use a WebKit data store of their own,
named by a hash of the server's address (`tabs::store_id`), so it is the same
store at every launch. The one exception is the server used last before tabs
existed: it keeps WebKit's default store, and with it the local storage where
Codeman keeps its per-device settings (every other server starts those afresh
once). Before a connect only that server's cookies are removed from its store,
never another tab's.
**What a page may ask of the app** (all in `src/policy.rs`, unit-tested):
- Codeman shows content it did not write on its own origin: rendered HTML files
@@ -136,8 +162,11 @@ classes of wry's own delegates, so wry stays an unmodified crates.io dependency.
relay 401s from content Codeman did not write. Only such a challenge can
send the user back to the connect screen. WebKit is handed the login without
persistence, so it keeps no copy: every challenge gets the current login,
and one from before a Switch Server is never replayed.
- Each connect starts by clearing the app's cookies (never local storage).
and one from before another connect is never replayed. Each tab hands over
a login of its own, and a challenge goes to the tab whose server holds the
URL that got the 401 (the deepest base path, when two servers share an
origin behind one proxy), so one tab never answers for another.
- Each connect starts by clearing that server's cookies (never local storage).
Codeman checks its session cookie before the `Authorization` header, so an
earlier user's cookie would otherwise win over the new login.
- Microphone and camera requests prompt per page. wry's default without a
@@ -242,7 +271,7 @@ can write to the runtime folder. It asks `preflight` for the list like an instal
does, and both pass `--no-admin`: that flag decides which agents count as
installable, so without it on both the page could offer one the run refuses. The
menu item is on the connect page because that is where the app may run things:
from a Codeman page it leaves the page the way *Switch Server* does.
from a Codeman page it opens in a new tab, as New Server Tab does.
**Terminal stays for what the app cannot do.** The route with Homebrew asks for
the administrator password on a terminal, the Xcode tools arrive as a system
+13 -6
View File
@@ -1636,13 +1636,20 @@
els.fullscreen.checked = !!msg.startFullscreen;
els.version.textContent = 'Codeman Desktop ' + (msg.version || '');
renderRecent();
if (state.servers[0]) choose(state.servers[0]);
// A server tab opened again at launch names its server (target), and
// connects to it by itself when connectNow says so; any other tab
// shows the server used last.
var target = typeof msg.target === 'string' && msg.target ? msg.target : '';
var targeted = target ? (state.servers.filter(function (s) { return s.url === target; })[0] || { url: target }) : null;
var shown = targeted || state.servers[0];
if (shown) choose(shown);
var auto = !!(msg.autoConnect && !manual && !tooOld && !msg.starting && !msg.notice && state.servers[0]);
// The tab of the server used last; This Mac on a first run. An
// automatic connect opens Codeman without looking at this Mac first:
// that look runs a few processes and asks the server once more, and
// it is only needed when the connect fails, which then asks for it.
selectTab(state.servers[0] && !isLocalUrl(state.servers[0].url) ? 'remote' : 'local', auto);
if (targeted) auto = !!(msg.connectNow && !tooOld && !msg.starting && !msg.notice);
// The tab of that server; This Mac on a first run. An automatic
// connect opens Codeman without looking at this Mac first: that look
// runs a few processes and asks the server once more, and it is only
// needed when the connect fails, which then asks for it.
selectTab(shown && !isLocalUrl(shown.url) ? 'remote' : 'local', auto);
if (msg.starting) {
setBusy(true, false);
setStatus('busy', 'Starting Codeman on this Mac…', msg.notice || '');
+373
View File
@@ -0,0 +1,373 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>All servers</title>
<style>
/* All servers (Cmd+0): one card per server tab, what needs you first. The
native side sends the whole list, already ordered, on every change. */
:root { color-scheme: dark; }
* { box-sizing: border-box; }
html { min-height: 100%; background: #0b0c0f; }
body {
margin: 0; min-height: 100%; overflow-x: hidden; background: #0b0c0f; color: #e8eaed;
font: 13px/1.4 -apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, sans-serif;
-webkit-user-select: none; user-select: none; cursor: default;
}
main { padding: 22px 28px 28px; }
header { display: flex; align-items: baseline; flex-wrap: wrap; column-gap: 14px; row-gap: 4px; margin-bottom: 18px; }
h1 { margin: 0; font-size: 20px; font-weight: 650; letter-spacing: -0.01em; }
#summary { font-size: 13px; color: #8b9099; }
#summary .needs { color: #fca5a5; }
#summary .waiting { color: #fcd34d; }
#grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(300px, 100%), 1fr)); gap: 18px; align-items: stretch; }
button { font: inherit; color: inherit; margin: 0; cursor: pointer; -webkit-user-select: none; user-select: none; }
button:focus-visible { outline: 2px solid #3b82f6; outline-offset: 2px; }
.card {
--c: #94a3b8;
display: flex; flex-direction: column; min-width: 0; min-height: 236px; padding-top: 3px;
border: 1px solid #23252b; border-radius: 12px; background: #121316;
box-shadow: inset 0 3px 0 var(--c);
}
.card.urgent { border-color: rgba(248,113,113,0.45); }
.card.offline { border-style: dashed; border-color: #30333b; background: #0f1013; box-shadow: inset 0 3px 0 #30333b; }
.card.slim { min-height: 0; align-self: start; }
.head {
display: flex; align-items: flex-start; gap: 10px; width: 100%; padding: 11px 16px 10px;
border: 0; border-radius: 9px 9px 0 0; background: transparent; text-align: left;
}
.head:hover .name { text-decoration: underline; text-decoration-color: #3a3d45; text-underline-offset: 3px; }
.head:focus-visible { outline-offset: -2px; }
.title { flex: 1; min-width: 0; }
.name { display: block; font-size: 15px; font-weight: 650; line-height: 1.35; color: #e8eaed; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.card.offline .name { color: #8b9099; }
.url { display: block; margin-top: 2px; font-size: 12px; color: #8b9099; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.key { flex: none; padding-top: 2px; font-size: 12px; color: #6b7079; }
.body { flex: 1; min-height: 0; padding: 0 10px; }
.row {
display: flex; align-items: center; gap: 9px; width: 100%; padding: 7px 8px; margin: 0 0 3px;
border: 0; border-radius: 8px; background: transparent; font-size: 12.5px; line-height: 18px; text-align: left;
}
.row:hover { background: #1a1c21; }
.row.needs { background: rgba(248,113,113,0.10); }
.row.needs:hover { background: rgba(248,113,113,0.16); }
.row.waiting { background: rgba(251,191,36,0.07); }
.row.waiting:hover { background: rgba(251,191,36,0.12); }
.mark { flex: none; display: flex; align-items: center; justify-content: center; width: 18px; height: 18px; }
.mark::before { content: ""; display: block; }
.row.needs .mark { border-radius: 9px; background: #f87171; color: #2a0707; font-weight: 700; font-size: 11px; line-height: 18px; }
.row.needs .mark::before { display: none; }
.row.waiting .mark::before { width: 9px; height: 9px; border-radius: 50%; background: #fbbf24; }
.row.working .mark::before {
width: 11px; height: 11px; border-radius: 50%; border: 2px solid #60a5fa; border-right-color: transparent;
animation: spin 1s linear infinite;
}
.row.idle .mark::before { width: 8px; height: 8px; border-radius: 50%; background: #3a3d45; }
.sname { flex: 0 1 auto; min-width: 0; max-width: 55%; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.stext { flex: 1 1 0; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #8b9099; }
.row.needs .stext { color: #fca5a5; }
.row.waiting .stext { color: #fcd34d; }
.row.idle .stext { color: #6b7079; }
.more { padding: 3px 8px 0; font-size: 12px; color: #6b7079; }
.note { display: flex; align-items: center; gap: 9px; padding: 4px 6px; font-size: 12.5px; color: #8b9099; }
.note.warn { color: #fcd34d; }
.foot { display: flex; align-items: center; gap: 10px; margin-top: 10px; padding: 10px 16px 14px; border-top: 1px solid #1d1f24; }
.meta { flex: 1; min-width: 0; font-size: 12px; color: #6b7079; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.action {
flex: none; height: 28px; padding: 0 12px; border: 1px solid #30333b; border-radius: 7px;
background: #16181d; color: #e8eaed; font-weight: 600; font-size: 12px;
}
.action:hover { background: #1d2026; border-color: #3a3d45; }
.action.urgent { border-color: #ef4444; background: #ef4444; color: #ffffff; }
.action.urgent:hover { border-color: #dc2626; background: #dc2626; }
.add {
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px;
min-height: 236px; padding: 0; border: 1.5px dashed #30333b; border-radius: 12px;
background: transparent; color: #8b9099;
}
.add:hover { border-color: #3a3d45; color: #c9ccd2; }
.add-ico { width: 40px; height: 40px; border-radius: 12px; border: 1.5px dashed #3a3d45; display: flex; align-items: center; justify-content: center; }
.add-label { font-size: 13px; font-weight: 600; }
.add-key { font-size: 12px; color: #6b7079; }
.spin {
flex: none; width: 14px; height: 14px; border-radius: 50%;
border: 2px solid #30333b; border-top-color: #60a5fa; animation: spin 0.9s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) {
.row.working .mark::before, .spin { animation: none; }
}
</style>
</head>
<body>
<main>
<header>
<h1>All servers</h1>
<span id="summary"></span>
</header>
<div id="grid"></div>
</main>
<script>
(function () {
'use strict';
var FALLBACK_COLOR = '#94a3b8';
var COLOR_RE = /^#[0-9a-fA-F]{6}$/;
var MAX_ROWS = 4;
var STATES = ['needs', 'waiting', 'working', 'idle'];
var SVG_NS = 'http://www.w3.org/2000/svg';
var grid = document.getElementById('grid');
var summary = document.getElementById('summary');
function post(msg) { try { window.ipc.postMessage(JSON.stringify(msg)); } catch (e) { /* not in the app */ } }
// Names, URLs, versions and session texts come from servers: they are only
// ever set as text, and a colour only after it passed the #rrggbb check.
function str(v) { return typeof v === 'string' ? v : ''; }
function color(v) { return typeof v === 'string' && COLOR_RE.test(v) ? v : FALLBACK_COLOR; }
function count(v) {
var n = Math.floor(Number(v));
return isFinite(n) && n > 0 ? n : 0;
}
function shortcut(v) {
var n = Number(v);
return n >= 1 && n <= 9 && Math.floor(n) === n ? n : null;
}
function plural(n, one, many) { return n + ' ' + (n === 1 ? one : many); }
function normServer(s) {
if (!s || typeof s !== 'object') return null;
var tab = Number(s.tab);
if (!isFinite(tab)) return null;
var c = s.counts && typeof s.counts === 'object' ? s.counts : {};
var sessions = [];
(Array.isArray(s.sessions) ? s.sessions : []).forEach(function (x) {
if (!x || typeof x !== 'object') return;
sessions.push({
id: str(x.id),
name: str(x.name),
state: STATES.indexOf(x.state) >= 0 ? x.state : 'idle',
text: str(x.text)
});
});
return {
tab: tab,
name: str(s.name),
color: color(s.color),
url: str(s.url),
local: s.local === true,
key: shortcut(s.key),
version: str(s.version),
kind: s.kind === 'connect' || s.kind === 'loading' ? s.kind : 'server',
offline: s.offline === true,
refused: s.refused === true,
sessions: sessions,
counts: {
needsYou: count(c.needsYou),
waiting: count(c.waiting),
working: count(c.working),
sessions: count(c.sessions)
}
};
}
function el(tag, cls, text) {
var e = document.createElement(tag);
if (cls) e.className = cls;
if (text !== undefined) e.textContent = text;
return e;
}
function button(cls, focusKey, text) {
var b = el('button', cls, text);
b.type = 'button';
b.dataset.focus = focusKey;
return b;
}
function plusIcon(size) {
var s = document.createElementNS(SVG_NS, 'svg');
s.setAttribute('width', String(size));
s.setAttribute('height', String(size));
s.setAttribute('viewBox', '0 0 16 16');
s.setAttribute('fill', 'none');
s.setAttribute('stroke', 'currentColor');
s.setAttribute('stroke-width', '1.7');
s.setAttribute('aria-hidden', 'true');
var p = document.createElementNS(SVG_NS, 'path');
p.setAttribute('d', 'M8 2.5v11M2.5 8h11');
s.appendChild(p);
return s;
}
function renderSummary(servers) {
var needs = 0, waiting = 0, working = 0, offline = 0;
servers.forEach(function (s) {
if (s.offline) { offline++; return; }
needs += s.counts.needsYou;
waiting += s.counts.waiting;
working += s.counts.working;
});
var parts = [];
if (needs) parts.push(el('span', 'needs', needs + (needs === 1 ? ' needs you' : ' need you')));
if (waiting) parts.push(el('span', 'waiting', waiting + ' waiting'));
if (working) parts.push(el('span', 'working', working + ' working'));
if (offline) parts.push(el('span', 'offline', offline + ' offline'));
if (!parts.length) parts.push(el('span', 'calm', 'Nothing needs you'));
var out = [];
parts.forEach(function (p, i) {
if (i) out.push(document.createTextNode(' · '));
out.push(p);
});
summary.replaceChildren.apply(summary, out);
}
function sessionRow(s, x) {
var row = button('row ' + x.state, 'row:' + s.tab + ':' + x.id);
var mark = el('span', 'mark', x.state === 'needs' ? '!' : undefined);
mark.setAttribute('aria-hidden', 'true');
row.appendChild(mark);
row.appendChild(el('span', 'sname', x.name || 'Untitled'));
row.appendChild(el('span', 'stext', x.text));
var said = { needs: 'needs you', waiting: 'waiting', working: 'working', idle: 'idle' }[x.state];
row.setAttribute('aria-label', (x.name || 'Untitled') + ', ' + said + (x.text ? ': ' + x.text : ''));
if (x.id) row.addEventListener('click', function () { post({ cmd: 'openSession', tab: s.tab, session: x.id }); });
else row.disabled = true;
return row;
}
function card(s) {
var c = el('section', 'card');
c.style.setProperty('--c', s.color);
var name = s.name || (s.kind === 'connect' ? 'New server tab' : 'Untitled');
c.setAttribute('aria-label', name);
var head = button('head', 'head:' + s.tab);
var title = el('span', 'title');
title.appendChild(el('span', 'name', name));
if (s.url) title.appendChild(el('span', 'url', s.url));
head.appendChild(title);
if (s.key) head.appendChild(el('span', 'key', '⌘' + s.key));
head.addEventListener('click', function () { post({ cmd: 'open', tab: s.tab }); });
c.appendChild(head);
var body = el('div', 'body');
var meta = '';
var action = button('action', 'act:' + s.tab, 'Open');
var onAction = function () { post({ cmd: 'open', tab: s.tab }); };
if (s.kind === 'connect') {
c.classList.add('slim');
body.appendChild(el('div', 'note', 'Not connected yet'));
} else if (s.kind === 'loading') {
var note = el('div', 'note');
note.appendChild(el('span', 'spin'));
note.appendChild(document.createTextNode('Connecting…'));
body.appendChild(note);
} else if (s.offline) {
c.classList.add('offline');
body.appendChild(el('div', 'note', 'Not answering, the app keeps trying'));
meta = s.version;
action.textContent = 'Retry';
onAction = function () { post({ cmd: 'retry', tab: s.tab }); };
} else if (s.refused) {
body.appendChild(el('div', 'note warn', 'The login was refused'));
meta = s.version;
} else {
var shown = s.sessions.slice(0, MAX_ROWS);
shown.forEach(function (x) { body.appendChild(sessionRow(s, x)); });
var total = Math.max(s.counts.sessions, s.sessions.length);
if (total > shown.length) body.appendChild(el('div', 'more', '+' + (total - shown.length) + ' more'));
if (!total) body.appendChild(el('div', 'note', 'No sessions'));
meta = plural(total, 'session', 'sessions') + (s.version ? ' · ' + s.version : '');
if (s.counts.needsYou > 0) {
c.classList.add('urgent');
action.textContent = 'Answer';
action.classList.add('urgent');
// Answer goes straight to the first session that needs you, when the
// list names it; else to the server.
var first = s.sessions.filter(function (x) { return x.state === 'needs' && x.id; })[0];
if (first) onAction = function () { post({ cmd: 'openSession', tab: s.tab, session: first.id }); };
}
}
c.appendChild(body);
var foot = el('div', 'foot');
foot.appendChild(el('span', 'meta', meta));
action.setAttribute('aria-label', action.textContent + ' ' + name);
action.addEventListener('click', onAction);
foot.appendChild(action);
c.appendChild(foot);
return c;
}
function addCard() {
var b = button('add', 'new');
b.setAttribute('aria-label', 'Add a server');
var ico = el('span', 'add-ico');
ico.appendChild(plusIcon(16));
b.appendChild(ico);
b.appendChild(el('span', 'add-label', 'Add a server'));
b.appendChild(el('span', 'add-key', '⌘T'));
b.addEventListener('click', function () { post({ cmd: 'new' }); });
return b;
}
var lastJson = null;
function render(servers) {
// A state arrives every few seconds: the button that had the keyboard
// focus gets it back in the new cards.
var active = document.activeElement;
var focusKey = active && active.dataset ? active.dataset.focus : '';
renderSummary(servers);
var cards = servers.map(card);
cards.push(addCard());
grid.replaceChildren.apply(grid, cards);
if (focusKey) {
var all = grid.querySelectorAll('[data-focus]');
for (var i = 0; i < all.length; i++) {
if (all[i].dataset.focus === focusKey) { all[i].focus({ preventScroll: true }); break; }
}
}
}
function onNative(msg) {
if (typeof msg === 'string') {
try { msg = JSON.parse(msg); } catch (e) { return; }
}
if (!msg || typeof msg !== 'object' || msg.type !== 'state') return;
var servers = [];
var seen = new Set();
(Array.isArray(msg.servers) ? msg.servers : []).forEach(function (raw) {
var s = normServer(raw);
if (!s || seen.has(s.tab)) return;
seen.add(s.tab);
servers.push(s);
});
var json = JSON.stringify(servers);
if (json === lastJson) return;
lastJson = json;
render(servers);
}
Object.defineProperty(window, '__codemanOverview', {
value: Object.freeze({ onNative: onNative }),
writable: false,
configurable: false,
enumerable: false
});
render([]);
post({ cmd: 'ready' });
})();
</script>
</body>
</html>
+604
View File
@@ -0,0 +1,604 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Codeman tabs</title>
<style>
/* The tab strip: a 38px web view across the top of the window, under the
macOS traffic lights. One tab per Codeman server; the native side owns
the tabs and sends the whole list on every change. */
:root { color-scheme: dark; }
* { box-sizing: border-box; }
html, body { margin: 0; height: 100%; overflow: hidden; background: #141519; }
body {
font: 500 13px/1 -apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, sans-serif;
color: #a3a8b1; cursor: default;
-webkit-user-select: none; user-select: none;
}
#strip {
position: relative; height: 38px; display: flex; align-items: flex-end; gap: 4px;
padding: 0 8px 0 78px; overflow: hidden; background: #141519;
}
#strip.fullscreen { padding-left: 10px; }
/* The bottom line is drawn under the tabs, so the active tab covers it and
joins the page below. */
#strip::after {
content: ""; position: absolute; left: 0; right: 0; bottom: 0; height: 1px;
background: #23252b; pointer-events: none; z-index: 1;
}
.icon-btn {
align-self: center; flex: none; width: 28px; height: 28px; padding: 0; border: 0;
border-radius: 7px; background: transparent; color: #8b9099;
display: flex; align-items: center; justify-content: center; cursor: default; outline: none;
}
.icon-btn:hover { background: #1b1d22; color: #c9ccd2; }
#overview { margin-right: 6px; }
#overview.on { background: #2563eb; color: #ffffff; }
#new { margin-left: 2px; }
/* Empty strip moves the window, so some of it stays empty however many
tabs there are. */
#fill { flex: 1 0 48px; align-self: stretch; }
/* The tabs share the room evenly: 200px each, down to 72px; past that the
row is clipped, never wrapped or scrolled. */
#tabs {
display: flex; align-items: flex-end; gap: 2px; flex: 0 1 auto; min-width: 0;
height: 100%; overflow: hidden;
}
.tab {
--c: #94a3b8;
/* width, not only flex-basis: the row's own width is worked out from
its tabs' widths, and flex-basis does not count there. */
position: relative; flex: 0 1 auto; width: 200px; min-width: 72px; height: 31px;
display: flex; align-items: center; gap: 8px; padding: 0 7px 0 10px;
border-radius: 9px 9px 0 0; color: #a3a8b1; overflow: hidden;
}
.tab:hover { background: #1b1d22; }
/* A thin line between two tabs neither in front nor under the pointer, so a
badge at a tab's right end reads as that tab's and not the next one's. */
.tab + .tab::before {
content: ''; position: absolute; left: 0; top: 9px; bottom: 7px; width: 1px;
background: #2c2f37; pointer-events: none;
}
.tab.active::before, .tab.active + .tab::before,
.tab:hover::before, .tab:hover + .tab::before { display: none; }
.tab.active {
z-index: 2; background: #0b0c0f; color: #e8eaed;
box-shadow: inset 0 2px 0 var(--c), inset 1px 0 0 #23252b, inset -1px 0 0 #23252b;
}
/* The tab button itself is a transparent layer over the whole tab, so a
click anywhere on it is one target and the name, icon and badge stay
plain text for the screen reader's label. */
.hit {
position: absolute; inset: 0; z-index: 0; margin: 0; padding: 0; border: 0;
background: transparent; border-radius: inherit; cursor: default; outline: none;
}
.ico { flex: none; display: flex; color: var(--c); }
.tab.connect .ico { color: #60a5fa; }
.name { flex: 1 1 auto; min-width: 0; line-height: 16px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tab.offline .name { color: #6b7079; }
.tab.renaming .name { display: none; }
.rename {
position: relative; z-index: 1; flex: 1 1 auto; min-width: 0; height: 21px; margin: 0;
padding: 0 5px; border: 1px solid #3b82f6; border-radius: 5px; background: #0b0c0f;
color: #e8eaed; font: inherit; outline: none; -webkit-user-select: text; user-select: text;
}
.badge { flex: none; display: none; }
.badge.needs {
display: block; min-width: 18px; height: 18px; padding: 0 6px; border-radius: 9px;
background: #f87171; color: #2a0707; font: 700 11px/18px -apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, sans-serif;
text-align: center; font-variant-numeric: tabular-nums;
}
.badge.waiting { display: block; width: 9px; height: 9px; border-radius: 50%; background: #fbbf24; }
.badge.working {
display: block; width: 11px; height: 11px; border-radius: 50%;
border: 2px solid #60a5fa; border-right-color: transparent; animation: spin 1s linear infinite;
}
.badge.offline { display: block; width: 10px; height: 10px; border-radius: 50%; border: 1.5px dashed #6b7079; }
.spin {
display: block; width: 12px; height: 12px; margin: 1.5px; border-radius: 50%;
border: 2px solid #30333b; border-top-color: var(--c); animation: spin 0.9s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
.close {
position: relative; z-index: 1; flex: none; width: 16px; height: 16px; padding: 0; border: 0;
border-radius: 4px; background: transparent; color: #8b9099; cursor: default; outline: none;
display: none; align-items: center; justify-content: center;
}
.tab:hover .close, .tab.active .close { display: flex; }
.close:hover { background: #2a2d34; color: #e8eaed; }
/* Only while a tab is dragged do the others slide aside. */
#tabs.dragging .tab { transition: transform 150ms ease; }
#tabs.dragging .tab.lifted { transition: none; z-index: 3; background: #1b1d22; }
#tabs.dragging .tab.lifted.active { background: #0b0c0f; }
@media (prefers-reduced-motion: reduce) {
.badge.working, .spin { animation: none; }
#tabs.dragging .tab { transition: none; }
}
</style>
</head>
<body>
<div id="strip">
<button id="overview" class="icon-btn" type="button" tabindex="-1" aria-label="All servers" aria-pressed="false" title="All servers (⌘0)">
<svg width="15" height="15" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><rect x="1.5" y="1.5" width="5" height="5" rx="1.2"></rect><rect x="9.5" y="1.5" width="5" height="5" rx="1.2"></rect><rect x="1.5" y="9.5" width="5" height="5" rx="1.2"></rect><rect x="9.5" y="9.5" width="5" height="5" rx="1.2"></rect></svg>
</button>
<div id="tabs" role="tablist" aria-label="Servers"></div>
<button id="new" class="icon-btn" type="button" tabindex="-1" aria-label="New server tab" title="New server tab (⌘T)">
<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true"><path d="M8 2.5v11M2.5 8h11"></path></svg>
</button>
<div id="fill"></div>
</div>
<script>
(function () {
'use strict';
var FALLBACK_COLOR = '#94a3b8';
var COLOR_RE = /^#[0-9a-fA-F]{6}$/;
var MAX_NAME = 40;
var DRAG_START_PX = 4;
var SVG_NS = 'http://www.w3.org/2000/svg';
var strip = document.getElementById('strip');
var tabsEl = document.getElementById('tabs');
var overviewBtn = document.getElementById('overview');
var newBtn = document.getElementById('new');
function post(msg) { try { window.ipc.postMessage(JSON.stringify(msg)); } catch (e) { /* not in the app */ } }
// Everything below arrives from the native side, and most of it was typed
// on a server (names, URLs): it is only ever set as text or as a checked
// attribute value, never parsed as markup or CSS.
function str(v) { return typeof v === 'string' ? v : ''; }
function color(v) { return typeof v === 'string' && COLOR_RE.test(v) ? v : FALLBACK_COLOR; }
function count(v) {
var n = Math.floor(Number(v));
return isFinite(n) && n > 0 ? n : 0;
}
function shortcut(v) {
var n = Number(v);
return n >= 1 && n <= 9 && Math.floor(n) === n ? n : null;
}
function normTab(t) {
if (!t || typeof t !== 'object') return null;
var id = Number(t.id);
if (!isFinite(id)) return null;
var st = t.status && typeof t.status === 'object' ? t.status : {};
return {
id: id,
name: str(t.name),
color: color(t.color),
active: t.active === true,
kind: t.kind === 'connect' || t.kind === 'loading' ? t.kind : 'server',
local: t.local === true,
url: str(t.url),
key: shortcut(t.key),
needs: count(st.needsYou),
waiting: count(st.waiting),
working: count(st.working),
offline: st.offline === true
};
}
// One badge, by precedence: needs you, waiting, working, not answering.
function badgeOf(t) {
if (t.kind === 'connect') return '';
if (t.needs) return 'needs';
if (t.waiting) return 'waiting';
if (t.working) return 'working';
if (t.offline) return 'offline';
return '';
}
function statusWords(t) {
if (t.kind === 'loading') return ['Connecting'];
if (t.kind === 'connect') return [];
var out = [];
if (t.needs) out.push(t.needs + (t.needs === 1 ? ' needs you' : ' need you'));
if (t.waiting) out.push(t.waiting + ' waiting');
if (t.working) out.push(t.working + ' working');
if (t.offline) out.push('Not answering');
return out;
}
function displayName(t) { return t.name || 'Untitled'; }
// ---- icons (fixed shapes from this file; no outside text goes in) ----
function svg(size, width, parts) {
var s = document.createElementNS(SVG_NS, 'svg');
s.setAttribute('width', String(size));
s.setAttribute('height', String(size));
s.setAttribute('viewBox', '0 0 16 16');
s.setAttribute('fill', 'none');
s.setAttribute('stroke', 'currentColor');
s.setAttribute('stroke-width', String(width));
s.setAttribute('aria-hidden', 'true');
parts.forEach(function (p) {
var el = document.createElementNS(SVG_NS, p[0]);
Object.keys(p[1]).forEach(function (k) { el.setAttribute(k, p[1][k]); });
s.appendChild(el);
});
return s;
}
var ICONS = {
local: function () {
return svg(15, 1.5, [['rect', { x: '2.5', y: '3', width: '11', height: '7.5', rx: '1.2' }], ['path', { d: 'M1 13h14' }]]);
},
server: function () {
return svg(15, 1.5, [
['rect', { x: '2', y: '2', width: '12', height: '5', rx: '1.2' }],
['rect', { x: '2', y: '9', width: '12', height: '5', rx: '1.2' }],
['path', { d: 'M4.5 4.5h1M4.5 11.5h1' }]
]);
},
connect: function () { return svg(15, 1.7, [['path', { d: 'M8 2.5v11M2.5 8h11' }]]); },
loading: function () {
var s = document.createElement('span');
s.className = 'spin';
return s;
},
close: function () { return svg(10, 1.6, [['path', { d: 'M3 3l10 10M13 3L3 13' }]]); }
};
function iconKind(t) {
if (t.kind === 'connect' || t.kind === 'loading') return t.kind;
return t.local ? 'local' : 'server';
}
// ---- state ----
var state = { tabs: [], overviewActive: false, fullscreen: false };
var lastJson = '';
var views = new Map(); // tab id -> the tab's elements and what they show
var renaming = null; // { id, input, initial }
var drag = null; // a press on a tab that may turn into a drag
var pendingRender = false;
var rendering = false;
var suppressClick = false;
function createView(id) {
var root = document.createElement('div');
root.className = 'tab';
root.setAttribute('role', 'presentation');
root.dataset.id = String(id);
var hit = document.createElement('button');
hit.type = 'button';
hit.className = 'hit';
hit.tabIndex = -1;
hit.setAttribute('role', 'tab');
var ico = document.createElement('span');
ico.className = 'ico';
ico.setAttribute('aria-hidden', 'true');
var name = document.createElement('span');
name.className = 'name';
name.setAttribute('aria-hidden', 'true');
var badge = document.createElement('span');
badge.className = 'badge';
badge.setAttribute('aria-hidden', 'true');
var close = document.createElement('button');
close.type = 'button';
close.className = 'close';
close.tabIndex = -1;
close.setAttribute('aria-label', 'Close tab');
close.title = 'Close tab';
close.appendChild(ICONS.close());
root.appendChild(hit);
root.appendChild(ico);
root.appendChild(name);
root.appendChild(badge);
root.appendChild(close);
var v = { id: id, root: root, hit: hit, ico: ico, name: name, badge: badge, close: close, icon: '', badgeKind: null, tab: null };
views.set(id, v);
return v;
}
function updateView(v, t) {
v.tab = t;
var bk = badgeOf(t);
var cls = 'tab' + (t.active ? ' active' : '') + (bk === 'offline' ? ' offline' : '') +
(t.kind !== 'server' ? ' ' + t.kind : '') + (renaming && renaming.id === t.id ? ' renaming' : '');
if (v.root.className !== cls) v.root.className = cls;
v.root.style.setProperty('--c', t.color);
var ik = iconKind(t);
if (v.icon !== ik) {
v.icon = ik;
v.ico.replaceChildren(ICONS[ik]());
}
var label = displayName(t);
if (v.name.textContent !== label) v.name.textContent = label;
var btext = bk === 'needs' ? (t.needs > 99 ? '99+' : String(t.needs)) : '';
if (v.badgeKind !== bk + btext) {
v.badgeKind = bk + btext;
v.badge.className = 'badge' + (bk ? ' ' + bk : '');
v.badge.textContent = btext;
}
var words = statusWords(t);
v.hit.setAttribute('aria-selected', t.active ? 'true' : 'false');
v.hit.setAttribute('aria-label', [label].concat(words).join(', '));
// The strip is too short for a hover card under it, so the native
// tooltip carries the same lines.
var lines = [label + (t.key ? ' ⌘' + t.key : '')];
if (t.url) lines.push(t.url);
v.hit.title = lines.concat(words).join('\n');
}
function render() {
if (drag && drag.active) { pendingRender = true; return; }
pendingRender = false;
rendering = true;
strip.classList.toggle('fullscreen', state.fullscreen);
overviewBtn.classList.toggle('on', state.overviewActive);
overviewBtn.setAttribute('aria-pressed', state.overviewActive ? 'true' : 'false');
var seen = new Set();
state.tabs.forEach(function (t, i) {
var v = views.get(t.id) || createView(t.id);
updateView(v, t);
seen.add(t.id);
var at = tabsEl.children[i];
if (at !== v.root) tabsEl.insertBefore(v.root, at || null);
});
views.forEach(function (v, id) {
if (seen.has(id)) return;
if (renaming && renaming.id === id) endRename('gone');
v.root.remove();
views.delete(id);
});
rendering = false;
// Moving a tab in the row takes the focus from a rename under way: give it back.
if (renaming && document.activeElement !== renaming.input) renaming.input.focus();
}
function applyState(msg) {
var seen = new Set();
var tabs = [];
(Array.isArray(msg.tabs) ? msg.tabs : []).forEach(function (raw) {
var t = normTab(raw);
if (!t || seen.has(t.id)) return;
seen.add(t.id);
tabs.push(t);
});
var next = { tabs: tabs, overviewActive: msg.overviewActive === true, fullscreen: msg.fullscreen === true };
var json = JSON.stringify(next);
if (json === lastJson && !pendingRender) return;
lastJson = json;
state = next;
render();
}
// ---- rename ----
function startRename(id) {
var v = views.get(id);
if (!v || (drag && drag.active)) return;
if (renaming) {
if (renaming.id === id) { renaming.input.focus(); return; }
endRename('commit');
}
var input = document.createElement('input');
input.type = 'text';
input.className = 'rename';
input.maxLength = MAX_NAME;
input.spellcheck = false;
input.autocomplete = 'off';
input.setAttribute('aria-label', 'Tab name');
input.value = v.tab ? v.tab.name.slice(0, MAX_NAME) : '';
renaming = { id: id, input: input, before: v.tab ? v.tab.name : '', initial: input.value.trim() };
v.root.classList.add('renaming');
v.root.insertBefore(input, v.badge);
input.addEventListener('keydown', function (ev) {
ev.stopPropagation();
if (ev.key === 'Enter') { ev.preventDefault(); endRename('commit'); }
else if (ev.key === 'Escape') { ev.preventDefault(); endRename('cancel'); }
});
input.addEventListener('blur', function () {
if (rendering) return;
if (renaming && renaming.input === input) endRename('commit');
});
// The keyboard reaches this field only while this web view is the first
// responder, and the native side hands it back to the page below after
// every other click on the strip: ask for it.
post({ cmd: 'editing' });
input.focus();
input.select();
}
// how: 'commit' (Enter, a click elsewhere), 'cancel' (Escape) or 'gone'
// (the tab was closed). Every rename that ends on a tab still there posts
// one rename, a cancelled or unchanged one with the name the tab had: the
// native side takes that as "rename finished" and hands the keyboard back
// to the page below.
function endRename(how) {
var r = renaming;
if (!r) return;
renaming = null;
var name = r.input.value.trim().slice(0, MAX_NAME);
r.input.remove();
var v = views.get(r.id);
if (v) v.root.classList.remove('renaming');
if (how === 'gone') return;
if (how === 'cancel' || name === r.initial) {
post({ cmd: 'rename', id: r.id, name: r.before });
return;
}
// Shown at once; an empty name is the default the native side picks.
if (v && name) v.name.textContent = name;
post({ cmd: 'rename', id: r.id, name: name });
}
// ---- drag to reorder ----
function beginDrag() {
var roots = Array.prototype.slice.call(tabsEl.children);
drag.roots = roots;
drag.from = roots.indexOf(drag.root);
if (drag.from < 0) { drag = null; return; }
drag.rects = roots.map(function (r) { return r.getBoundingClientRect(); });
var r0 = drag.rects[drag.from];
var gap = roots.length > 1 ? drag.rects[1].left - drag.rects[0].right : 0;
drag.step = r0.width + gap;
drag.to = drag.from;
drag.active = true;
if (renaming) endRename('commit');
try { drag.root.setPointerCapture(drag.pointerId); } catch (e) { /* the pointer is gone */ }
tabsEl.classList.add('dragging');
drag.root.classList.add('lifted');
}
function moveDrag(dx) {
var rects = drag.rects;
var r0 = rects[drag.from];
var minDx = rects[0].left - r0.left;
var maxDx = rects[rects.length - 1].right - r0.right;
dx = Math.max(minDx, Math.min(maxDx, dx));
drag.root.style.transform = 'translateX(' + dx + 'px)';
var centre = r0.left + r0.width / 2 + dx;
var to = 0;
for (var i = 0; i < rects.length; i++) {
if (i !== drag.from && centre > rects[i].left + rects[i].width / 2) to++;
}
drag.to = to;
drag.roots.forEach(function (r, i) {
if (i === drag.from) return;
var shift = 0;
if (drag.from < to && i > drag.from && i <= to) shift = -drag.step;
else if (to < drag.from && i >= to && i < drag.from) shift = drag.step;
r.style.transform = shift ? 'translateX(' + shift + 'px)' : '';
});
}
function endDrag(commit) {
var d = drag;
drag = null;
if (!d || !d.active) return;
try { d.root.releasePointerCapture(d.pointerId); } catch (e) { /* already released */ }
// The slide stops before the tabs move, so nothing animates back.
tabsEl.classList.remove('dragging');
d.root.classList.remove('lifted');
d.roots.forEach(function (r) { r.style.transform = ''; });
// The click that ends a drag is not a select.
suppressClick = true;
setTimeout(function () { suppressClick = false; }, 0);
if (commit && d.to !== d.from) {
var at = state.tabs.findIndex(function (t) { return t.id === d.id; });
if (at >= 0) {
var moved = state.tabs.splice(at, 1)[0];
state.tabs.splice(d.to, 0, moved);
lastJson = JSON.stringify(state);
}
post({ cmd: 'move', id: d.id, to: d.to });
pendingRender = true;
}
if (pendingRender) render();
}
function tabOf(target) {
var root = target && target.closest ? target.closest('.tab') : null;
return root && views.has(Number(root.dataset.id)) ? Number(root.dataset.id) : null;
}
function inside(target, sel) { return !!(target && target.closest && target.closest(sel)); }
// ---- events ----
var middleDownOn = null;
document.addEventListener('mousedown', function (ev) {
var t = ev.target;
if (renaming && t !== renaming.input) endRename('commit');
if (inside(t, 'input')) return;
// The strip never takes the focus or starts a selection.
ev.preventDefault();
if (ev.button === 1) { middleDownOn = tabOf(t); return; }
if (ev.button !== 0 || ev.ctrlKey) return;
if (inside(t, '.tab, button')) return;
// The second press of a double click zooms, as a title bar does. Decided
// here, not on dblclick: the first press's window drag may keep WebKit
// from ever seeing a dblclick.
if (ev.detail === 2) post({ cmd: 'zoom' });
if (ev.detail > 1) return;
post({ cmd: 'drag' });
});
// Middle click closes, as in a browser (auxclick is not in every WebKit).
document.addEventListener('mouseup', function (ev) {
if (ev.button !== 1) return;
var id = tabOf(ev.target);
if (id !== null && id === middleDownOn) post({ cmd: 'close', id: id });
middleDownOn = null;
});
document.addEventListener('dblclick', function (ev) {
var t = ev.target;
var id = tabOf(t);
if (id !== null) {
if (!inside(t, '.close, input')) startRename(id);
return;
}
});
// WebKit's own menu (Reload, Inspect Element) never shows on the strip,
// the rename field included; only a tab has a menu, the native one, and
// not while its name is being typed.
document.addEventListener('contextmenu', function (ev) {
ev.preventDefault();
var id = inside(ev.target, 'input') ? null : tabOf(ev.target);
if (id !== null) post({ cmd: 'menu', id: id });
});
tabsEl.addEventListener('click', function (ev) {
if (suppressClick) { suppressClick = false; return; }
if (ev.ctrlKey) return; // a Control-click is the right click: the menu answers it
var id = tabOf(ev.target);
if (id === null || inside(ev.target, 'input')) return;
if (inside(ev.target, '.close')) post({ cmd: 'close', id: id });
else post({ cmd: 'select', id: id });
});
tabsEl.addEventListener('pointerdown', function (ev) {
if (ev.button !== 0 || ev.ctrlKey || !ev.isPrimary) return;
var id = tabOf(ev.target);
if (id === null || inside(ev.target, '.close, input')) return;
drag = { id: id, root: views.get(id).root, pointerId: ev.pointerId, startX: ev.clientX, active: false };
});
document.addEventListener('pointermove', function (ev) {
if (!drag || ev.pointerId !== drag.pointerId) return;
var dx = ev.clientX - drag.startX;
if (!drag.active) {
if (Math.abs(dx) < DRAG_START_PX) return;
beginDrag();
if (!drag) return;
}
moveDrag(dx);
});
document.addEventListener('pointerup', function (ev) {
if (drag && ev.pointerId === drag.pointerId) endDrag(true);
});
document.addEventListener('pointercancel', function (ev) {
if (drag && ev.pointerId === drag.pointerId) endDrag(false);
});
window.addEventListener('blur', function () { if (drag) endDrag(false); });
overviewBtn.addEventListener('click', function () { post({ cmd: 'overview' }); });
newBtn.addEventListener('click', function () { post({ cmd: 'new' }); });
function onNative(msg) {
if (typeof msg === 'string') {
try { msg = JSON.parse(msg); } catch (e) { return; }
}
if (!msg || typeof msg !== 'object') return;
if (msg.type === 'state') applyState(msg);
else if (msg.type === 'rename') {
var id = Number(msg.id);
if (isFinite(id)) startRename(id);
}
}
Object.defineProperty(window, '__codemanTabs', {
value: Object.freeze({ onNative: onNative }),
writable: false,
configurable: false,
enumerable: false
});
post({ cmd: 'ready' });
})();
</script>
</body>
</html>
+238 -1
View File
@@ -57,6 +57,10 @@ pub enum Poll {
#[derive(Deserialize)]
struct Session {
#[serde(default)]
id: String,
#[serde(default)]
name: Option<String>,
#[serde(default)]
status: String,
#[serde(default)]
@@ -80,11 +84,20 @@ fn count_working(body: &str) -> Option<u32> {
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Approval {
#[serde(default)]
kind: String,
#[serde(default, rename = "acknowledgedAt")]
#[serde(default)]
acknowledged_at: Option<f64>,
#[serde(default)]
session_id: String,
#[serde(default)]
tool_name: Option<String>,
#[serde(default)]
tool_summary: Option<String>,
#[serde(default)]
message: Option<String>,
}
#[derive(Deserialize)]
@@ -108,6 +121,145 @@ fn read_alerts(body: &str) -> Option<(bool, bool)> {
Some((waiting, needs_you))
}
/// What one agent session is doing, most urgent first (`SessionState::rank`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub enum SessionState {
/// Stopped on a permission or a question: a red tab.
Needs,
/// Finished, and nobody has looked yet: a yellow tab.
Waiting,
/// At work.
Working,
Idle,
}
impl SessionState {
pub fn rank(self) -> u8 {
match self {
SessionState::Needs => 0,
SessionState::Waiting => 1,
SessionState::Working => 2,
SessionState::Idle => 3,
}
}
}
/// One agent session of a server, for the tab badges and the overview. `name`
/// and `text` come from the server: the pages that show them treat them as
/// text.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionRow {
pub id: String,
pub name: String,
pub state: SessionState,
pub text: String,
}
/// Every agent session of a server and what it is doing. Shell tabs are left
/// out, as for the logo.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Detail {
pub sessions: Vec<SessionRow>,
}
impl Detail {
/// The same answer `Poller::poll` gives for this server.
#[cfg_attr(not(test), allow(dead_code))]
pub fn activity(&self) -> Activity {
let any = |state: SessionState| self.sessions.iter().any(|s| s.state == state);
Activity {
working: any(SessionState::Working),
waiting: any(SessionState::Waiting),
needs_you: any(SessionState::Needs),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum DetailPoll {
Seen(Detail),
Failed,
/// 401 or 403: the login is refused (or must be changed first). Asking
/// again would count against the login rate limit.
Refused,
/// 429: too many failed logins from this address, maybe other clients'.
/// Worth asking again, much later.
RateLimited,
}
/// How long a server's text may be in a row of the overview, in characters.
const MAX_ROW_TEXT: usize = 160;
const MAX_ROW_NAME: usize = 80;
/// How many sessions of one server are kept, so a server cannot make the app
/// hold a list of any length.
const MAX_SESSIONS: usize = 200;
/// Server text for a row: control characters out, whitespace runs folded,
/// cut at `max` characters.
fn row_text(raw: &str, max: usize) -> String {
let folded = raw
.split(|c: char| c.is_whitespace() || c.is_control())
.filter(|w| !w.is_empty())
.collect::<Vec<_>>()
.join(" ");
match folded.char_indices().nth(max) {
Some((cut, _)) => format!("{}\u{2026}", &folded[..cut]),
None => folded,
}
}
/// The detail of a server from its two answers: `GET api/sessions` and, when
/// the server has it, `GET api/approvals` (None: an older server, no alerts).
/// None when the sessions answer is not a list of sessions.
pub fn read_detail(sessions_body: &str, approvals_body: Option<&str>) -> Option<Detail> {
let (Sessions::Envelope { data: sessions } | Sessions::Bare(sessions)) =
serde_json::from_str(sessions_body).ok()?;
let approvals: Vec<Approval> = approvals_body
.and_then(|body| serde_json::from_str::<ApprovalsAnswer>(body).ok())
.map(|a| a.data.approvals)
.unwrap_or_default();
let rows = sessions
.into_iter()
.filter(|s| s.mode != "shell" && !s.id.is_empty())
.take(MAX_SESSIONS)
.map(|s| {
let mine = || approvals.iter().filter(|a| a.session_id == s.id);
let urgent = mine().find(|a| a.kind == "permission" || a.kind == "question");
let waiting = mine().any(|a| a.kind == "idle" && a.acknowledged_at.is_none());
let (state, text) = if let Some(a) = urgent {
let text = match (a.kind.as_str(), &a.tool_name, &a.tool_summary, &a.message) {
("permission", Some(tool), Some(summary), _) => format!("{tool}: {summary}"),
("permission", Some(tool), None, _) => format!("Allow {tool}?"),
(_, _, _, Some(message)) => message.clone(),
("question", _, _, None) => "Has a question for you".to_string(),
_ => "Needs your permission".to_string(),
};
(SessionState::Needs, text)
} else if waiting {
(SessionState::Waiting, "Finished, waiting for you".to_string())
} else if s.status == "busy" {
(SessionState::Working, "Working".to_string())
} else {
(SessionState::Idle, "Idle".to_string())
};
let name = s.name.as_deref().map(|n| row_text(n, MAX_ROW_NAME)).unwrap_or_default();
let name = if name.is_empty() {
s.id.chars().take(8).collect()
} else {
name
};
SessionRow {
id: s.id,
name,
state,
text: row_text(&text, MAX_ROW_TEXT),
}
})
.collect();
Some(Detail { sessions: rows })
}
/// `name=value` out of a `Set-Cookie` header, for Codeman's session cookie.
fn session_cookie(header: &str) -> Option<&str> {
let pair = header.split(';').next()?.trim();
@@ -215,6 +367,29 @@ impl Poller {
(activity.waiting, activity.needs_you) = self.alerts;
Poll::Seen(activity)
}
/// Every agent session and what it is doing (`read_detail`), for a server
/// tab's badges and the overview. Needs a poller made with `alerts`.
pub fn detail(&mut self) -> DetailPoll {
let url = self.sessions_url.clone();
let sessions = match self.ask(&url) {
Some((200, Some(body))) => body,
Some((429, _)) => return DetailPoll::RateLimited,
Some((s, _)) if refused(s) => return DetailPoll::Refused,
_ => return DetailPoll::Failed,
};
let approvals = match self.approvals_url.clone() {
Some(url) => match self.ask(&url) {
Some((200, body)) => body,
Some((429, _)) => return DetailPoll::RateLimited,
Some((s, _)) if refused(s) => return DetailPoll::Refused,
// An older server has no list; a failed read counts as none.
_ => None,
},
None => None,
};
read_detail(&sessions, approvals.as_deref()).map_or(DetailPoll::Failed, DetailPoll::Seen)
}
}
#[cfg(test)]
@@ -462,4 +637,66 @@ mod tests {
let server = Url::parse(&format!("http://127.0.0.1:{port}/")).unwrap();
assert_eq!(Poller::new(&server, None, false).unwrap().poll(), Poll::Failed);
}
#[test]
fn detail_reads_every_agent_session_and_its_state() {
let sessions = r#"{"success":true,"data":[
{"id":"s1","name":"webshop","status":"busy","mode":"claude"},
{"id":"s2","name":"billing","status":"idle","mode":"claude"},
{"id":"s3","name":"docs","status":"idle","mode":"codex"},
{"id":"s4","name":"shell","status":"busy","mode":"shell"},
{"id":"s5","status":"idle","mode":"claude"},
{"id":"s6","name":" two\n lines\u0007 ","status":"idle","mode":"claude"}]}"#;
let approvals = r#"{"success":true,"data":{"approvals":[
{"sessionId":"s2","kind":"permission","toolName":"Bash","toolSummary":"npm run migrate"},
{"sessionId":"s3","kind":"idle"},
{"sessionId":"s5","kind":"idle","acknowledgedAt":1},
{"sessionId":"s6","kind":"question","message":"Which locale first?"}]}}"#;
let detail = read_detail(sessions, Some(approvals)).unwrap();
let states: Vec<(&str, SessionState, &str)> = detail
.sessions
.iter()
.map(|s| (s.id.as_str(), s.state, s.text.as_str()))
.collect();
assert_eq!(
states,
[
("s1", SessionState::Working, "Working"),
("s2", SessionState::Needs, "Bash: npm run migrate"),
("s3", SessionState::Waiting, "Finished, waiting for you"),
("s5", SessionState::Idle, "Idle"),
("s6", SessionState::Needs, "Which locale first?"),
]
);
// A session with no name shows its id's start; server text is folded.
assert_eq!(detail.sessions[3].name, "s5");
assert_eq!(detail.sessions[4].name, "two lines");
assert_eq!(
detail.activity(),
Activity {
working: true,
waiting: true,
needs_you: true
}
);
}
#[test]
fn detail_without_approvals_and_from_junk() {
let bare = r#"[{"id":"a","name":"x","status":"busy","mode":"claude"}]"#;
let detail = read_detail(bare, None).unwrap();
assert_eq!(detail.sessions.len(), 1);
assert_eq!(detail.sessions[0].state, SessionState::Working);
assert_eq!(read_detail("not json", None), None);
assert_eq!(read_detail(r#"{"success":true,"data":{}}"#, None), None);
// A junk approvals answer counts as none.
assert_eq!(read_detail(bare, Some("<html>")).unwrap().sessions.len(), 1);
let long = format!(
r#"[{{"id":"a","name":"{}","status":"idle","mode":"claude"}}]"#,
"n".repeat(500)
);
let name = &read_detail(&long, None).unwrap().sessions[0].name;
assert_eq!(name.chars().count(), MAX_ROW_NAME + 1);
assert!(name.ends_with('\u{2026}'));
}
}
+44
View File
@@ -5,6 +5,10 @@ use std::borrow::Cow;
use wry::http::{header::CONTENT_TYPE, Request, Response, StatusCode};
const CONNECT_HTML: &[u8] = include_bytes!("../assets/connect.html");
/// The tab strip across the top of the window, and the overview of every
/// server (tabs.rs).
const TABS_HTML: &[u8] = include_bytes!("../assets/tabs.html");
const OVERVIEW_HTML: &[u8] = include_bytes!("../assets/overview.html");
const ICON_PNG: &[u8] = include_bytes!("../assets/icon.png");
/// The connect page loads nothing from outside the app.
@@ -14,6 +18,8 @@ const CSP: &str = "default-src 'none'; script-src 'unsafe-inline'; style-src 'un
pub fn respond(request: Request<Vec<u8>>) -> Response<Cow<'static, [u8]>> {
let (body, mime): (&'static [u8], &str) = match request.uri().path() {
"/" | "/index.html" => (CONNECT_HTML, "text/html; charset=utf-8"),
"/tabs.html" => (TABS_HTML, "text/html; charset=utf-8"),
"/overview.html" => (OVERVIEW_HTML, "text/html; charset=utf-8"),
"/icon.png" => (ICON_PNG, "image/png"),
_ => {
return Response::builder()
@@ -220,6 +226,24 @@ pub fn refused_script(session_id: Option<&str>) -> String {
)
}
/// Hands a message to one of the app's own pages: the connect page
/// (`__codemanDesktop`), the tab strip (`__codemanTabs`) or the overview
/// (`__codemanOverview`). The message is JSON, which is also a JavaScript
/// expression.
pub fn native_message_script(global: &str, msg: &serde_json::Value) -> String {
format!("window.{global} && window.{global}.onNative({msg})")
}
/// Selects a session in Codeman's page, as a click on its tab would (the
/// overview's rows). `id` has passed `tabs::is_session_id`, and goes in as a
/// JSON string all the same.
pub fn select_session_script(id: &str) -> String {
let id = serde_json::to_string(id).unwrap_or_else(|_| "\"\"".into());
format!(
"try {{ if (window.app && typeof window.app.selectSession === 'function') window.app.selectSession({id}); }} catch (e) {{}}"
)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -248,6 +272,26 @@ mod tests {
assert_eq!(get("/other.js").status(), StatusCode::NOT_FOUND);
}
#[test]
fn serves_the_strip_and_the_overview() {
for (path, global) in [("/tabs.html", "__codemanTabs"), ("/overview.html", "__codemanOverview")] {
let page = get(path);
assert_eq!(page.status(), StatusCode::OK, "{path}");
assert_eq!(page.headers()["content-security-policy"], CSP, "{path}");
assert!(String::from_utf8_lossy(page.body()).contains(global), "{path}");
}
}
#[test]
fn page_scripts_carry_json() {
let msg = serde_json::json!({ "type": "state", "name": "a\"b</script>" });
let script = native_message_script("__codemanTabs", &msg);
assert!(script.starts_with("window.__codemanTabs && window.__codemanTabs.onNative({"));
assert!(script.contains(r#""a\"b</script>""#));
let select = select_session_script("abc-1");
assert!(select.contains(r#"selectSession("abc-1")"#));
}
#[test]
fn refused_script_escapes_the_session_id() {
let js = refused_script(Some("a'\"); alert(1); //\u{2028}\\"));
+157
View File
@@ -11,6 +11,8 @@ use std::io;
use std::path::{Path, PathBuf};
const MAX_SERVERS: usize = 8;
/// How many server tabs are saved for the next launch.
pub const MAX_TABS: usize = 24;
/// How many recovery copies of an unreadable config can sit side by side:
/// `desktop.json.corrupt`, then `desktop.json.corrupt.1` to `.9`.
const ASIDE_SLOTS: usize = 10;
@@ -59,6 +61,50 @@ pub struct Config {
/// make the whole file unreadable, which would cost the server list.
#[serde(deserialize_with = "lenient_window")]
pub window: Option<WindowFrame>,
/// The server tabs to open again at the next launch, in strip order. Only
/// tabs that belong to a server are kept. Read leniently, like `window`.
#[serde(deserialize_with = "lenient_tabs")]
pub tabs: Vec<TabEntry>,
/// The tab that was in front, an index into `tabs`.
#[serde(deserialize_with = "lenient_index")]
pub active_tab: usize,
/// The one server whose pages keep WebKit's default data store, so the
/// local storage it had before tabs existed (Codeman's per-device settings)
/// stays with it; every other server gets a store of its own
/// (`tabs::store_id`). None: not decided yet, which the first launch with
/// tabs does (the most recent server, or `Some("")` for none).
#[serde(deserialize_with = "lenient_string", skip_serializing_if = "Option::is_none")]
pub default_store_server: Option<String>,
}
/// One saved tab: the server it is for, and what the user made of it.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct TabEntry {
pub url: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub color: Option<String>,
}
fn lenient_tabs<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<TabEntry>, D::Error> {
let value = serde_json::Value::deserialize(d)?;
let list = value.as_array().cloned().unwrap_or_default();
Ok(list
.into_iter()
.filter_map(|v| serde_json::from_value::<TabEntry>(v).ok())
.collect())
}
fn lenient_index<'de, D: serde::Deserializer<'de>>(d: D) -> Result<usize, D::Error> {
let value = serde_json::Value::deserialize(d)?;
Ok(value.as_u64().and_then(|n| usize::try_from(n).ok()).unwrap_or(0))
}
fn lenient_string<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
let value = serde_json::Value::deserialize(d)?;
Ok(value.as_str().map(str::to_owned))
}
fn lenient_window<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<WindowFrame>, D::Error> {
@@ -83,6 +129,9 @@ impl Default for Config {
logo_blink: BlinkStyles::default(),
keep_awake: keep_awake::Settings::default(),
window: None,
tabs: Vec::new(),
active_tab: 0,
default_store_server: None,
}
}
}
@@ -341,6 +390,35 @@ impl Config {
self.servers.retain(|s| !s.url.is_empty() && seen.insert(s.url.clone()));
self.servers.truncate(MAX_SERVERS);
self.window = self.window.and_then(WindowFrame::sanitized);
let mut seen = std::collections::HashSet::new();
self.tabs.retain(|t| !t.url.is_empty() && seen.insert(t.url.clone()));
self.tabs.truncate(MAX_TABS);
for tab in &mut self.tabs {
tab.name = tab.name.as_deref().and_then(crate::tabs::clean_name);
tab.color = tab.color.take().filter(|c| crate::tabs::is_color(c));
}
if self.active_tab >= self.tabs.len() {
self.active_tab = 0;
}
}
/// Settle `default_store_server` once: the server used last keeps the data
/// store it always had. True when it changed (the caller saves).
pub fn settle_default_store(&mut self) -> bool {
if self.default_store_server.is_some() {
return false;
}
self.default_store_server = Some(self.servers.first().map(|s| s.url.clone()).unwrap_or_default());
true
}
/// The data store a server's pages use: None for WebKit's default one,
/// else the server's own (`tabs::store_id`).
pub fn store_for(&self, url: &str) -> Option<[u8; 16]> {
match &self.default_store_server {
Some(server) if server == url => None,
_ => Some(crate::tabs::store_id(url)),
}
}
/// Move (or add) a server to the top of the recent list. Returns the
@@ -898,4 +976,83 @@ mod tests {
};
assert!(full.fitted_to(&tiny, MIN).unwrap().fullscreen);
}
#[test]
fn tabs_round_trip_and_bad_values_are_dropped() {
let dir = tmp_dir("tabs");
let path = dir.join("desktop.json");
fs::create_dir_all(&dir).unwrap();
fs::write(
&path,
r##"{"servers":[],"activeTab":7,"tabs":[
{"url":"http://127.0.0.1:3000/","name":" Mine ","color":"#A78BFA"},
{"url":"http://127.0.0.1:3000/","name":"again"},
{"url":"https://studio.example.ts.net/","color":"red;x"},
{"url":""},
42,
{"name":"no url"}]}"##,
)
.unwrap();
let (c, can_save) = Config::load_from(&path);
assert!(can_save);
assert_eq!(
c.tabs,
[
TabEntry {
url: "http://127.0.0.1:3000/".into(),
name: Some("Mine".into()),
color: Some("#A78BFA".into()),
},
TabEntry {
url: "https://studio.example.ts.net/".into(),
name: None,
color: None,
},
]
);
// An index past the list falls back to the first tab.
assert_eq!(c.active_tab, 0);
c.save_to(&path).unwrap();
let (again, _) = Config::load_from(&path);
assert_eq!(again.tabs, c.tabs);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn a_bad_tab_value_never_costs_the_server_list() {
let dir = tmp_dir("badtabs");
let path = dir.join("desktop.json");
fs::create_dir_all(&dir).unwrap();
fs::write(
&path,
r#"{"servers":[{"url":"http://a/"}],"tabs":"nope","activeTab":-3,"defaultStoreServer":5}"#,
)
.unwrap();
let (c, can_save) = Config::load_from(&path);
assert!(can_save);
assert_eq!(c.servers.len(), 1);
assert!(c.tabs.is_empty());
assert_eq!(c.active_tab, 0);
assert_eq!(c.default_store_server, None);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn the_server_used_last_keeps_the_default_store() {
let mut c = Config::default();
let _ = c.remember("http://old/", None, false);
let _ = c.remember("http://recent/", None, false);
assert!(c.settle_default_store());
assert_eq!(c.default_store_server.as_deref(), Some("http://recent/"));
// Decided once: a later connect does not move it.
let _ = c.remember("http://old/", None, false);
assert!(!c.settle_default_store());
assert_eq!(c.store_for("http://recent/"), None);
assert_eq!(c.store_for("http://old/"), Some(crate::tabs::store_id("http://old/")));
// A first run with no server keeps no server on the default store.
let mut fresh = Config::default();
assert!(fresh.settle_default_store());
assert_eq!(fresh.default_store_server.as_deref(), Some(""));
assert!(fresh.store_for("http://x/").is_some());
}
}
+103 -43
View File
@@ -1165,14 +1165,33 @@ fn watch(logo: &impl Logo, marker: &Marker, styles: BlinkStyles, signals: &mut i
}
}
/// The one line the app writes to the child.
#[derive(Serialize, Deserialize)]
/// The one line the app writes to the child: every open server tab, each with
/// its login, and the styles. The logo shows the most urgent state of all of
/// them together.
#[derive(Serialize, Deserialize, PartialEq)]
struct Connection {
server: String,
authorization: Option<String>,
servers: Vec<Target>,
styles: BlinkStyles,
}
/// One server the child asks.
#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
pub struct Target {
pub server: String,
pub authorization: Option<String>,
}
/// What several servers' agents do together: each state holds when it holds on
/// any of them.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn merged(all: &[Activity]) -> Activity {
all.iter().fold(Activity::default(), |acc, a| Activity {
working: acc.working || a.working,
waiting: acc.waiting || a.waiting,
needs_you: acc.needs_you || a.needs_you,
})
}
/// The app's side: the pipe to the child, which is all there is to it.
#[derive(Default)]
pub struct Watcher {
@@ -1185,27 +1204,23 @@ impl Watcher {
self.current.is_some()
}
/// Watch this server with this login in these styles, or nothing. A child
/// for anything else ends first: its pipe closes with the old value. It is
/// back to normal well before the next child looks, which takes `SETTLE`.
pub fn sync(&mut self, want: Option<(&str, Option<&str>, BlinkStyles)>) {
let same = match (&self.current, want) {
(Some((now, _)), Some((server, authorization, styles))) => {
now.server == server && now.authorization.as_deref() == authorization && now.styles == styles
}
/// Watch these servers with their logins in these styles, or nothing (an
/// empty list is nothing too). A child for anything else ends first: its
/// pipe closes with the old value. It is back to normal well before the
/// next child looks, which takes `SETTLE`.
pub fn sync(&mut self, want: Option<(Vec<Target>, BlinkStyles)>) {
let want = want
.filter(|(servers, _)| !servers.is_empty())
.map(|(servers, styles)| Connection { servers, styles });
let same = match (&self.current, &want) {
(Some((now, _)), Some(want)) => now == want,
(None, None) => true,
_ => false,
};
if same {
return;
}
self.current = want.and_then(|(server, authorization, styles)| {
spawn_child(Connection {
server: server.to_owned(),
authorization: authorization.map(str::to_owned),
styles,
})
});
self.current = want.and_then(spawn_child);
}
}
@@ -1843,16 +1858,25 @@ mod system {
}
}
/// Runs for the life of the child. A server that does not answer counts as
/// nothing going on, and one that refuses the login is never asked again.
fn poll_until_refused(mut poller: Poller, shared: &Mutex<Activity>) {
/// Runs for the life of the child, one per server. A server that does not
/// answer counts as nothing going on, and one that refuses the login is
/// never asked again. Each writes its own slot, and `shared` is what all of
/// them say together (`merged`).
fn poll_until_refused(mut poller: Poller, index: usize, slots: &Mutex<Vec<Activity>>, shared: &Mutex<Activity>) {
loop {
let poll = poller.poll();
if let Ok(mut activity) = shared.lock() {
*activity = match poll {
Poll::Seen(seen) => seen,
_ => Activity::default(),
};
let seen = match poll {
Poll::Seen(seen) => seen,
_ => Activity::default(),
};
let all = slots.lock().ok().map(|mut slots| {
if let Some(slot) = slots.get_mut(index) {
*slot = seen;
}
super::merged(&slots)
});
if let (Some(all), Ok(mut activity)) = (all, shared.lock()) {
*activity = all;
}
if poll == Poll::Refused {
return;
@@ -1877,18 +1901,19 @@ mod system {
.read_line(&mut line)
.ok()
.and_then(|_| serde_json::from_str::<Connection>(&line).ok());
let Some(Connection {
server,
authorization,
styles,
}) = connection
else {
let Some(Connection { servers, styles }) = connection else {
std::process::exit(0);
};
let poller = Url::parse(&server)
.ok()
.and_then(|url| Poller::new(&url, authorization, styles.wants_alerts()));
let (Some(poller), Some(logo)) = (poller, SystemLogo::open()) else {
let pollers: Vec<Poller> = servers
.into_iter()
.filter_map(|target| {
Url::parse(&target.server)
.ok()
.and_then(|url| Poller::new(&url, target.authorization, styles.wants_alerts()))
})
.collect();
let logo = SystemLogo::open();
let Some(logo) = logo.filter(|_| !pollers.is_empty()) else {
std::process::exit(0);
};
@@ -1900,8 +1925,12 @@ mod system {
let _ = closed.send(());
});
let activity = Arc::new(Mutex::new(Activity::default()));
let found = activity.clone();
std::thread::spawn(move || poll_until_refused(poller, &found));
let slots = Arc::new(Mutex::new(vec![Activity::default(); pollers.len()]));
for (index, poller) in pollers.into_iter().enumerate() {
let found = activity.clone();
let slots = slots.clone();
std::thread::spawn(move || poll_until_refused(poller, index, &slots, &found));
}
let mut signals = Live {
pipe_closed,
@@ -3371,15 +3400,17 @@ mod tests {
fn the_connection_line_round_trips_with_and_without_a_login() {
for authorization in [None, Some("Basic abc".to_string())] {
let line = serde_json::to_string(&Connection {
server: "http://127.0.0.1:3000/".into(),
authorization: authorization.clone(),
servers: vec![Target {
server: "http://127.0.0.1:3000/".into(),
authorization: authorization.clone(),
}],
styles: WORK,
})
.unwrap();
assert!(!line.contains('\n'), "one line");
let back: Connection = serde_json::from_str(&line).unwrap();
assert_eq!(back.server, "http://127.0.0.1:3000/");
assert_eq!(back.authorization, authorization);
assert_eq!(back.servers[0].server, "http://127.0.0.1:3000/");
assert_eq!(back.servers[0].authorization, authorization);
assert_eq!(back.styles, WORK);
}
}
@@ -3686,4 +3717,33 @@ mod tests {
watcher.sync(None);
assert!(watcher.current.is_none());
}
#[test]
fn several_servers_merge_into_one_logo() {
assert_eq!(merged(&[]), Activity::default());
assert_eq!(merged(&[working(), Activity::default()]), working());
let all = merged(&[working(), needs_you(), waiting()]);
assert!(all.working && all.waiting && all.needs_you);
}
#[test]
fn the_child_line_names_every_server() {
let line = serde_json::to_string(&Connection {
servers: vec![
Target {
server: "http://127.0.0.1:3000/".into(),
authorization: None,
},
Target {
server: "https://studio.example.ts.net/".into(),
authorization: Some("Basic eA==".into()),
},
],
styles: WORK,
})
.unwrap();
let back: Connection = serde_json::from_str(&line).unwrap();
assert_eq!(back.servers.len(), 2);
assert_eq!(back.servers[1].authorization.as_deref(), Some("Basic eA=="));
}
}
+294 -74
View File
@@ -21,8 +21,14 @@
//! of it: every challenge comes back here and gets the login of that moment,
//! never one an earlier connect left behind.
//!
//! Two smaller helpers live here too: `clear_cookies`, which empties the web
//! views' cookie jar before a login so an earlier user's session cookie cannot
//! Each server tab hands over a login of its own (`set_credentials`, keyed by
//! the tab), and a challenge is answered with the login of the tab whose server
//! it is (`pick`), and only to a web view of that tab (`bind_view`), so two
//! tabs never answer for each other, even when one tab's page fetches from
//! the other's server.
//!
//! Two smaller helpers live here too: `clear_cookies`, which removes one
//! server's cookies before a login so an earlier user's session cookie cannot
//! win over the new login, and `content_size`, the window's content area.
//!
//! `install` adds the missing methods to the classes of the delegates wry made,
@@ -145,6 +151,40 @@ fn bare_host(host: &str) -> &str {
host.strip_prefix('[').and_then(|h| h.strip_suffix(']')).unwrap_or(host)
}
/// Which tab's login a challenge is for. The URL that got the 401 belongs to
/// the tab whose server the protection space names and whose base path holds
/// it, the deepest one when several do (a server at `/` and another below a
/// path on the same origin, behind one proxy); then that tab answers only when
/// the URL is in its scope (`policy::challenge_in_scope`). So a web tab of the
/// deeper server never gets the login of the server above it. None: no tab's
/// server, so WebKit's own handling.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn pick<'a>(challenge: &Challenge<'_>, saved: &'a [(u64, BasicCredentials)]) -> Option<(u64, &'a BasicCredentials)> {
let failed = challenge.failed?;
let (tab, owner) = saved
.iter()
.filter(|(_, s)| {
credentials_match(s, challenge.scheme, challenge.host, challenge.port)
&& crate::policy::within_base(failed, &s.server)
})
.max_by_key(|(_, s)| s.server.path().len())?;
crate::policy::challenge_in_scope(failed, &owner.server).then_some((*tab, owner))
}
/// Whether a cookie the store keeps for `domain` goes to pages of `host`: a
/// host-only cookie of that host (Codeman's own, which names no domain), or a
/// domain cookie (`.example.ts.net`) the host lies under. Case-insensitive,
/// IPv6 brackets ignored.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn cookie_for_host(domain: &str, host: &str) -> bool {
let host = bare_host(host).to_ascii_lowercase();
let domain = bare_host(domain.trim()).to_ascii_lowercase();
match domain.strip_prefix('.') {
Some(parent) => host == parent || host.ends_with(&domain),
None => !domain.is_empty() && host == domain,
}
}
/// How a dialog names the page that opened it ("localhost:3000"), from a
/// security origin's host and port (0 = the scheme's default, left out).
fn origin_label(host: &str, port: i64) -> Option<String> {
@@ -182,25 +222,51 @@ pub fn install(webview: &wry::WebView) {
imp::install(webview);
}
/// The login HTTP Basic challenges from that server are answered with
/// (`None`: answer none), from the next challenge on: WebKit keeps no copy of
/// an earlier one. Also re-arms the refusal report. Main thread only.
/// The login HTTP Basic challenges from tab `tab`'s server are answered with
/// (`None`: that tab answers none), from the next challenge on: WebKit keeps
/// no copy of an earlier one. Also re-arms that tab's refusal report. Main
/// thread only.
#[cfg(target_os = "macos")]
pub fn set_credentials(creds: Option<BasicCredentials>) {
imp::set_credentials(creds);
pub fn set_credentials(tab: u64, creds: Option<BasicCredentials>) {
imp::set_credentials(tab, creds);
}
/// Called on the main thread, once per `set_credentials`, when the server
/// refused the saved login. It runs inside a WebKit callback, so it should
/// only post an event, never touch windows directly.
/// Called on the main thread with the tab, once per `set_credentials` of that
/// tab, when its server refused the saved login. It runs inside a WebKit
/// callback, so it should only post an event, never touch windows directly.
#[cfg(target_os = "macos")]
pub fn set_auth_rejected_handler(handler: Box<dyn Fn()>) {
pub fn set_auth_rejected_handler(handler: Box<dyn Fn(u64)>) {
imp::set_auth_rejected_handler(handler);
}
/// Removes every cookie from the app's default website data store, which all
/// of its web views use, then calls `done`. Only cookies: local storage, where
/// Codeman keeps per-device settings, stays. Main thread only.
/// Ties a web view to a tab: a Basic challenge from that web view is answered
/// with that tab's login only, never another tab's, whatever server the
/// request went to. Call it for every server page and pop-out web view. Main
/// thread only.
#[cfg(target_os = "macos")]
pub fn bind_view(webview: &wry::WebView, tab: u64) {
imp::bind_view(webview, tab);
}
/// A closed tab's web views answer no challenge any more.
#[cfg(target_os = "macos")]
pub fn forget_tab(tab: u64) {
imp::forget_tab(tab);
}
/// Whether WebKit gives each server a data store of its own
/// (`dataStoreForIdentifier:`, macOS 14 and later). wry falls back to the
/// default store without it, and so does `clear_cookies`.
#[cfg(target_os = "macos")]
pub fn own_stores_available() -> bool {
imp::os_major_version() >= 14
}
/// Removes the cookies of `host` (`cookie_for_host`) from a data store: the
/// server's own (`store`, on a macOS that has them) or the default one, then
/// calls `done`. Only that host's cookies, so the other servers' tabs stay
/// logged in, and only cookies: local storage, where Codeman keeps
/// per-device settings, stays. Main thread only.
///
/// `done` runs exactly once, on the main thread, as its own operation on the
/// main queue: never before this returns and never inside a WebKit callback.
@@ -209,8 +275,8 @@ pub fn set_auth_rejected_handler(handler: Box<dyn Fn()>) {
/// nothing and calls `done` right away on the calling thread. If WebKit never
/// answers at all, `done` never runs: the caller's own deadline covers that.
#[cfg(target_os = "macos")]
pub fn clear_cookies(done: Box<dyn FnOnce()>) {
imp::clear_cookies(done);
pub fn clear_cookies(store: Option<[u8; 16]>, host: String, done: Box<dyn FnOnce()>) {
imp::clear_cookies(store, host, done);
}
/// The window's content area in points (`contentRectForFrameRect` of its
@@ -244,28 +310,38 @@ mod imp {
use objc2::{msg_send, sel, ClassType, Message};
use objc2_app_kit::{NSAlert, NSAlertFirstButtonReturn, NSTextField, NSView, NSWindow};
use objc2_foundation::{
MainThreadMarker, NSDate, NSInteger, NSOperationQueue, NSPoint, NSRect, NSSet, NSSize, NSString,
NSURLAuthenticationChallenge, NSURLAuthenticationMethodHTTPBasic, NSURLCredential, NSURLCredentialPersistence,
NSURLProtectionSpace, NSURLRequest, NSURLResponse, NSURLSessionAuthChallengeDisposition, NSURL,
MainThreadMarker, NSArray, NSHTTPCookie, NSInteger, NSOperationQueue, NSPoint, NSProcessInfo, NSRect, NSSize,
NSString, NSURLAuthenticationChallenge, NSURLAuthenticationMethodHTTPBasic, NSURLCredential,
NSURLCredentialPersistence, NSURLProtectionSpace, NSURLRequest, NSURLResponse,
NSURLSessionAuthChallengeDisposition, NSURL, NSUUID,
};
use objc2_web_kit::{WKFrameInfo, WKSecurityOrigin, WKWebsiteDataStore, WKWebsiteDataTypeCookies};
use objc2_web_kit::{WKFrameInfo, WKSecurityOrigin, WKWebsiteDataStore};
use tao::platform::macos::WindowExtMacOS;
use url::Url;
use wry::WebViewExtMacOS;
use super::{decide, dialog_title, origin_label, BasicCredentials, Challenge, ChallengeAnswer};
use super::{
cookie_for_host, decide, dialog_title, origin_label, pick, BasicCredentials, Challenge, ChallengeAnswer,
};
/// Page text in a dialog is cut at this many UTF-16 units, so a huge
/// message cannot push the alert's buttons off the screen.
const MAX_DIALOG_UTF16: usize = 2000;
/// What the app is told, with the tab, when a server refuses its login.
type RejectedHandler = Rc<dyn Fn(u64)>;
thread_local! {
/// The login challenges are answered with; `None` answers none.
static SAVED: RefCell<Option<BasicCredentials>> = const { RefCell::new(None) };
/// The server refused `SAVED` and the app was told; `set_credentials` clears it.
static REJECTED: Cell<bool> = const { Cell::new(false) };
/// Told once when the server refuses `SAVED`.
static ON_REJECTED: RefCell<Option<Rc<dyn Fn()>>> = const { RefCell::new(None) };
/// The login of each tab that has one, by tab.
static SAVED: RefCell<Vec<(u64, BasicCredentials)>> = const { RefCell::new(Vec::new()) };
/// The tabs whose server refused their login, the app told; a tab's
/// `set_credentials` takes it out again.
static REJECTED: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
/// The tab of each server page and pop-out web view, by the address of
/// its WKWebView (`bind_view`).
static VIEWS: RefCell<Vec<(usize, u64)>> = const { RefCell::new(Vec::new()) };
/// Told once, with the tab, when a server refuses its login.
static ON_REJECTED: RefCell<Option<RejectedHandler>> = const { RefCell::new(None) };
}
// The added methods, with every object argument as a raw pointer: WebKit
@@ -365,61 +441,145 @@ mod imp {
}
}
pub(super) fn set_credentials(creds: Option<BasicCredentials>) {
pub(super) fn set_credentials(tab: u64, creds: Option<BasicCredentials>) {
if MainThreadMarker::new().is_none() {
eprintln!("codeman-desktop: macos::set_credentials called off the main thread; ignored");
return;
}
let stored = SAVED.try_with(|saved| saved.try_borrow_mut().map(|mut saved| *saved = creds).is_ok());
let stored = SAVED.try_with(|saved| {
saved
.try_borrow_mut()
.map(|mut saved| {
saved.retain(|(t, _)| *t != tab);
if let Some(creds) = creds {
saved.push((tab, creds));
}
})
.is_ok()
});
if stored != Ok(true) {
eprintln!("codeman-desktop: could not store the login for Basic challenges");
}
let _ = REJECTED.try_with(|rejected| rejected.set(false));
let _ = REJECTED.try_with(|rejected| {
if let Ok(mut rejected) = rejected.try_borrow_mut() {
rejected.retain(|t| *t != tab);
}
});
}
pub(super) fn set_auth_rejected_handler(handler: Box<dyn Fn()>) {
pub(super) fn bind_view(webview: &wry::WebView, tab: u64) {
if MainThreadMarker::new().is_none() {
return;
}
let address = Retained::as_ptr(&WebViewExtMacOS::webview(webview)) as usize;
let _ = VIEWS.try_with(|views| {
if let Ok(mut views) = views.try_borrow_mut() {
// A WKWebView freed earlier may have left its address behind.
views.retain(|(a, _)| *a != address);
views.push((address, tab));
}
});
}
pub(super) fn forget_tab(tab: u64) {
let _ = VIEWS.try_with(|views| {
if let Ok(mut views) = views.try_borrow_mut() {
views.retain(|(_, t)| *t != tab);
}
});
}
/// The tab a WKWebView belongs to, by its address.
fn tab_of_view(web_view: *mut AnyObject) -> Option<u64> {
let address = web_view as usize;
VIEWS
.try_with(|views| {
views
.try_borrow()
.ok()
.and_then(|views| views.iter().find(|(a, _)| *a == address).map(|(_, t)| *t))
})
.ok()
.flatten()
}
pub(super) fn os_major_version() -> isize {
NSProcessInfo::processInfo().operatingSystemVersion().majorVersion
}
pub(super) fn set_auth_rejected_handler(handler: Box<dyn Fn(u64)>) {
if MainThreadMarker::new().is_none() {
eprintln!("codeman-desktop: macos::set_auth_rejected_handler called off the main thread; ignored");
return;
}
let handler: Rc<dyn Fn()> = Rc::from(handler);
let handler: RejectedHandler = Rc::from(handler);
let stored = ON_REJECTED.try_with(|slot| slot.try_borrow_mut().map(|mut slot| *slot = Some(handler)).is_ok());
if stored != Ok(true) {
eprintln!("codeman-desktop: could not store the login-refused handler");
}
}
pub(super) fn clear_cookies(done: Box<dyn FnOnce()>) {
if MainThreadMarker::new().is_none() {
pub(super) fn clear_cookies(store: Option<[u8; 16]>, host: String, done: Box<dyn FnOnce()>) {
let Some(mtm) = MainThreadMarker::new() else {
eprintln!("codeman-desktop: macos::clear_cookies called off the main thread; cookies kept");
// `done` was made on this thread, so it runs here instead of being
// sent to another one.
run_done(done);
return;
}
};
// Every way out of here, a panic included, either hands `pending` to
// WebKit's completion handler or drops it, and both pass `done` on.
let pending = Pending(Cell::new(Some(done)));
let _ = catch_unwind(AssertUnwindSafe(|| autoreleasepool(|_| remove_cookies(pending))));
// WebKit's completion handlers or drops it, and both pass `done` on.
let pending = Rc::new(Pending(Cell::new(Some(done))));
let _ = catch_unwind(AssertUnwindSafe(|| {
autoreleasepool(|_| remove_cookies(mtm, store, host, pending))
}));
}
fn remove_cookies(pending: Pending) {
// SAFETY: class methods called on the main thread (checked by the
// caller), with nil handled by the `Option` return types.
let store: Option<Retained<WKWebsiteDataStore>> =
unsafe { msg_send![WKWebsiteDataStore::class(), defaultDataStore] };
let since: Option<Retained<NSDate>> = unsafe { msg_send![NSDate::class(), distantPast] };
let (Some(store), Some(since)) = (store, since) else {
eprintln!("codeman-desktop: no website data store; cookies kept");
return;
fn remove_cookies(mtm: MainThreadMarker, store: Option<[u8; 16]>, host: String, pending: Rc<Pending>) {
// The same store wry gave the server's web view: its own on a macOS that
// has them, else the default one. `dataStoreForIdentifier:` does not
// exist before macOS 14, and an all-zero identifier throws.
let own = store.filter(|id| os_major_version() >= 14 && id.iter().any(|b| *b != 0));
// SAFETY: class methods called on the main thread (the marker).
let data_store: Retained<WKWebsiteDataStore> = match own {
Some(id) => unsafe { WKWebsiteDataStore::dataStoreForIdentifier(&NSUUID::from_bytes(id), mtm) },
None => unsafe { WKWebsiteDataStore::defaultDataStore(mtm) },
};
// SAFETY: an immutable string constant exported by WebKit.
let types = NSSet::from_slice(&[unsafe { WKWebsiteDataTypeCookies }]);
let completion = RcBlock::new(move || pending.finish());
// SAFETY: main thread; WebKit copies the block, keeps it until the
// cookies are gone and then calls it. Dropping our reference after the
// call is fine.
unsafe { store.removeDataOfTypes_modifiedSince_completionHandler(&types, &since, &completion) };
// SAFETY: a property read on the main thread.
let cookies = unsafe { data_store.httpCookieStore() };
let delete_from = cookies.clone();
let fetched = RcBlock::new(move |all: std::ptr::NonNull<NSArray<NSHTTPCookie>>| {
// SAFETY: WebKit hands a valid array for the length of this call.
let all = unsafe { all.as_ref() };
let mine: Vec<Retained<NSHTTPCookie>> = autoreleasepool(|_| {
all.to_vec()
.into_iter()
.filter(|cookie| rust_string(&cookie.domain()).is_some_and(|d| cookie_for_host(&d, &host)))
.collect()
});
if mine.is_empty() {
pending.finish();
return;
}
// `done` goes once the last of them is deleted.
let left = Rc::new(Cell::new(mine.len()));
for cookie in &mine {
let left = left.clone();
let pending = pending.clone();
let deleted = RcBlock::new(move || {
left.set(left.get().saturating_sub(1));
if left.get() == 0 {
pending.finish();
}
});
// SAFETY: main thread (WebKit calls this handler there); WebKit
// copies the block and calls it once the cookie is gone.
unsafe { delete_from.deleteCookie_completionHandler(cookie, Some(&deleted)) };
}
});
// SAFETY: main thread; WebKit copies the block, calls it with the
// store's cookies, and releases it.
unsafe { cookies.getAllCookies(&fetched) };
}
/// `done` until it is passed on: by the completion handler, or, when
@@ -692,7 +852,7 @@ mod imp {
extern "C-unwind" fn did_receive_challenge(
_this: *mut AnyObject,
_cmd: Sel,
_web_view: *mut AnyObject,
web_view: *mut AnyObject,
challenge: *mut NSURLAuthenticationChallenge,
handler: *mut ChallengeHandler,
) {
@@ -700,22 +860,24 @@ mod imp {
let Some(handler) = (unsafe { handler.as_ref() }) else {
return;
};
let reply = catch_unwind(AssertUnwindSafe(|| reply_to(unsafe { challenge.as_ref() }))).unwrap_or_default();
let tab = tab_of_view(web_view);
let reply = catch_unwind(AssertUnwindSafe(|| reply_to(unsafe { challenge.as_ref() }, tab))).unwrap_or_default();
let credential = reply
.credential
.as_ref()
.map_or(ptr::null_mut(), |c| Retained::as_ptr(c).cast_mut());
handler.call((reply.disposition, credential));
// Told after WebKit has its answer, so the app's handler cannot delay it.
if reply.report {
notify_rejected();
if let Some(tab) = reply.report {
notify_rejected(tab);
}
}
struct Reply {
disposition: NSURLSessionAuthChallengeDisposition,
credential: Option<Retained<NSURLCredential>>,
report: bool,
/// The tab whose server refused its login, to tell the app.
report: Option<u64>,
}
impl Default for Reply {
@@ -723,12 +885,14 @@ mod imp {
Reply {
disposition: NSURLSessionAuthChallengeDisposition::PerformDefaultHandling,
credential: None,
report: false,
report: None,
}
}
}
fn reply_to(challenge: Option<&NSURLAuthenticationChallenge>) -> Reply {
/// `tab`: the tab of the web view that was challenged, whose login is the
/// only one it may get. None (a view of no tab): no login at all.
fn reply_to(challenge: Option<&NSURLAuthenticationChallenge>, tab: Option<u64>) -> Reply {
let Some(challenge) = challenge else {
return Reply::default();
};
@@ -762,10 +926,13 @@ mod imp {
let failed = failure_url(challenge);
let saved = SAVED
.try_with(|saved| saved.try_borrow().ok().and_then(|saved| saved.clone()))
.try_with(|saved| saved.try_borrow().ok().map(|saved| saved.clone()))
.ok()
.flatten();
let rejected = REJECTED.try_with(Cell::get).unwrap_or(false);
.flatten()
.unwrap_or_default()
.into_iter()
.filter(|(t, _)| Some(*t) == tab)
.collect::<Vec<_>>();
let asked = Challenge {
basic,
proxy,
@@ -775,8 +942,14 @@ mod imp {
previous_failures: previous_failures as i64,
failed: failed.as_ref(),
};
match (decide(&asked, saved.as_ref(), rejected), saved) {
(ChallengeAnswer::UseCredential, Some(saved)) => {
let picked = pick(&asked, &saved);
let rejected = picked.is_some_and(|(tab, _)| {
REJECTED
.try_with(|rejected| rejected.try_borrow().is_ok_and(|r| r.contains(&tab)))
.unwrap_or(false)
});
match (decide(&asked, picked.map(|(_, s)| s), rejected), picked) {
(ChallengeAnswer::UseCredential, Some((_, saved))) => {
let user = NSString::from_str(&saved.username);
let password = NSString::from_str(&saved.password);
// None: WebKit uses it for this request only and stores
@@ -797,26 +970,32 @@ mod imp {
Some(credential) => Reply {
disposition: NSURLSessionAuthChallengeDisposition::UseCredential,
credential: Some(credential),
report: false,
report: None,
},
None => Reply::default(),
}
}
(ChallengeAnswer::CancelAndReport, _) => {
let _ = REJECTED.try_with(|rejected| rejected.set(true));
(ChallengeAnswer::CancelAndReport, Some((tab, _))) => {
let _ = REJECTED.try_with(|rejected| {
if let Ok(mut rejected) = rejected.try_borrow_mut() {
rejected.push(tab);
}
});
eprintln!("codeman-desktop: {host}:{port} refused the saved login; not sending it again");
Reply {
disposition: NSURLSessionAuthChallengeDisposition::CancelAuthenticationChallenge,
credential: None,
report: true,
report: Some(tab),
}
}
(ChallengeAnswer::Cancel, _) => Reply {
disposition: NSURLSessionAuthChallengeDisposition::CancelAuthenticationChallenge,
credential: None,
report: false,
report: None,
},
(ChallengeAnswer::Default | ChallengeAnswer::UseCredential, _) => Reply::default(),
(ChallengeAnswer::Default | ChallengeAnswer::UseCredential | ChallengeAnswer::CancelAndReport, _) => {
Reply::default()
}
}
})
}
@@ -833,7 +1012,7 @@ mod imp {
Url::parse(&rust_string(&*text?)?).ok()
}
fn notify_rejected() {
fn notify_rejected(tab: u64) {
// Cloned out first: the handler may call `set_credentials` or
// `set_auth_rejected_handler`, which would find the cell borrowed.
let handler = ON_REJECTED
@@ -841,7 +1020,7 @@ mod imp {
.ok()
.flatten();
if let Some(handler) = handler {
if catch_unwind(AssertUnwindSafe(|| handler())).is_err() {
if catch_unwind(AssertUnwindSafe(|| handler(tab))).is_err() {
eprintln!("codeman-desktop: the login-refused handler panicked");
}
}
@@ -1074,4 +1253,45 @@ mod tests {
// gets a first line of the app's own, never its own text in bold.
assert_eq!(dialog_title(None), "An embedded page says:");
}
#[test]
fn each_tab_answers_for_its_own_server() {
let saved = vec![
(1, saved("http://127.0.0.1:3000/")),
(2, saved("http://127.0.0.1:5000/")),
(3, saved("http://h:3000/")),
(4, saved("http://h:3000/codeman/")),
];
let at = |port: i64, host: &'static str, failed: &Url| {
let c = challenge("http", host, port, 0, Some(failed));
pick(&c, &saved).map(|(tab, _)| tab)
};
assert_eq!(at(3000, "127.0.0.1", &url("http://127.0.0.1:3000/api/status")), Some(1));
assert_eq!(at(5000, "127.0.0.1", &url("http://127.0.0.1:5000/api/status")), Some(2));
assert_eq!(at(4000, "127.0.0.1", &url("http://127.0.0.1:4000/api/status")), None);
// Below a base path the deeper server wins; elsewhere the root one.
assert_eq!(at(3000, "h", &url("http://h:3000/codeman/api/status")), Some(4));
assert_eq!(at(3000, "h", &url("http://h:3000/api/status")), Some(3));
// A web tab under either is nobody's.
assert_eq!(at(3000, "h", &url("http://h:3000/webview/cap/")), None);
assert_eq!(at(3000, "h", &url("http://h:3000/codeman/webview/cap/")), None);
let none: Vec<(u64, BasicCredentials)> = Vec::new();
let c = challenge("http", "h", 3000, 0, None);
assert!(pick(&c, &none).is_none());
}
#[test]
fn cookies_go_with_their_host() {
assert!(cookie_for_host("127.0.0.1", "127.0.0.1"));
assert!(cookie_for_host("Studio.Example.ts.net", "studio.example.ts.net"));
assert!(cookie_for_host(".example.ts.net", "studio.example.ts.net"));
assert!(cookie_for_host(".example.ts.net", "example.ts.net"));
assert!(cookie_for_host("::1", "[::1]"));
assert!(!cookie_for_host("atlas.example.ts.net", "studio.example.ts.net"));
assert!(!cookie_for_host(".other.ts.net", "studio.example.ts.net"));
assert!(!cookie_for_host("example.ts.net", "studio.example.ts.net"));
assert!(!cookie_for_host("localhost", "127.0.0.1"));
assert!(!cookie_for_host("", "127.0.0.1"));
assert!(!cookie_for_host(".ample.ts.net", "studio.example.ts.net"));
}
}
+2235 -689
View File
File diff suppressed because it is too large. Load diff
+225 -2
View File
@@ -3,6 +3,8 @@
use muda::accelerator::{Accelerator, Code, Modifiers};
use muda::{AboutMetadata, CheckMenuItem, Menu, MenuItem, PredefinedMenuItem, Submenu};
use crate::tabs::{PALETTE, PALETTE_NAMES};
use crate::config::Config;
use crate::keep_awake::{self, Mode};
use crate::logo::{self, BlinkStyle, Signal};
@@ -21,11 +23,124 @@ pub mod menu_id {
pub const DEVTOOLS: &str = "devtools";
pub const HELP_DOCS: &str = "help-docs";
pub const HELP_GITHUB: &str = "help-github";
pub const TAB_NEW: &str = "tab-new";
pub const TAB_CLOSE: &str = "tab-close";
pub const TAB_REOPEN: &str = "tab-reopen";
pub const TAB_OVERVIEW: &str = "tab-overview";
pub const TAB_NEXT: &str = "tab-next";
pub const TAB_PREVIOUS: &str = "tab-previous";
pub const WINDOW_CLOSE: &str = "window-close";
/// `tab-key-<n>`: the tab ⌘n selects (tabs::index_of_key).
pub const TAB_KEY_PREFIX: &str = "tab-key-";
/// `tab-menu:<tab>:<action>`: an item of a tab's right-click menu.
pub const TAB_MENU_PREFIX: &str = "tab-menu:";
}
/// What a tab's right-click menu asks for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TabAction {
Rename,
/// A palette colour, by index into `tabs::PALETTE`.
Color(usize),
Reload,
/// Show the connect page in this tab (another server, or the same with
/// another login).
Reconnect,
Close,
CloseOthers,
}
impl TabAction {
fn id(self, tab: u64) -> String {
let action = match self {
TabAction::Rename => "rename".to_string(),
TabAction::Color(i) => format!("color-{i}"),
TabAction::Reload => "reload".to_string(),
TabAction::Reconnect => "reconnect".to_string(),
TabAction::Close => "close".to_string(),
TabAction::CloseOthers => "close-others".to_string(),
};
format!("{}{tab}:{action}", menu_id::TAB_MENU_PREFIX)
}
/// The tab and action of a right-click menu item's id.
pub fn parse(id: &str) -> Option<(u64, TabAction)> {
let (tab, action) = id.strip_prefix(menu_id::TAB_MENU_PREFIX)?.split_once(':')?;
let tab = tab.parse().ok()?;
let action = match action {
"rename" => TabAction::Rename,
"reload" => TabAction::Reload,
"reconnect" => TabAction::Reconnect,
"close" => TabAction::Close,
"close-others" => TabAction::CloseOthers,
other => {
let i: usize = other.strip_prefix("color-")?.parse().ok()?;
(i < PALETTE.len()).then_some(TabAction::Color(i))?
}
};
Some((tab, action))
}
}
/// The ⌘ number of a `tab-key-<n>` item.
pub fn tab_key(id: &str) -> Option<usize> {
id.strip_prefix(menu_id::TAB_KEY_PREFIX)?
.parse()
.ok()
.filter(|k| (1..=9).contains(k))
}
/// The right-click menu of one tab. `server`: the tab shows a server (Reload
/// and Connect to Another Server make sense); `others`: there are other tabs.
pub fn tab_context_menu(tab: u64, color: &str, server: bool, others: bool) -> muda::Result<Menu> {
let menu = Menu::new();
menu.append(&MenuItem::with_id(
TabAction::Rename.id(tab),
"Rename Tab\u{2026}",
true,
None,
))?;
let colors = Submenu::new("Tab Color", true);
for (i, (value, name)) in PALETTE.iter().zip(PALETTE_NAMES).enumerate() {
let chosen = value.eq_ignore_ascii_case(color);
colors.append(&CheckMenuItem::with_id(
TabAction::Color(i).id(tab),
name,
true,
chosen,
None,
))?;
}
menu.append(&colors)?;
menu.append(&PredefinedMenuItem::separator())?;
menu.append(&MenuItem::with_id(TabAction::Reload.id(tab), "Reload", server, None))?;
menu.append(&MenuItem::with_id(
TabAction::Reconnect.id(tab),
"Connect This Tab to Another Server\u{2026}",
server,
None,
))?;
menu.append(&PredefinedMenuItem::separator())?;
menu.append(&MenuItem::with_id(TabAction::Close.id(tab), "Close Tab", true, None))?;
menu.append(&MenuItem::with_id(
TabAction::CloseOthers.id(tab),
"Close Other Tabs",
others,
None,
))?;
Ok(menu)
}
pub struct AppMenu {
pub bar: Menu,
pub window_menu: Submenu,
/// Server: the tab commands, then one item per tab (`set_tabs`).
server_menu: Submenu,
/// ⌘1 to ⌘9, made once and shown as many as there are tabs.
tab_items: Vec<CheckMenuItem>,
/// How many of `tab_items` are in the menu.
tab_items_shown: usize,
pub reopen: MenuItem,
pub help_menu: Submenu,
pub start_fullscreen: CheckMenuItem,
/// The one switch for the logo. None on a Mac without a lit logo, which has no
@@ -120,6 +235,34 @@ fn build_keep_awake(config: &Config) -> muda::Result<(Submenu, KeepAwakeMenu)> {
))
}
impl AppMenu {
/// One item per tab under Server, as (name, in front), with ⌘1 to ⌘8 for
/// the first eight and ⌘9 for the last (`tabs::key_of`). Items past nine
/// tabs are left out, as Safari does.
pub fn set_tabs(&mut self, tabs: &[(String, bool)]) {
let len = tabs.len();
let shown: Vec<(usize, &(String, bool))> = tabs
.iter()
.enumerate()
.filter_map(|(i, t)| crate::tabs::key_of(i, len).map(|k| (k, t)))
.collect();
for item in self.tab_items.iter().take(self.tab_items_shown) {
let _ = self.server_menu.remove(item);
}
self.tab_items_shown = 0;
// Appended in key order, which is tab order.
for (key, (name, active)) in shown {
if let Some(item) = self.tab_items.get(key - 1) {
item.set_text(name);
item.set_checked(*active);
if self.server_menu.append(item).is_ok() {
self.tab_items_shown = self.tab_items_shown.max(key);
}
}
}
}
}
pub fn build_menu(config: &Config) -> muda::Result<AppMenu> {
let bar = Menu::new();
let about = PredefinedMenuItem::about(
@@ -243,6 +386,52 @@ pub fn build_menu(config: &Config) -> muda::Result<AppMenu> {
logo_switch = Some(switch);
logo_lid = Some(lid);
}
let cmd = |code| Some(Accelerator::new(Modifiers::META, code));
let cmd_shift = |code| Some(Accelerator::new(Modifiers::META | Modifiers::SHIFT, code));
let reopen = MenuItem::with_id(menu_id::TAB_REOPEN, "Reopen Closed Tab", false, cmd_shift(Code::KeyT));
let server_menu = Submenu::with_items(
"Server",
true,
&[
&MenuItem::with_id(menu_id::TAB_NEW, "New Server Tab", true, cmd(Code::KeyT)),
&MenuItem::with_id(menu_id::TAB_CLOSE, "Close Tab", true, cmd(Code::KeyW)),
&reopen,
&PredefinedMenuItem::separator(),
&MenuItem::with_id(menu_id::TAB_OVERVIEW, "Show All Servers", true, cmd(Code::Digit0)),
&MenuItem::with_id(
menu_id::TAB_PREVIOUS,
"Show Previous Tab",
true,
cmd_shift(Code::BracketLeft),
),
&MenuItem::with_id(menu_id::TAB_NEXT, "Show Next Tab", true, cmd_shift(Code::BracketRight)),
&PredefinedMenuItem::separator(),
],
)?;
const DIGITS: [Code; 9] = [
Code::Digit1,
Code::Digit2,
Code::Digit3,
Code::Digit4,
Code::Digit5,
Code::Digit6,
Code::Digit7,
Code::Digit8,
Code::Digit9,
];
let tab_items = DIGITS
.iter()
.enumerate()
.map(|(i, code)| {
CheckMenuItem::with_id(
format!("{}{}", menu_id::TAB_KEY_PREFIX, i + 1),
"",
true,
false,
cmd(*code),
)
})
.collect();
let window_menu = Submenu::with_items(
"Window",
true,
@@ -250,7 +439,9 @@ pub fn build_menu(config: &Config) -> muda::Result<AppMenu> {
&PredefinedMenuItem::minimize(None),
&PredefinedMenuItem::maximize(None),
&PredefinedMenuItem::separator(),
&PredefinedMenuItem::close_window(None),
// Not the predefined Close Window: ⌘W closes a tab (Server menu),
// as in Safari, so closing the window is ⇧⌘W.
&MenuItem::with_id(menu_id::WINDOW_CLOSE, "Close Window", true, cmd_shift(Code::KeyW)),
&PredefinedMenuItem::separator(),
&PredefinedMenuItem::bring_all_to_front(None),
],
@@ -263,10 +454,14 @@ pub fn build_menu(config: &Config) -> muda::Result<AppMenu> {
&MenuItem::with_id(menu_id::HELP_GITHUB, "Codeman on GitHub", true, None),
],
)?;
bar.append_items(&[&app_menu, &edit, &view, &window_menu, &help_menu])?;
bar.append_items(&[&app_menu, &edit, &view, &server_menu, &window_menu, &help_menu])?;
Ok(AppMenu {
bar,
window_menu,
server_menu,
tab_items,
tab_items_shown: 0,
reopen,
help_menu,
start_fullscreen,
logo_switch,
@@ -275,3 +470,31 @@ pub fn build_menu(config: &Config) -> muda::Result<AppMenu> {
logo_lid,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tab_menu_ids_round_trip() {
for action in [
TabAction::Rename,
TabAction::Color(0),
TabAction::Color(5),
TabAction::Reload,
TabAction::Reconnect,
TabAction::Close,
TabAction::CloseOthers,
] {
assert_eq!(TabAction::parse(&action.id(42)), Some((42, action)));
}
assert_eq!(TabAction::parse("tab-menu:42:color-6"), None);
assert_eq!(TabAction::parse("tab-menu:x:close"), None);
assert_eq!(TabAction::parse("tab-menu:42:other"), None);
assert_eq!(TabAction::parse("reload"), None);
assert_eq!(tab_key("tab-key-1"), Some(1));
assert_eq!(tab_key("tab-key-9"), Some(9));
assert_eq!(tab_key("tab-key-0"), None);
assert_eq!(tab_key("tab-key-10"), None);
}
}
+229
View File
@@ -826,6 +826,141 @@ pub fn parse_ipc(frame_url: &str, body: &str, phase: &Phase, is_main_window: boo
Some(Ipc::Host(cmd))
}
/// The tab strip across the top of the window (assets/tabs.html).
pub const STRIP_PAGE: &str = "codemanapp://localhost/tabs.html";
/// The overview of every server (assets/overview.html).
pub const OVERVIEW_PAGE: &str = "codemanapp://localhost/overview.html";
/// What the tab strip asks for. Tab ids are the app's own numbers; a stale or
/// made-up one matches no tab and does nothing.
#[derive(Debug, PartialEq, Eq)]
pub enum StripCmd {
Ready,
Select(u64),
Close(u64),
New,
Overview,
/// Right-click on a tab: the native menu for it.
Menu(u64),
/// The name the user typed (cleaned by `tabs::clean_name`; empty puts the
/// default back).
Rename {
id: u64,
name: String,
},
Move {
id: u64,
to: usize,
},
/// A rename started: the strip takes the keyboard for its name field.
Editing,
/// A mouse-down on the strip's empty space: drag the window.
Drag,
/// A double-click there: what a title bar double-click does.
Zoom,
}
/// What the overview asks for.
#[derive(Debug, PartialEq, Eq)]
pub enum OverviewCmd {
Ready,
Open(u64),
/// Show that tab and select the session in Codeman's page
/// (`tabs::is_session_id` is checked before it goes anywhere).
OpenSession {
tab: u64,
session: String,
},
New,
Retry(u64),
}
#[derive(Deserialize)]
#[serde(tag = "cmd", rename_all = "camelCase", deny_unknown_fields)]
enum RawStrip {
Ready,
Select { id: u64 },
Close { id: u64 },
New,
Overview,
Menu { id: u64 },
Rename { id: u64, name: String },
Move { id: u64, to: usize },
Editing,
Drag,
Zoom,
}
#[derive(Deserialize)]
#[serde(tag = "cmd", rename_all = "camelCase", deny_unknown_fields)]
enum RawOverview {
Ready,
Open { tab: u64 },
OpenSession { tab: u64, session: String },
New,
Retry { tab: u64 },
}
/// Whether `frame_url` is exactly the bundled page `page` (a query or
/// fragment does not matter).
fn is_bundled_page(frame_url: &str, page: &str) -> bool {
let (Ok(frame), Ok(page)) = (Url::parse(frame_url), Url::parse(page)) else {
return false;
};
frame.scheme() == APP_SCHEME && frame.host_str() == page.host_str() && frame.path() == page.path()
}
/// A message from the tab strip. Only its own page in its own web view is
/// listened to: the caller passes only what came from the strip's web view,
/// and the frame must be the strip page.
pub fn parse_strip_ipc(frame_url: &str, body: &str) -> Option<StripCmd> {
if body.len() > MAX_MESSAGE_LEN || !is_bundled_page(frame_url, STRIP_PAGE) {
return None;
}
Some(match serde_json::from_str::<RawStrip>(body).ok()? {
RawStrip::Ready => StripCmd::Ready,
RawStrip::Select { id } => StripCmd::Select(id),
RawStrip::Close { id } => StripCmd::Close(id),
RawStrip::New => StripCmd::New,
RawStrip::Overview => StripCmd::Overview,
RawStrip::Menu { id } => StripCmd::Menu(id),
RawStrip::Rename { id, name } if name.len() <= MAX_FIELD_LEN => StripCmd::Rename { id, name },
RawStrip::Move { id, to } => StripCmd::Move { id, to },
RawStrip::Editing => StripCmd::Editing,
RawStrip::Drag => StripCmd::Drag,
RawStrip::Zoom => StripCmd::Zoom,
RawStrip::Rename { .. } => return None,
})
}
/// A message from the overview, under the same rule as the strip's.
pub fn parse_overview_ipc(frame_url: &str, body: &str) -> Option<OverviewCmd> {
if body.len() > MAX_MESSAGE_LEN || !is_bundled_page(frame_url, OVERVIEW_PAGE) {
return None;
}
Some(match serde_json::from_str::<RawOverview>(body).ok()? {
RawOverview::Ready => OverviewCmd::Ready,
RawOverview::Open { tab } => OverviewCmd::Open(tab),
RawOverview::OpenSession { tab, session } if session.len() <= MAX_FIELD_LEN => {
OverviewCmd::OpenSession { tab, session }
}
RawOverview::New => OverviewCmd::New,
RawOverview::Retry { tab } => OverviewCmd::Retry(tab),
RawOverview::OpenSession { .. } => return None,
})
}
/// The navigations the strip's and the overview's web views allow: their own
/// bundled page and nothing else, so neither can ever show a server's page or
/// another site.
pub fn bundled_navigation(target: &str, page: &str) -> Navigation {
if is_bundled_page(target, page) {
Navigation::Allow
} else {
Navigation::Block
}
}
/// Only http(s) URLs ever reach the default browser (never `file:`, a custom
/// app scheme, or anything `open` would hand to another program).
pub fn external_url(target: &str) -> Option<Url> {
@@ -1886,4 +2021,98 @@ mod tests {
assert!(external_url("codemanapp://localhost/").is_none());
assert!(external_url("vscode://file/x").is_none());
}
#[test]
fn strip_messages_only_from_the_strip_page() {
let strip = STRIP_PAGE;
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"ready"}"#), Some(StripCmd::Ready));
assert_eq!(
parse_strip_ipc(strip, r#"{"cmd":"select","id":3}"#),
Some(StripCmd::Select(3))
);
assert_eq!(
parse_strip_ipc(strip, r#"{"cmd":"close","id":3}"#),
Some(StripCmd::Close(3))
);
assert_eq!(
parse_strip_ipc(strip, r#"{"cmd":"menu","id":3}"#),
Some(StripCmd::Menu(3))
);
assert_eq!(
parse_strip_ipc(strip, r#"{"cmd":"rename","id":3,"name":"studio"}"#),
Some(StripCmd::Rename {
id: 3,
name: "studio".into()
})
);
assert_eq!(
parse_strip_ipc(strip, r#"{"cmd":"move","id":3,"to":0}"#),
Some(StripCmd::Move { id: 3, to: 0 })
);
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"drag"}"#), Some(StripCmd::Drag));
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"zoom"}"#), Some(StripCmd::Zoom));
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"editing"}"#), Some(StripCmd::Editing));
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"new"}"#), Some(StripCmd::New));
assert_eq!(
parse_strip_ipc(strip, r#"{"cmd":"overview"}"#),
Some(StripCmd::Overview)
);
assert_eq!(
parse_strip_ipc("codemanapp://localhost/tabs.html?x=1", r#"{"cmd":"new"}"#),
Some(StripCmd::New)
);
// Other frames, other pages, other shapes.
assert_eq!(parse_strip_ipc(CONNECT_PAGE, r#"{"cmd":"new"}"#), None);
assert_eq!(parse_strip_ipc(OVERVIEW_PAGE, r#"{"cmd":"new"}"#), None);
assert_eq!(parse_strip_ipc("http://localhost/tabs.html", r#"{"cmd":"new"}"#), None);
assert_eq!(parse_strip_ipc("codemanapp://evil/tabs.html", r#"{"cmd":"new"}"#), None);
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"select","id":-1}"#), None);
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"select","id":"3"}"#), None);
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"connect","url":"http://x/"}"#), None);
let long = format!(
r#"{{"cmd":"rename","id":1,"name":"{}"}}"#,
"x".repeat(MAX_FIELD_LEN + 1)
);
assert_eq!(parse_strip_ipc(strip, &long), None);
}
#[test]
fn overview_messages_only_from_the_overview_page() {
let page = OVERVIEW_PAGE;
assert_eq!(parse_overview_ipc(page, r#"{"cmd":"ready"}"#), Some(OverviewCmd::Ready));
assert_eq!(
parse_overview_ipc(page, r#"{"cmd":"open","tab":2}"#),
Some(OverviewCmd::Open(2))
);
assert_eq!(
parse_overview_ipc(page, r#"{"cmd":"retry","tab":2}"#),
Some(OverviewCmd::Retry(2))
);
assert_eq!(parse_overview_ipc(page, r#"{"cmd":"new"}"#), Some(OverviewCmd::New));
assert_eq!(
parse_overview_ipc(page, r#"{"cmd":"openSession","tab":2,"session":"abc-1"}"#),
Some(OverviewCmd::OpenSession {
tab: 2,
session: "abc-1".into()
})
);
assert_eq!(parse_overview_ipc(STRIP_PAGE, r#"{"cmd":"new"}"#), None);
assert_eq!(parse_overview_ipc(CONNECT_PAGE, r#"{"cmd":"ready"}"#), None);
assert_eq!(parse_overview_ipc(page, r#"{"cmd":"select","id":1}"#), None);
}
#[test]
fn bundled_pages_navigate_nowhere_else() {
assert_eq!(bundled_navigation(STRIP_PAGE, STRIP_PAGE), Navigation::Allow);
assert_eq!(bundled_navigation(OVERVIEW_PAGE, STRIP_PAGE), Navigation::Block);
assert_eq!(bundled_navigation(CONNECT_PAGE, STRIP_PAGE), Navigation::Block);
assert_eq!(
bundled_navigation("http://127.0.0.1:3000/", STRIP_PAGE),
Navigation::Block
);
assert_eq!(bundled_navigation("about:blank", OVERVIEW_PAGE), Navigation::Block);
// The connect page's own gate does not admit the two new pages.
assert!(!is_connect_page(&Url::parse(STRIP_PAGE).unwrap()));
assert!(!is_connect_page(&Url::parse(OVERVIEW_PAGE).unwrap()));
}
}
+650
View File
@@ -0,0 +1,650 @@
//! Server tabs: the pure half. One window holds a tab per Codeman server (or a
//! "New server" tab that shows the connect page), a strip across the top of
//! the window draws them (`assets/tabs.html`), and an overview of every server
//! (`assets/overview.html`) can take the place of the active tab. Everything
//! here is a decision with no window behind it, so it is unit-tested on its own:
//! names, colours, order, which data store a server's pages use, and the state
//! the two pages are sent.
use serde::Serialize;
use url::{Host, Url};
use crate::agents::{Detail, SessionState};
/// The height of the tab strip, in points. The window's other web views start
/// below it.
pub const STRIP_HEIGHT: f64 = 38.0;
/// Where the window's traffic lights go so they sit centred in the strip: the
/// close button's left edge and the buttons' centre line, in points.
pub const TRAFFIC_LIGHTS: (f64, f64) = (14.0, 19.0);
/// The longest tab name the strip accepts, in characters.
pub const MAX_NAME: usize = 40;
/// How many session rows a card of the overview gets.
pub const OVERVIEW_ROWS: usize = 4;
/// How many closed tabs Reopen Closed Tab remembers.
pub const MAX_CLOSED: usize = 10;
/// The colours a new tab is given, in turn: violet, cyan, emerald, pink,
/// amber, slate. None of them is the red, amber dot or blue of a status badge
/// at the same lightness, so a stripe never reads as an alert.
pub const PALETTE: [&str; 6] = ["#a78bfa", "#22d3ee", "#34d399", "#f472b6", "#f59e0b", "#94a3b8"];
/// The names the right-click menu gives the palette, in the same order.
pub const PALETTE_NAMES: [&str; 6] = ["Violet", "Cyan", "Green", "Pink", "Amber", "Slate"];
/// A colour the strip may draw: `#rrggbb` and nothing else, so a value read
/// from the settings file can never carry CSS.
pub fn is_color(value: &str) -> bool {
value.len() == 7 && value.starts_with('#') && value[1..].bytes().all(|b| b.is_ascii_hexdigit())
}
/// The first palette colour no open tab uses, else the palette again in turn.
pub fn next_color<'a>(used: impl IntoIterator<Item = &'a str>) -> String {
let used: Vec<String> = used.into_iter().map(str::to_ascii_lowercase).collect();
PALETTE
.iter()
.find(|c| !used.iter().any(|u| u == *c))
.copied()
.unwrap_or(PALETTE[used.len() % PALETTE.len()])
.to_string()
}
/// What a tab is called until the user names it: `This Mac` for a server on
/// loopback, else the first label of its host name (`studio` for
/// `studio.example.ts.net`), or the whole address for an IP literal. A port
/// other than Codeman's 3000 (or the scheme's own) is added, so two servers on
/// one machine do not look alike.
pub fn default_name(url: &Url) -> String {
let base = match url.host() {
_ if crate::policy::is_loopback(url) => "This Mac".to_string(),
Some(Host::Domain(name)) => name
.split('.')
.next()
.filter(|l| !l.is_empty())
.unwrap_or(name)
.to_string(),
Some(Host::Ipv4(ip)) => ip.to_string(),
Some(Host::Ipv6(ip)) => format!("[{ip}]"),
None => url.as_str().to_string(),
};
match url.port() {
Some(port) if port != 3000 => format!("{base}:{port}"),
_ => base,
}
}
/// A name the user typed, cleaned: trimmed, control characters dropped, cut at
/// `MAX_NAME` characters. None when nothing is left, which puts the default
/// name back.
pub fn clean_name(raw: &str) -> Option<String> {
let kept: String = raw.chars().filter(|c| !c.is_control()).collect();
let trimmed: String = kept.trim().chars().take(MAX_NAME).collect();
let trimmed = trimmed.trim_end().to_string();
(!trimmed.is_empty()).then_some(trimmed)
}
/// What a rename the strip finished does to a tab's own name: None, nothing
/// (it ended without a change: Escape, or Enter on the same text, sends the
/// name the tab shows, and kept, that would pin "New server" to a tab before
/// it has a server); `Some(None)`, back to the default name (an empty name,
/// or the default typed out); `Some(Some(name))`, that name.
pub fn renamed(typed: &str, shown: &str, default: Option<&str>) -> Option<Option<String>> {
let Some(name) = clean_name(typed) else {
return Some(None);
};
if clean_name(shown).as_deref() == Some(name.as_str()) {
return None;
}
Some((default != Some(name.as_str())).then_some(name))
}
/// The identifier of the WebKit data store (cookies and local storage) that a
/// server's pages use. Each server gets one of its own, so two servers on one
/// host (a Codeman on port 3000 and a beta on 5000) never share a login cookie,
/// which carries the same name on both and is not told apart by port. Derived
/// from the server's address, so the same server finds its store, and with it
/// Codeman's per-device settings, at every launch. Two 64-bit FNV-1a hashes
/// with different starting values: stable across Rust releases, which the
/// standard library's hasher is not promised to be.
pub fn store_id(server: &str) -> [u8; 16] {
fn fnv(bytes: &[u8], basis: u64) -> u64 {
bytes
.iter()
.fold(basis, |hash, b| (hash ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3))
}
let bytes = server.as_bytes();
let hi = fnv(bytes, 0xcbf2_9ce4_8422_2325);
let lo = fnv(bytes, 0x8422_2325_cbf2_9ce4 ^ 0x5eed);
let mut id = [0u8; 16];
id[..8].copy_from_slice(&hi.to_be_bytes());
id[8..].copy_from_slice(&lo.to_be_bytes());
// A well-formed UUID: version 8 (custom), RFC 4122 variant.
id[6] = (id[6] & 0x0f) | 0x80;
id[8] = (id[8] & 0x3f) | 0x80;
id
}
/// Where `from` lands when the strip asks to move it to `to`, both indexes
/// into a list of `len`. None for an index out of range or no move.
pub fn moved(len: usize, from: usize, to: usize) -> Option<usize> {
(from < len && to < len && from != to).then_some(to)
}
/// The tab after (or before) `active` in a list of `len`, wrapping around.
pub fn neighbour(len: usize, active: usize, forward: bool) -> Option<usize> {
match len {
0 => None,
_ if forward => Some((active + 1) % len),
_ => Some((active + len - 1) % len),
}
}
/// Which tab to show after closing the one at `closed` (of `len` before the
/// close), when it was the active one: the tab that took its place, else the
/// one before it.
pub fn after_close(len: usize, closed: usize) -> Option<usize> {
match len {
0 | 1 => None,
_ if closed + 1 < len => Some(closed),
_ => Some(closed - 1),
}
}
/// Whether `id` can be handed to Codeman's page as a session id: what Codeman
/// makes (UUIDs) and nothing that could step out of a string.
pub fn is_session_id(id: &str) -> bool {
!id.is_empty() && id.len() <= 128 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
/// What a tab shows.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum Kind {
/// The connect page, nothing chosen yet.
Connect,
/// A server's page is on its way; the connect page still shows.
Loading,
/// A server's page.
Server,
}
/// What the badges of a tab are counted from: the last status read of its
/// server, and whether that server answers at all.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Seen {
pub detail: Option<Detail>,
/// The last few reads failed.
pub offline: bool,
/// The server refused the login: nothing is asked any more.
pub refused: bool,
}
/// One tab as the strip and the overview see it.
#[derive(Debug, Clone)]
pub struct View<'a> {
pub id: u64,
pub name: String,
pub color: &'a str,
pub kind: Kind,
pub url: Option<&'a Url>,
pub version: Option<&'a str>,
pub seen: &'a Seen,
}
#[derive(Debug, Serialize, PartialEq, Eq, Default)]
#[serde(rename_all = "camelCase")]
pub struct Counts {
pub needs_you: usize,
pub waiting: usize,
pub working: usize,
pub sessions: usize,
}
fn counts(seen: &Seen) -> Counts {
let Some(detail) = &seen.detail else {
return Counts::default();
};
let of = |state: SessionState| detail.sessions.iter().filter(|s| s.state == state).count();
Counts {
needs_you: of(SessionState::Needs),
waiting: of(SessionState::Waiting),
working: of(SessionState::Working),
sessions: detail.sessions.len(),
}
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct StripStatus {
working: usize,
waiting: usize,
needs_you: usize,
offline: bool,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct StripTab<'a> {
id: u64,
name: &'a str,
color: &'a str,
active: bool,
kind: Kind,
local: bool,
url: Option<&'a str>,
key: Option<usize>,
status: StripStatus,
}
/// The ⌘ number of the tab at `index`: ⌘1 to ⌘8 for the first eight, ⌘9 for
/// the last one, as in Safari.
pub fn key_of(index: usize, len: usize) -> Option<usize> {
match index {
_ if index + 1 == len && len > 8 => Some(9),
i if i < 8 => Some(i + 1),
_ => None,
}
}
/// The tab ⌘`key` selects in a list of `len`.
pub fn index_of_key(key: usize, len: usize) -> Option<usize> {
match key {
9 if len > 0 => Some(len - 1),
k @ 1..=8 if k <= len => Some(k - 1),
_ => None,
}
}
/// The strip's whole state (`assets/tabs.html`, message `state`).
pub fn strip_state(tabs: &[View<'_>], active: Option<usize>, overview: bool, fullscreen: bool) -> serde_json::Value {
let len = tabs.len();
let list: Vec<StripTab<'_>> = tabs
.iter()
.enumerate()
.map(|(i, t)| {
let c = counts(t.seen);
StripTab {
id: t.id,
name: &t.name,
color: t.color,
active: !overview && active == Some(i),
kind: t.kind,
local: t.url.is_some_and(crate::policy::is_loopback),
url: t.url.map(Url::as_str),
key: key_of(i, len),
status: StripStatus {
working: c.working,
waiting: c.waiting,
needs_you: c.needs_you,
offline: t.kind == Kind::Server && t.seen.offline,
},
}
})
.collect();
serde_json::json!({
"type": "state",
"tabs": list,
"overviewActive": overview,
"fullscreen": fullscreen,
})
}
#[derive(Serialize)]
struct Row<'a> {
id: &'a str,
name: &'a str,
state: SessionState,
text: &'a str,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Card<'a> {
tab: u64,
name: &'a str,
color: &'a str,
url: Option<&'a str>,
local: bool,
key: Option<usize>,
version: Option<&'a str>,
kind: Kind,
offline: bool,
refused: bool,
sessions: Vec<Row<'a>>,
counts: Counts,
}
/// The overview's whole state (`assets/overview.html`, message `state`): a
/// card per tab, the servers that need someone first, then those with an agent
/// waiting, then the rest in tab order. Each card lists its sessions most
/// urgent first, `OVERVIEW_ROWS` at most.
pub fn overview_state(tabs: &[View<'_>]) -> serde_json::Value {
let len = tabs.len();
let mut cards: Vec<(usize, Card<'_>)> = tabs
.iter()
.enumerate()
.map(|(i, t)| {
let mut rows: Vec<Row<'_>> = t
.seen
.detail
.iter()
.flat_map(|d| d.sessions.iter())
.map(|s| Row {
id: &s.id,
name: &s.name,
state: s.state,
text: &s.text,
})
.collect();
rows.sort_by_key(|r| r.state.rank());
rows.truncate(OVERVIEW_ROWS);
(
i,
Card {
tab: t.id,
name: &t.name,
color: t.color,
url: t.url.map(Url::as_str),
local: t.url.is_some_and(crate::policy::is_loopback),
key: key_of(i, len),
version: t.version,
kind: t.kind,
offline: t.kind == Kind::Server && t.seen.offline,
refused: t.seen.refused,
sessions: rows,
counts: counts(t.seen),
},
)
})
.collect();
cards.sort_by_key(|(i, card)| {
let urgency = match (card.counts.needs_you, card.counts.waiting) {
(n, _) if n > 0 => 0,
(_, w) if w > 0 => 1,
_ => 2,
};
(urgency, *i)
});
let servers: Vec<Card<'_>> = cards.into_iter().map(|(_, c)| c).collect();
serde_json::json!({ "type": "state", "servers": servers })
}
/// The window title while a tab shows: the page's own title, else the tab's
/// name.
pub fn window_title(page_title: Option<&str>, name: &str) -> String {
match page_title.map(str::trim) {
Some(t) if !t.is_empty() => t.to_string(),
_ => name.to_string(),
}
}
/// Whether two server addresses are on the same host (scheme and port aside):
/// the case where, without a data store of their own, they would share a login
/// cookie.
pub fn same_host(a: &Url, b: &Url) -> bool {
match (a.host_str(), b.host_str()) {
(Some(x), Some(y)) => x.eq_ignore_ascii_case(y),
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::agents::SessionRow;
fn u(s: &str) -> Url {
Url::parse(s).unwrap()
}
#[test]
fn colours_are_hex_only() {
assert!(is_color("#a78bfa"));
assert!(is_color("#A78BFA"));
assert!(!is_color("a78bfa"));
assert!(!is_color("#a78bf"));
assert!(!is_color("#a78bfg"));
assert!(!is_color("red;background:url(x)"));
assert!(!is_color("#a78bfa;"));
}
#[test]
fn new_tabs_take_the_first_free_colour() {
assert_eq!(next_color([]), PALETTE[0]);
assert_eq!(next_color([PALETTE[0]]), PALETTE[1]);
assert_eq!(next_color([PALETTE[1], "#A78BFA"]), PALETTE[2]);
let all: Vec<&str> = PALETTE.to_vec();
assert_eq!(next_color(all.clone()), PALETTE[0]);
let mut seven = all;
seven.push(PALETTE[0]);
assert_eq!(next_color(seven), PALETTE[1]);
}
#[test]
fn default_names() {
assert_eq!(default_name(&u("http://127.0.0.1:3000/")), "This Mac");
assert_eq!(default_name(&u("http://localhost:3000/")), "This Mac");
assert_eq!(default_name(&u("http://127.0.0.1:5000/")), "This Mac:5000");
assert_eq!(default_name(&u("https://studio.example.ts.net/")), "studio");
assert_eq!(default_name(&u("http://build-01.lan:3000/")), "build-01");
assert_eq!(default_name(&u("http://192.168.1.40:3000/")), "192.168.1.40");
assert_eq!(
default_name(&u("http://192.168.1.40:8080/codeman/")),
"192.168.1.40:8080"
);
assert_eq!(default_name(&u("http://[fd00::1]:3000/")), "[fd00::1]");
}
#[test]
fn names_are_cleaned() {
assert_eq!(clean_name(" studio ").as_deref(), Some("studio"));
assert_eq!(clean_name("a\u{0}b\nc").as_deref(), Some("abc"));
assert_eq!(clean_name(" "), None);
assert_eq!(clean_name(""), None);
let long = "x".repeat(100);
assert_eq!(clean_name(&long).map(|n| n.chars().count()), Some(MAX_NAME));
// Characters, not bytes: a multi-byte name is not cut inside a character.
let wide = "ü".repeat(60);
assert_eq!(clean_name(&wide).map(|n| n.chars().count()), Some(MAX_NAME));
}
#[test]
fn renames() {
// Escape on a new tab sends back what it shows: nothing changes.
assert_eq!(renamed("New server", "New server", None), None);
assert_eq!(renamed(" studio ", "studio", Some("studio")), None);
assert_eq!(
renamed("prod box", "studio", Some("studio")),
Some(Some("prod box".into()))
);
// The default typed out, or nothing at all, is the default again.
assert_eq!(renamed("studio", "prod box", Some("studio")), Some(None));
assert_eq!(renamed(" ", "prod box", Some("studio")), Some(None));
// A shown name longer than a name may be, sent back unchanged.
let long = "x".repeat(60);
assert_eq!(renamed(&long, &long, None), None);
}
#[test]
fn store_ids_are_stable_and_distinct() {
let a = store_id("http://127.0.0.1:3000/");
assert_eq!(a, store_id("http://127.0.0.1:3000/"));
assert_ne!(a, store_id("http://127.0.0.1:5000/"));
assert_ne!(a, store_id("http://127.0.0.1:3000/x/"));
// Version 8, RFC 4122 variant.
assert_eq!(a[6] >> 4, 8);
assert_eq!(a[8] >> 6, 0b10);
// Pinned, so a change of the hash (which would cost every server its
// local storage) fails here first.
assert_eq!(
store_id(""),
[0xcb, 0xf2, 0x9c, 0xe4, 0x84, 0x22, 0x83, 0x25, 0x84, 0x22, 0x23, 0x25, 0xcb, 0xf2, 0xc2, 0x09]
);
}
#[test]
fn order_helpers() {
assert_eq!(moved(3, 0, 2), Some(2));
assert_eq!(moved(3, 1, 1), None);
assert_eq!(moved(3, 3, 0), None);
assert_eq!(moved(3, 0, 3), None);
assert_eq!(neighbour(3, 2, true), Some(0));
assert_eq!(neighbour(3, 0, false), Some(2));
assert_eq!(neighbour(0, 0, true), None);
assert_eq!(after_close(3, 0), Some(0));
assert_eq!(after_close(3, 2), Some(1));
assert_eq!(after_close(1, 0), None);
}
#[test]
fn command_numbers() {
assert_eq!(key_of(0, 3), Some(1));
assert_eq!(key_of(2, 3), Some(3));
assert_eq!(key_of(7, 12), Some(8));
assert_eq!(key_of(8, 12), None);
assert_eq!(key_of(11, 12), Some(9));
assert_eq!(key_of(8, 9), Some(9));
assert_eq!(index_of_key(1, 3), Some(0));
assert_eq!(index_of_key(3, 3), Some(2));
assert_eq!(index_of_key(4, 3), None);
assert_eq!(index_of_key(9, 3), Some(2));
assert_eq!(index_of_key(9, 0), None);
assert_eq!(index_of_key(0, 3), None);
}
#[test]
fn session_ids() {
assert!(is_session_id("0f8d0215-661e-4a1c-bfad-d7f6fd2ed4b5"));
assert!(!is_session_id(""));
assert!(!is_session_id("a'b"));
assert!(!is_session_id("a\"); alert(1); (\""));
assert!(!is_session_id(&"a".repeat(129)));
}
fn row(id: &str, state: SessionState) -> SessionRow {
SessionRow {
id: id.into(),
name: id.into(),
state,
text: String::new(),
}
}
fn seen(rows: Vec<SessionRow>) -> Seen {
Seen {
detail: Some(Detail { sessions: rows }),
offline: false,
refused: false,
}
}
#[test]
fn strip_state_marks_the_active_tab_and_counts() {
let a = u("http://127.0.0.1:3000/");
let b = u("https://studio.example.ts.net/");
let busy = seen(vec![
row("1", SessionState::Working),
row("2", SessionState::Needs),
row("3", SessionState::Needs),
row("4", SessionState::Waiting),
]);
let none = Seen {
offline: true,
..Seen::default()
};
let tabs = [
View {
id: 1,
name: "This Mac".into(),
color: PALETTE[0],
kind: Kind::Server,
url: Some(&a),
version: None,
seen: &busy,
},
View {
id: 2,
name: "studio".into(),
color: PALETTE[1],
kind: Kind::Server,
url: Some(&b),
version: None,
seen: &none,
},
];
let state = strip_state(&tabs, Some(1), false, true);
assert_eq!(state["type"], "state");
assert_eq!(state["fullscreen"], true);
assert_eq!(state["tabs"][0]["active"], false);
assert_eq!(state["tabs"][1]["active"], true);
assert_eq!(state["tabs"][0]["local"], true);
assert_eq!(state["tabs"][0]["status"]["needsYou"], 2);
assert_eq!(state["tabs"][0]["status"]["waiting"], 1);
assert_eq!(state["tabs"][0]["status"]["working"], 1);
assert_eq!(state["tabs"][1]["status"]["offline"], true);
assert_eq!(state["tabs"][1]["key"], 2);
// The overview takes the place of the active tab.
let state = strip_state(&tabs, Some(1), true, false);
assert_eq!(state["tabs"][1]["active"], false);
assert_eq!(state["overviewActive"], true);
}
#[test]
fn overview_puts_urgent_servers_and_sessions_first() {
let a = u("http://127.0.0.1:3000/");
let b = u("https://studio.example.ts.net/");
let calm = seen(vec![row("w", SessionState::Working), row("i", SessionState::Idle)]);
let urgent = seen(vec![
row("i1", SessionState::Idle),
row("i2", SessionState::Idle),
row("w1", SessionState::Working),
row("n1", SessionState::Needs),
row("y1", SessionState::Waiting),
row("i3", SessionState::Idle),
]);
let tabs = [
View {
id: 10,
name: "This Mac".into(),
color: PALETTE[0],
kind: Kind::Server,
url: Some(&a),
version: Some("1.51.0"),
seen: &calm,
},
View {
id: 11,
name: "studio".into(),
color: PALETTE[1],
kind: Kind::Server,
url: Some(&b),
version: None,
seen: &urgent,
},
];
let state = overview_state(&tabs);
let servers = state["servers"].as_array().unwrap();
assert_eq!(servers[0]["tab"], 11);
assert_eq!(servers[0]["key"], 2);
assert_eq!(servers[1]["tab"], 10);
let rows: Vec<&str> = servers[0]["sessions"]
.as_array()
.unwrap()
.iter()
.map(|r| r["id"].as_str().unwrap())
.collect();
assert_eq!(rows, ["n1", "y1", "w1", "i1"]);
assert_eq!(servers[0]["counts"]["sessions"], 6);
assert_eq!(servers[0]["sessions"][0]["state"], "needs");
assert_eq!(servers[1]["version"], "1.51.0");
}
#[test]
fn titles_and_hosts() {
assert_eq!(window_title(Some(" Codeman "), "atlas"), "Codeman");
assert_eq!(window_title(Some(""), "atlas"), "atlas");
assert_eq!(window_title(None, "atlas"), "atlas");
assert!(same_host(&u("http://127.0.0.1:3000/"), &u("http://127.0.0.1:5000/")));
assert!(same_host(&u("http://Studio.lan:3000/"), &u("https://studio.lan/")));
assert!(!same_host(&u("http://127.0.0.1:3000/"), &u("http://localhost:3000/")));
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "codeman",
"description": "Drive Codeman, the self-hosted session manager for AI coding agents, from inside a Claude Code session: spawn worker sessions, prompt them, wait for them, read their answers, clean up. Acts inside a Codeman-managed session; outside one it only reads saved Codex conversations offline.",
"version": "1.51.1",
"version": "1.51.0",
"author": {
"name": "Ark0N",
"url": "https://github.com/Ark0N"
+1 -11
View File
@@ -927,7 +927,7 @@ program
program
.command('tui')
.argument('[session]', 'attach straight to a session: its number in `codeman tui --list`, or its exact session name')
.argument('[n]', 'attach straight to the nth session of `codeman tui --list`')
.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,16 +940,6 @@ program
return;
}
if (position !== undefined) {
// Digits only is a list number, as it always was; anything else is a session name.
if (!/^\d+$/.test(position)) {
if (position.trim() === '') {
console.error(palette.err('An empty session name matches nothing.'));
process.exitCode = 1;
return;
}
process.exitCode = await runTuiAttach(position);
return;
}
const n = Number.parseInt(position, 10);
if (!Number.isSafeInteger(n) || n < 1) {
console.error(palette.err(`"${position}" is not a session number.`));
+4 -4
View File
@@ -303,8 +303,8 @@ const CLAUDE: CliEntry = {
transcript: 'claude-jsonl',
altScreen: 'strip-full',
echo: { policy: 'buffer', anchor: { kind: 'glyph', glyph: '❯', offset: 2 } },
// Read by `_shouldForwardWheelToApp` (terminal-ui.js) through `window.__codemanWheelForward`;
// forwarding also needs the server-published `cliMouseTracking` flag (#498).
// 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.
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:
// `always` is what keeps `_shouldForwardWheelToApp` (terminal-ui.js) from checking one.
// 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).
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
+6 -15
View File
@@ -596,18 +596,10 @@ 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).
*
* ⚠️ '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.
* ⚠️ 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.
*/
wheelForward: { mode: 'never' | 'version-gated' | 'always'; minVersion?: string };
/**
@@ -1017,15 +1009,14 @@ export interface CliOverlays {
/**
* ⚠️ DECLARED-FOR-LATER: fields no code reads yet.
*
* `accent`, `overlays.credStore`, `capabilities.echo`, `capabilities.keyboardAccessory` and
* `capabilities.maxFrameBytes` all describe FRONTEND
* `accent`, `overlays.credStore`, `capabilities.echo`, `capabilities.wheelForward`,
* `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, and so did `capabilities.wheelForward`, which the browser's wheel
* gate reads through `window.__codemanWheelForward`.
* CLI-management Settings list.
*
* They are declared now because each entry should describe its CLI completely, and because
* transcribing them while the hand-written source is still on screen is when the values are
-52
View File
@@ -1,52 +0,0 @@
/**
* @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;
};
}
+10 -263
View File
@@ -27,11 +27,6 @@
* - **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';
@@ -58,23 +53,6 @@ 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;
@@ -88,33 +66,7 @@ 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;
@@ -153,158 +105,6 @@ 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.
*
@@ -334,25 +134,6 @@ 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;
@@ -393,12 +174,11 @@ 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, starter?: string): Promise<StartResult> {
export function startDeepSeekWeb(dshDir: string, authority: string): Promise<StartResult> {
const run = startLock.then(
() => startDeepSeekWebLocked(dshDir, authority, starter),
() => startDeepSeekWebLocked(dshDir, authority, starter)
() => startDeepSeekWebLocked(dshDir, authority),
() => startDeepSeekWebLocked(dshDir, authority)
);
startLock = run.then(
() => undefined,
@@ -407,24 +187,13 @@ export function startDeepSeekWeb(dshDir: string, authority: string, starter?: st
return run;
}
async function startDeepSeekWebLocked(
dshDir: string,
authority: string,
starter: string | undefined
): Promise<StartResult> {
async function startDeepSeekWebLocked(dshDir: string, authority: string): Promise<StartResult> {
// Reuse only when the running server is BOTH healthy and fenced for the
// 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.
// 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.
if (current) {
if (
!current.cookieFailed &&
current.authority === authority &&
current.starter === starter &&
(await answersHttp(current.port))
) {
if (current.authority === authority && (await answersHttp(current.port))) {
return { ok: true, port: current.port, url: `http://127.0.0.1:${current.port}`, reused: true };
}
await stopDeepSeekWeb();
@@ -454,15 +223,8 @@ async function startDeepSeekWebLocked(
// 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) => {
const text = chunk.toString('utf-8');
if (output.length < OUTPUT_CAP) output += text;
if (banner.length < BANNER_SCAN_CAP) banner += text;
if (output.length < OUTPUT_CAP) output += chunk.toString('utf-8');
};
child.stdout?.on('data', capture);
child.stderr?.on('data', capture);
@@ -479,16 +241,7 @@ async function startDeepSeekWebLocked(
if (current?.child === child) current = null;
});
const running: RunningServer = {
child,
port,
authority,
starter,
output: () => output,
banner: () => banner,
cookie: null,
cookieFailed: false,
};
const running: RunningServer = { child, port, authority, output: () => output };
current = running;
const deadline = Date.now() + READY_TIMEOUT_MS;
@@ -502,12 +255,6 @@ async function startDeepSeekWebLocked(
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));
+1 -8
View File
@@ -4,10 +4,7 @@
* 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) 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.
* `~/.codeman/discord-bridge.json` (sessionId -> threadId, not secret)
* - IO: `DiscordApi` (REST, injected fetch), `DiscordGateway` (inbound WebSocket, injected
* socket factory) and `DiscordBridge` (the rules that tie them to sessions)
*
@@ -30,7 +27,6 @@ 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,
@@ -828,7 +824,6 @@ export interface DiscordBridgeDeps {
}
export class DiscordBridge {
private readonly replies: DiscordReplyDedupe;
private cfg: DiscordConfig = { ...DEFAULT_DISCORD_CONFIG };
private threads: Record<string, string> = {};
private loaded = false;
@@ -862,7 +857,6 @@ 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);
}
@@ -1307,7 +1301,6 @@ export class DiscordBridge {
if (!this.cfg.allowedUserIds.includes(m.author?.id)) return;
const sessionId = Object.keys(this.threads).find((k) => this.threads[k] === m.channel_id);
if (!sessionId) return;
if (!(await this.replies.claim(m.guild_id, m.channel_id, m.id))) return;
const t = this.now();
const prev = this.lastReply.get(sessionId);
if (prev !== undefined && t - prev < REPLY_MIN_INTERVAL_MS) {
-111
View File
@@ -1,111 +0,0 @@
/**
* @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;
}
}
+8 -33
View File
@@ -15,8 +15,7 @@ import { join } from 'node:path';
import { watch as chokidarWatch, type FSWatcher as ChokidarWatcher } from 'chokidar';
import { getErrorMessage, type TeamConfig, type TeamTask, type InboxMessage } from './types.js';
import { closeWatcherOnError } from './utils/close-watcher-on-error.js';
import type { TeamConfig, TeamTask, InboxMessage } from './types.js';
import { LRUMap } from './utils/lru-map.js';
import { TEAM_POLL_INTERVAL_MS, MAX_CACHED_TEAMS, MAX_CACHED_TASKS } from './config/team-config.js';
@@ -37,8 +36,6 @@ 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();
@@ -50,28 +47,11 @@ export class TeamWatcher extends EventEmitter {
start(): void {
if (this.pollTimer) return;
this.poll();
this.pollTimer = setInterval(() => {
this.setupFsWatchers(); // re-creates a watcher an error stopped
this.poll();
}, TEAM_POLL_INTERVAL_MS);
this.pollTimer = setInterval(() => 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,
@@ -86,16 +66,13 @@ export class TeamWatcher extends EventEmitter {
this.teamsWatcher.on('change', teamsHandler);
this.teamsWatcher.on('unlink', teamsHandler);
this.teamsWatcher.on('unlinkDir', teamsHandler);
closeWatcherOnError(this.teamsWatcher, (err) => {
this.teamsWatcher = null;
this.watcherStopped('teams', err);
this.teamsWatcher.on('error', (err) => {
console.warn('[TeamWatcher] chokidar teams watcher error:', err);
});
} catch (err) {
this.watcherStopped('teams', err);
console.warn('[TeamWatcher] Failed to set up teams chokidar watcher, relying on polling:', err);
}
}
private setupTasksWatcher(): void {
try {
this.tasksWatcher = chokidarWatch(this.tasksDir, {
depth: 1,
@@ -107,12 +84,11 @@ 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
closeWatcherOnError(this.tasksWatcher, (err) => {
this.tasksWatcher = null;
this.watcherStopped('tasks', err);
this.tasksWatcher.on('error', (err) => {
console.warn('[TeamWatcher] chokidar tasks watcher error:', err);
});
} catch (err) {
this.watcherStopped('tasks', err);
console.warn('[TeamWatcher] Failed to set up tasks chokidar watcher, relying on polling:', err);
}
}
@@ -137,7 +113,6 @@ export class TeamWatcher extends EventEmitter {
this.taskMtimes.clear();
this.inboxMtimes.clear();
this.sessionToTeam.clear();
this.watchersDown.clear();
}
/** Get all discovered teams */
-10
View File
@@ -153,16 +153,6 @@ 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
}
+14 -72
View File
@@ -1,6 +1,6 @@
/**
* @fileoverview `codeman tui`: the full-screen dashboard plus the two
* non-interactive fast paths (`--list`, `<n|name>`).
* non-interactive fast paths (`--list`, `<n>`).
*
* 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|name>')} to attach.\n`
`Use ${palette.info('codeman tui --list')} for a plain list, or ${palette.info('codeman tui <n>')} to attach.\n`
);
return 1;
}
@@ -2689,72 +2689,17 @@ 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' };
/**
* 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.
* `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.
*/
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> {
export async function runTuiAttach(position: number, 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 {
@@ -2767,14 +2712,11 @@ export async function runTuiAttach(target: number | string, options: TuiRunOptio
process.stderr.write(authHint());
return 1;
}
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`);
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`
);
return 1;
}
const plan = planAttach(row.session.muxName, {
+4 -15
View File
@@ -991,19 +991,6 @@ 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
@@ -1011,7 +998,8 @@ export class TuiClient {
*/
async readDetachKey(): Promise<string | null> {
try {
return parseDetachKey(await this.listKeyTable('prefix'));
const { stdout } = await this.exec('tmux', ['-L', this.socket, 'list-keys', '-T', 'prefix']);
return parseDetachKey(stdout);
} catch {
return null;
}
@@ -1024,7 +1012,8 @@ export class TuiClient {
*/
async readPrefixBinding(key: string, table: TuiKeyTable = 'prefix'): Promise<string | null> {
try {
return parsePrefixBinding(await this.listKeyTable(table), key, table);
const { stdout } = await this.exec('tmux', ['-L', this.socket, 'list-keys', '-T', table]);
return parsePrefixBinding(stdout, key, table);
} catch {
return null;
}
-39
View File
@@ -1,39 +0,0 @@
/**
* @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);
});
}
+3 -3
View File
@@ -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`, `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.
**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.
**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`). ⚠️ 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)
**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)
**Phone toolbar: Enter replaces Shell** (post-1.8.0): inside `@media (max-width: 599px)` `btn-shell` is `display:none` and `btn-enter` takes its slot (`order: 4`); starting a shell moved into the Run dropdown (`Terminal / Shell` → `setRunMode('shell')` → `run()` → `runShell()`, button label "Run SH"). `runMode` is `z.string().max(20)` server-side, so new modes need no schema change. Desktop and tablet keep the green Run Shell button unchanged.
⚠️ **`sendEnterKey()` MUST go through `terminal._core.coreService.triggerDataEvent('\r', true)`** — not `sendInput()`, and never a raw POST to `/api/sessions/:id/input`. `localEchoEnabled` defaults to `MobileDetection.isTouchDevice()`, so on every phone the characters you type are buffered in the `LocalEchoOverlay` and have **never reached the PTY**; the `onData` Enter branch in terminal-ui.js is what flushes `pendingText` first and only then sends `\r` (after an 80ms delay so text lands first). Sending a bare `\r` submits an empty line and strands the typed text on screen, so the button looks dead. Replaying the keypress reuses the overlay flush, the flushed-offset cleanup and the ordering instead of reimplementing them. `KeyboardAccessory.sendKey()` is for escape sequences (arrows/Esc) and is the WRONG template to copy for input. The one deliberate exception: while the CJK field is visible (`#cjkInput.cjk-input-visible`), `onData` drops everything under `window.cjkActive`, so `sendEnterKey()` calls `CjkInput.submit()` instead, which sends what the field holds (a Send on Enter answer, or live text not yet flushed) and then Enter.
⚠️ **`sendEnterKey()` MUST 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.
⚠️ **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.
+3 -29
View File
@@ -4929,11 +4929,6 @@ 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();
}
@@ -9384,7 +9379,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, keepCjkDraft = false } = {}) {
_cleanupPreviousSession(newSessionId, { skipSnapshot = 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
@@ -9437,16 +9432,8 @@ 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') {
if (!(keepCjkDraft && CjkInput.holdUntilEnter)) {
if (this.activeSessionId) CjkInput.stashDraft?.(this.activeSessionId);
CjkInput.clear();
}
CjkInput.clear();
} else {
const cjkEl = document.getElementById('cjkInput');
if (cjkEl) cjkEl.value = '';
@@ -9986,19 +9973,11 @@ 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 {}
@@ -10045,10 +10024,9 @@ class CodemanApp {
// A session tab takes the stage back from any active web tab.
this._hideWebviewLayer?.();
this._cleanupPreviousSession(sessionId, { keepCjkDraft: reloadingSameSession });
this._cleanupPreviousSession(sessionId);
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 });
@@ -10845,7 +10823,6 @@ 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.
@@ -11127,9 +11104,6 @@ class CodemanApp {
this._retireUrlSession();
// Home is a choice to leave the grid too; it is remembered for Tiles.
this.closeTileGrid?.({ keepStored: true, reselect: false });
// A Send on Enter draft goes with its session: the null below hides that
// session from the next _cleanupPreviousSession, which would clear it unstashed.
if (typeof CjkInput !== 'undefined' && this.activeSessionId) CjkInput.stashDraft?.(this.activeSessionId);
// Deselect active session and show welcome screen
this.activeSessionId = null;
try { localStorage.removeItem('codeman-active-session'); } catch {}
+2 -2
View File
@@ -112,7 +112,7 @@ const MOBILE_RESIZE_RETRY_MS = 30000; // Small-viewport resize re-send whi
const AUTO_CLOSE_NOTIFICATION_MS = 8000; // Auto-close browser notifications
const DEFAULT_TOAST_DURATION_MS = 3000; // How long a corner toast stays by default
const MIN_NOTIFICATION_DURATION_MS = 1000; // Shortest configurable toast / browser-notification time
const MAX_NOTIFICATION_DURATION_MS = 300000; // Longest configurable toast / browser-notification time
const MAX_NOTIFICATION_DURATION_MS = 300000; // General UI throttle delay
const TERMINAL_CHUNK_SIZE = 32 * 1024; // 32KB chunks for terminal buffer loading
const TERMINAL_TAIL_SIZE = 1024 * 1024; // 1MB tail for initial load (more scrollback on tab switch)
// A shell's automatic loads (tab select, drop recovery, a tile's load) read
@@ -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; // Wait timeout for terminal sync
const SYNC_WAIT_TIMEOUT_MS = 50; // System stats polling
const TUI_REDRAW_SETTLE_MS = 400; // Grace for a TUI to redraw after a real resize, before fetching its buffer
// Z-index base values for layered floating windows
-5
View File
@@ -743,11 +743,6 @@
"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': '滚轮滚动本地历史',
+1 -9
View File
@@ -13,8 +13,7 @@
<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">
<!-- 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">
<link rel="manifest" href="manifest.json">
<title>Codeman</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Cdefs%3E%3ClinearGradient id='g' x1='0%25' y1='0%25' x2='100%25' y2='100%25'%3E%3Cstop offset='0%25' stop-color='%2360a5fa'/%3E%3Cstop offset='100%25' stop-color='%233b82f6'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect width='32' height='32' rx='6' fill='%230a0a0a'/%3E%3Cpath d='M18 4L8 18h6l-2 10 10-14h-6z' fill='url(%23g)'/%3E%3C/svg%3E">
<link rel="stylesheet" href="styles.css">
@@ -2065,13 +2064,6 @@
</div>
<label class="switch switch-sm"><input type="checkbox" id="appSettingsCjkInput"><span class="slider"></span></label>
</div>
<div class="set-row" data-search="cjk input send on enter hold draft pinned prompt field phone">
<div class="set-row-text">
<span class="set-row-label">Input Field: Send on Enter</span>
<span class="set-row-desc">With CJK Input on, keep typed text in the field until Enter instead of sending it as you type, so you can scroll the terminal and edit before sending. Autocorrect is on in this mode.</span>
</div>
<label class="switch switch-sm"><input type="checkbox" id="appSettingsCjkHoldUntilEnter"><span class="slider"></span></label>
</div>
<div class="set-row" data-search="extended keyboard bar tab esc arrows phone">
<div class="set-row-text">
<span class="set-row-label">Extended Keyboard Bar <span class="set-tag">phone</span></span>
+13 -321
View File
@@ -7,21 +7,6 @@
* 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
@@ -72,27 +57,6 @@ 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 = '​';
@@ -196,7 +160,6 @@ 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.
@@ -226,13 +189,6 @@ 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) {
@@ -241,133 +197,6 @@ 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) {
@@ -397,16 +226,14 @@ const CjkInput = (() => {
}
return {
init({ send, sendPrompt = null }) {
init({ send }) {
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();
@@ -489,14 +316,16 @@ const CjkInput = (() => {
_t(`keydown ${_kdesc(e.key)} kc=${e.keyCode} ic=${e.isComposing} c=${_composing}`);
_printableKeydownAt = null;
if (e.key === 'Enter') {
// 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;
}
e.preventDefault();
_submit();
_composing = false;
_cancelDebouncedFlush();
const val = _strip(_textarea.value);
if (val) {
_send(val + '\r');
} else {
_send('\r');
}
_resetToPhantom();
return;
}
@@ -505,15 +334,10 @@ const CjkInput = (() => {
_composing = false;
_cancelDebouncedFlush();
_resetToPhantom();
if (_hold) _autoGrow();
return;
}
// 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())) {
if (e.ctrlKey && CTRL_KEYS[e.key]) {
e.preventDefault();
_send(CTRL_KEYS[e.key]);
return;
@@ -581,11 +405,6 @@ const CjkInput = (() => {
_composing = false;
}
if (_hold) {
_holdInput(e);
return;
}
// ── Backspace / delete detection ──
if (e.inputType === 'deleteContentBackward' || e.inputType === 'deleteWordBackward') {
if (_composing) return;
@@ -645,24 +464,9 @@ const CjkInput = (() => {
* can't flush into the wrong session). Restores the phantom so backspace
* forwarding keeps working — unlike a raw `textarea.value = ''`.
*/
clear({ discard = false } = {}) {
clear() {
if (!_initialized || !_textarea) return;
_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;
}
_t('clear (external)');
_cancelDebouncedFlush();
clearTimeout(_compositionFlushTimer);
_compositionFlushTimer = null;
@@ -671,118 +475,6 @@ const CjkInput = (() => {
_resetToPhantom();
},
/**
* Send-on-Enter mode on or off (setting cjkInputHoldUntilEnter). On: text
* stays in the field until Enter and the browser's autocorrect is allowed,
* since nothing typed has reached the PTY yet. Off: the original live mode.
*/
setHoldUntilEnter(on) {
// The placeholder first, before the early return: App Settings applies a
// language switch live and then calls this with the mode unchanged. It is
// written only when the text differs, so a field mid-composition is not
// touched. i18n.js skips <textarea> subtrees (what is typed there is user
// content), so it is translated here, like the prompt composer's.
if (_textarea) {
const source = !!on
? 'Type, Enter to send (Shift+Enter: new line, Esc: clear)'
: 'CJK input (Enter = send, Esc = clear)';
const i18n = typeof window !== 'undefined' ? window.CodemanI18n : undefined;
const placeholder = typeof i18n?.t === 'function' ? i18n.t(source) : source;
if (_textarea.placeholder !== placeholder) _textarea.placeholder = placeholder;
}
// Called on every session select and SSE reconnect: with the mode
// unchanged, leave the rest of the field alone, since rewriting its
// attributes while it has focus can disturb a composition in progress.
if (_holdApplied && _textarea && _hold === !!on) return;
const wasHolding = _hold;
_hold = !!on;
if (!_textarea) return;
_holdApplied = true;
// Turning the mode off: live mode's next flush would send everything in
// the field, a held multi-line draft included (its newline runs the first
// line in a shell), and stashed drafts would come back if the mode is
// switched on again. Drop them all.
if (wasHolding && !_hold) {
_drafts.clear();
_resetToPhantom();
}
_heldBase = _strip(_textarea.value);
const v = _hold ? 'on' : 'off';
_textarea.setAttribute('autocorrect', v);
_textarea.setAttribute('autocapitalize', _hold ? 'sentences' : 'off');
_textarea.setAttribute('spellcheck', _hold ? 'true' : 'false');
if (_hold) {
_cancelDebouncedFlush();
_autoGrow();
} else {
_textarea.style.height = '';
}
_t(`hold ${v}`);
},
get holdUntilEnter() { return _hold; },
/**
* Enter from outside the field (the phone toolbar's Enter button, which
* xterm's onData would swallow while the field is visible). Same as Enter
* in the field. Returns false when nothing was done (not initialized) or a
* held answer was refused.
*/
submit() {
if (!_initialized || !_textarea) return false;
_t(`submit (external) c=${_composing}`);
if (_composing) {
// An IME still composing (Gboard holds the current word, iOS the
// unconverted pinyin): reading and resetting the field under it can
// desync the keyboard. Blur commits the composition, focus keeps the
// keyboard up (still inside the tap's gesture), then send what landed.
_textarea.blur();
_textarea.focus();
}
return _submit();
},
/**
* Send-on-Enter: keep the held draft of the session being left, so a
* switch (a stray sideways swipe) does not lose an answer. Call before
* clear(); restoreDraft() puts it back when that session is shown again.
*/
stashDraft(sessionId) {
if (!_initialized || !_textarea || !_hold || !sessionId) return;
// An empty field leaves any stash alone: a draft only sits in the map
// while its session is not shown (restoreDraft takes it out), and the
// tile grid may stash an id whose draft is already put away.
const draft = _strip(_textarea.value);
if (draft.trim()) _drafts.set(sessionId, draft);
},
/** Send-on-Enter: show the draft stashed for this session, if any, unless
* the field already holds text. */
restoreDraft(sessionId) {
if (!_initialized || !_textarea) return;
// The field now belongs to this session, draft or not (see _owner),
// unless it still holds another session's text (no clear() in between).
if (!_owner || !_strip(_textarea.value)) _owner = sessionId || null;
if (!_hold || !_drafts.has(sessionId)) return;
if (_strip(_textarea.value)) return;
const draft = _drafts.get(sessionId);
_drafts.delete(sessionId);
_t(`restore draft len=${draft.length}`);
_textarea.value = PHANTOM + draft;
_textarea.setSelectionRange(_textarea.value.length, _textarea.value.length);
_heldBase = draft;
_autoGrow();
},
/** Forget a stashed draft when its session no longer exists. */
discardDraft(sessionId) {
_drafts.delete(sessionId);
if (_owner === sessionId) _owner = null;
},
/** Diagnostic/test: the session the field's text belongs to. */
get draftOwner() { return _owner; },
/** Diagnostic: recent IME event trace (ring buffer). */
getTrace() {
return _trace.slice();
+13 -47
View File
@@ -435,55 +435,27 @@ const KeyboardHandler = {
// BEHIND the keyboard with its own search box out of sight.
const caseSheet = document.querySelector('.mobile-case-picker.active .mobile-case-picker-sheet');
// A focused field that starts behind the keyboard (the pinned CJK / Send on
// Enter field) makes Android pan the visual viewport down to reveal it (measured
// on Chrome: offsetTop 285px with a 458px visual viewport in a 744px layout one).
// The app is sized to the visual viewport but laid out at the top of the layout
// viewport, so that pan left only the terminal's last line on screen. On phones,
// follow the pan while the keyboard is up, whatever has focus: without a pan
// (offsetTop 0, the usual case) nothing moves, and a focus change that keeps the
// pan cannot drop the shift. Every other branch clears it.
// ⚠️ The transform makes .app the box its position:fixed children (header,
// toolbar, accessory bar, the field) are placed against, so their keyboard lift
// below is measured from .app's bottom, not the layout viewport's, or they would
// be lifted twice on a partial pan. The case sheet (#mobileCasePickerModal) is
// inside .app too and takes the same lift.
const appEl = document.querySelector('.app');
const pan = isSmallMedium ? Math.round(window.visualViewport.offsetTop || 0) : 0;
if (appEl) appEl.style.transform = pan > 0 ? `translateY(${pan}px)` : '';
// The layout viewport's height, which position:fixed bottoms are measured from.
// ⚠️ Not window.innerHeight alone: on the first keyboard open after focusing the
// pinned field, iOS Safari reported innerHeight as the shrunk visual height (323)
// while the layout viewport stayed 640 (documentElement.clientHeight), so the lift
// came out 0 and the bars stayed behind the keyboard. Earlier a delayed
// scrollIntoView re-ran this pass once innerHeight had caught up; without it the
// stale value stuck. The larger of the two cannot be stale in that direction.
const layoutHeight = Math.max(window.innerHeight, document.documentElement?.clientHeight || 0);
const visualBottom = window.visualViewport.offsetTop + window.visualViewport.height;
const keyboardOffset = Math.max(0, layoutHeight - visualBottom);
const insideLift = pan > 0 && appEl ? Math.max(0, pan + appEl.offsetHeight - visualBottom) : keyboardOffset;
if (isSmallMedium) {
// Phones/small tablets: toolbar and accessory bar are position:fixed
// via CSS. Use translateY to lift them above the keyboard.
const toolbar = document.querySelector('.toolbar');
const main = document.querySelector('.main');
const layoutHeight = window.innerHeight;
const visualBottom = window.visualViewport.offsetTop + window.visualViewport.height;
const keyboardOffset = Math.max(0, layoutHeight - visualBottom);
if (toolbar) {
toolbar.style.transform = insideLift > 0 ? `translateY(${-insideLift}px)` : '';
toolbar.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
}
if (accessoryBar) {
accessoryBar.style.transform = insideLift > 0 ? `translateY(${-insideLift}px)` : '';
accessoryBar.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
}
if (caseSheet) {
caseSheet.style.transform = insideLift > 0 ? `translateY(${-insideLift}px)` : '';
caseSheet.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
}
if (main && keyboardHeight > 0) {
// The field grows with its text in Send-on-Enter mode, so reserve its
// real height (44 = the one-line field plus its border, the old constant).
const cjkInputHeight = cjkInput?.classList.contains('cjk-input-visible')
? Math.max(44, cjkInput.offsetHeight + 10)
: 0;
const cjkInputHeight = cjkInput?.classList.contains('cjk-input-visible') ? 44 : 0;
main.style.paddingBottom = `${84 + cjkInputHeight}px`;
}
} else if (keyboardHeight > 0) {
@@ -500,8 +472,11 @@ const KeyboardHandler = {
// CJK textarea positioning (always position:fixed on touch devices).
if (cjkInput?.classList.contains('cjk-input-visible') && keyboardHeight > 0) {
if (isSmallMedium) {
// Phones: use translateY like toolbar/accessory bar (it sits inside .app too).
cjkInput.style.transform = insideLift > 0 ? `translateY(${-insideLift}px)` : '';
// Phones: use translateY like toolbar/accessory bar.
const layoutHeight = window.innerHeight;
const visualBottom = window.visualViewport.offsetTop + window.visualViewport.height;
const keyboardOffset = Math.max(0, layoutHeight - visualBottom);
cjkInput.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
cjkInput.style.bottom = '';
} else {
// iPad: direct bottom = keyboard + accessory bar height.
@@ -524,11 +499,7 @@ const KeyboardHandler = {
// keyboard was still up must still have its inline offset cleared, or the
// next open slides in already displaced.
const caseSheet = document.querySelector('.mobile-case-picker-sheet');
const appEl = document.querySelector('.app');
if (appEl) {
appEl.style.transform = '';
}
if (toolbar) {
toolbar.style.transform = '';
}
@@ -758,11 +729,6 @@ const KeyboardHandler = {
if (el.closest('.xterm') || el.closest('.terminal-container')) {
return false;
}
// The pinned CJK / Send on Enter field is position:fixed and lifted above the
// keyboard by updateLayoutForKeyboard(). Scrolling it into view centred it in its
// scrollable ancestors instead, which pushed the terminal off screen whenever the
// field took focus.
if (el.id === 'cjkInput') return false;
const tagName = el.tagName?.toLowerCase();
// Exclude type=range, type=checkbox, type=radio (don't trigger keyboard)
-10
View File
@@ -2082,16 +2082,6 @@ Object.assign(CodemanApp.prototype, {
* so overlay flush, flushed-offset cleanup and ordering are all reused. */
sendEnterKey() {
if (!this.activeSessionId) return;
// While the CJK field is visible, onData drops everything (cjkActive), this
// Enter included. Press Enter in the field instead: it sends what the field
// holds (a Send on Enter answer, or live text not yet flushed), then Enter.
if (
typeof CjkInput !== 'undefined' &&
document.getElementById('cjkInput')?.classList.contains('cjk-input-visible')
) {
CjkInput.submit?.();
return;
}
const coreService = this.terminal?._core?.coreService;
if (coreService && typeof coreService.triggerDataEvent === 'function') {
coreService.triggerDataEvent('\r', true);
+1 -6
View File
@@ -649,8 +649,6 @@ Object.assign(CodemanApp.prototype, {
document.getElementById('appSettingsTerminalWheelLocal').checked =
settings.terminalWheelLocalScrollback ?? defaults.terminalWheelLocalScrollback ?? false;
document.getElementById('appSettingsCjkInput').checked = settings.cjkInputEnabled ?? defaults.cjkInputEnabled ?? false;
document.getElementById('appSettingsCjkHoldUntilEnter').checked =
settings.cjkInputHoldUntilEnter ?? defaults.cjkInputHoldUntilEnter ?? false;
document.getElementById('appSettingsExtendedKeyboardBar').checked = settings.extendedKeyboardBar ?? false;
document.getElementById('appSettingsTabTwoRows').checked = settings.tabTwoRows ?? defaults.tabTwoRows ?? false;
document.getElementById('appSettingsShowTabCliLogos').checked = this.tabCliLogosEnabled(settings);
@@ -3197,7 +3195,6 @@ Object.assign(CodemanApp.prototype, {
),
terminalWheelLocalScrollback: document.getElementById('appSettingsTerminalWheelLocal').checked,
cjkInputEnabled: document.getElementById('appSettingsCjkInput').checked,
cjkInputHoldUntilEnter: document.getElementById('appSettingsCjkHoldUntilEnter').checked,
webglRendererEnabled: document.getElementById('appSettingsWebglRenderer').checked,
extendedKeyboardBar: document.getElementById('appSettingsExtendedKeyboardBar').checked,
tabTwoRows: document.getElementById('appSettingsTabTwoRows').checked,
@@ -3443,7 +3440,6 @@ Object.assign(CodemanApp.prototype, {
// SettingsUpdateSchema (.strict()), so sending it would 400 the whole PUT.
keyboardHoldsRows: _khr,
cjkInputEnabled: _cjk,
cjkInputHoldUntilEnter: _cjkHold,
extendedKeyboardBar: _ekb,
skin: _skin,
language: _language,
@@ -4482,7 +4478,6 @@ Object.assign(CodemanApp.prototype, {
sessionListLayout: 'header',
sessionSidebarFontSize: 12,
cjkInputEnabled: false,
cjkInputHoldUntilEnter: false,
terminalWheelLocalScrollback: false, // mobile scrolls via touch, not wheel
webglRendererEnabled: false, // mobile always uses the DOM renderer
skin: 'daylight-blue',
@@ -5211,7 +5206,7 @@ Object.assign(CodemanApp.prototype, {
'showFontControls', 'showSystemStats', 'showGpuStats', 'showCpuMhz', 'headerStatsStyle', 'showTokenCount', 'showCost',
'showLifecycleLog', 'showResponseViewer', 'showRedrawButton',
'showMonitor', 'showProjectInsights', 'showFileBrowser', 'showSubagents',
'subagentActiveTabOnly', 'tabTwoRows', 'showTabCliLogos', 'tabOrientation', 'tabRailWidth', 'tabRailDetail', 'tabRailSort', 'tabArrangement', 'tabStateOrder', 'sessionListLayout', 'sessionSidebarFontSize', 'localEchoEnabled', 'keyboardHoldsRows', 'cjkInputEnabled', 'cjkInputHoldUntilEnter', 'extendedKeyboardBar',
'subagentActiveTabOnly', 'tabTwoRows', 'showTabCliLogos', 'tabOrientation', 'tabRailWidth', 'tabRailDetail', 'tabRailSort', 'tabArrangement', 'tabStateOrder', 'sessionListLayout', 'sessionSidebarFontSize', 'localEchoEnabled', 'keyboardHoldsRows', 'cjkInputEnabled', 'extendedKeyboardBar',
'skin', 'showPlanUsageLimits', 'showAttachmentsButton', 'showFileViewerButton', 'webglRendererEnabled',
'terminalFontFamily', 'terminalFontWeight', 'terminalFontWeightBold',
'language',
-13
View File
@@ -14199,12 +14199,6 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
resize: none;
line-height: 1.4;
box-sizing: border-box;
/* A backstop: Send on Enter grows the field with its text only on touch devices
(input-cjk.js _autoGrow), where the .touch-device rule caps it too. On desktop
it keeps its one-line height, so this cap only guards against anything else
setting a taller one, which would push the terminal (and its PTY) down. */
max-height: 68px;
overflow-y: auto;
}
#cjkInput:focus {
@@ -14241,13 +14235,6 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
bottom: calc(var(--safe-area-bottom) + 84px);
}
/* Send on Enter grows the field with its text, but with the keyboard down .main
reserves a fixed 84px (below), so a grown field would cover the terminal's
last rows. Keep it one line tall there; the text scrolls inside. */
.touch-device:not(.keyboard-visible) #cjkInput.cjk-input-visible {
max-height: 34px;
}
body.touch-device.cjk-input-visible .main {
padding-bottom: calc(84px + var(--safe-area-bottom));
}
+27 -100
View File
@@ -1083,10 +1083,6 @@ Object.assign(CodemanApp.prototype, {
send: (text) => {
this._handleCjkInput(text);
},
// Send on Enter: a long or multi-line held answer goes out like the
// mobile prompt composer's Send (one bracketed paste, then Enter as a
// separate delayed write), bound to the session it was typed for.
sendPrompt: (text) => this._sendCjkPrompt(text),
});
}
@@ -1378,7 +1374,7 @@ Object.assign(CodemanApp.prototype, {
// selectSession() ends with scrollToLastNonEmptyLine(), that made
// the keyboard unreachable after every tab switch.
ev.preventDefault();
if (this._contentTouchStartBlurs()) this._blurMobileTerminalInput();
this._blurMobileTerminalInput();
}
// Hold still and this press becomes a text selection. Cancelled by any
// travel past the shared tap slop below, so a scroll can never become one.
@@ -4555,10 +4551,8 @@ Object.assign(CodemanApp.prototype, {
// after every key. So the onData hook never sees these keystrokes, and an
// armed modifier could neither fire NOR be spent: it survived until a
// session switch and then turned an innocent keystroke into a control byte.
// This is the module's single choke point to the PTY in live mode, so applying
// it here covers typed characters, IME flushes, Enter, backspace and arrows at
// once. In Send on Enter a held answer leaves through _sendCjkPrompt instead,
// which spends the modifier; an armed next character still comes here.
// This is the module's single choke point to the PTY, so applying it here
// covers typed characters, IME flushes, Enter, backspace and arrows at once.
// Same policy as the onData hook: the next single character is modified,
// anything longer merely spends the modifier.
if (typeof KeyboardAccessoryBar !== 'undefined' && KeyboardAccessoryBar.isCtrlArmed?.()) {
@@ -4570,49 +4564,6 @@ Object.assign(CodemanApp.prototype, {
this._sendInputAsync(this.activeSessionId, text);
},
/**
* Send on Enter (CjkInput, setting cjkInputHoldUntilEnter): deliver a held
* answer, then Enter as its own write ~120 ms later. Never `<text>\r` in one
* write: Codex reads characters arriving in one burst as a paste and folds an
* Enter inside it into the paste (even `1\r` stays unsent), and Claude Code
* does the same for a long burst. Same split as TmuxManager.sendInput: a
* single character is typed (a selection dialog ignores a pasted `3`, then
* Enter confirms the highlighted option), anything else goes through the
* composer's path as one bracketed paste. The session is captured now, so the
* delayed Enter cannot follow a tab switch. A lone digit while the session
* shows a permission or question dialog goes out without the Enter: the
* dialog acts on the digit itself, and a later Enter would confirm whatever
* the CLI shows next (a second permission prompt, unseen). Same rule as the
* Approvals Inbox and the Discord bridge (server.ts awaitingChoice). Returns
* false when nothing was sent (no session, too long), so the field keeps the
* text.
*/
_sendCjkPrompt(text) {
const sessionId = this.activeSessionId;
if (!sessionId || typeof KeyboardAccessoryBar === 'undefined') {
_crashDiag.log(`CJK prompt DROP no-session len=${text.length}`);
return false;
}
// A held answer is never what an armed one-shot Ctrl applies to (CjkInput
// sends the next typed character straight away as the control key), so
// Enter spends it, the same rule _handleCjkInput has for a longer chunk.
KeyboardAccessoryBar.clearCtrl?.();
_crashDiag.log(`CJK prompt→${sessionId.slice(0, 8)} len=${text.length}`);
if ([...text].length === 1) {
if (this._localEchoPolicy === 'predict') this._predictiveEcho?.clearPredictions();
this._sendInputAsync(sessionId, text);
const hooks = this.pendingHooks?.get(sessionId);
const awaitingChoice = !!hooks && (hooks.has('permission_prompt') || hooks.has('elicitation_dialog'));
if (/^\d$/.test(text) && awaitingChoice) {
_crashDiag.log(`CJK prompt digit answers a dialog, no Enter`);
return true;
}
setTimeout(() => this._sendInputAsync(sessionId, '\r', { useMux: true }), 120);
return true;
}
return KeyboardAccessoryBar._sendComposedPrompt(sessionId, text);
},
/**
* Re-assert a history anchor captured before a terminal write (#358).
*
@@ -5136,9 +5087,7 @@ Object.assign(CodemanApp.prototype, {
clearTerminalInput() {
if (!this.activeSessionId) return;
// discard: the line is thrown away, so a Send on Enter draft must not be
// stashed and come back on the next visit to this session.
if (typeof CjkInput !== 'undefined') CjkInput.clear({ discard: true });
if (typeof CjkInput !== 'undefined') CjkInput.clear();
// A tile or Pane B holds the keyboard: its TUI owns the editable buffer
// (no local-echo overlay there), so kill the line in that pane's session,
// never in the parked main pane's.
@@ -5701,19 +5650,6 @@ Object.assign(CodemanApp.prototype, {
return 'content';
},
/**
* Whether a touchstart on transcript content should blur the focused terminal input.
* It does for xterm's helper textarea: that blur, with the preventDefault beside it,
* keeps the compatibility click from opening the keyboard. It must NOT for the pinned
* CJK field: at touchstart the gesture may still be a scroll, and that field owns the
* keyboard while it is visible, so blurring it closed the keyboard on every swipe that
* started on the live screen. A real tap on inert transcript still closes the keyboard
* at touchend (the startedWithTerminalFocus branch), so a tap keeps its meaning.
*/
_contentTouchStartBlurs() {
return document.activeElement?.id !== 'cjkInput';
},
_blurMobileTerminalInput() {
const active = document.activeElement;
if (
@@ -5912,9 +5848,6 @@ Object.assign(CodemanApp.prototype, {
) {
// No focus change: a 'content' tap was already blurred by touchstart, and
// popping the keyboard behind a tab that is about to take over is noise.
// The pinned CJK field is the exception touchstart leaves focused (a swipe must
// not close its keyboard), so a tap that opens a link closes it here instead.
if (!this._contentTouchStartBlurs()) this._blurMobileTerminalInput();
return 'link';
}
@@ -6083,16 +6016,12 @@ Object.assign(CodemanApp.prototype, {
// True when a parsed CLI version string ('2.1.187' — banner-parsed on the
// server, delivered via session:cliInfo / SessionState.cliVersion) is known
// AND >= the minimum. Unknown or unparseable versions return false so
// callers keep the conservative behavior, and so does an unparseable
// minimum: it can come from a user's clis.json (`wheelForward.minVersion`).
// callers keep the conservative behavior.
_cliVersionAtLeast(version, minimum) {
const parse = (v) => {
const m = typeof v === 'string' ? /^v?(\d+)\.(\d+)\.(\d+)$/.exec(v.trim()) : null;
return m ? m.slice(1).map(Number) : null;
};
const parts = parse(version);
const min = parse(minimum);
if (!parts || !min) return false;
if (typeof version !== 'string') return false;
const parts = version.trim().replace(/^v/, '').split('.').map(Number);
if (parts.length !== 3 || parts.some((n) => !Number.isFinite(n))) return false;
const min = minimum.split('.').map(Number);
for (let i = 0; i < 3; i++) {
if (parts[i] !== min[i]) return parts[i] > min[i];
}
@@ -6152,26 +6081,24 @@ Object.assign(CodemanApp.prototype, {
if (mode && mode !== 'none') return false;
const session = this.sessions?.get(target.sessionId || this.activeSessionId);
const sessionMode = session?.mode || 'claude';
// Which CLIs scroll their own transcript on SGR wheel reports is the registry's
// `wheelForward` rule, published by renderIndexHtml as `window.__codemanWheelForward`
// (id -> rule, `never` left out; a page rendered without the map forwards nothing), so a
// custom clis.json entry shaped like pi forwards under its own id. Stock: claude from
// 2.1.187 (older versions take the wheel as menu navigation), codex, copilot and pi always.
// Their mouse DECSETs are stripped server-side (a drag selects locally), so xterm never
// encodes the wheel for them and the reports are sent by hand.
const rule = window.__codemanWheelForward?.[sessionMode];
if (!rule || (rule.mode !== 'always' && rule.mode !== 'version-gated')) return false;
if (rule.mode === 'version-gated' && !this._cliVersionAtLeast(session?.cliVersion, rule.minVersion)) return false;
// Only while the CLI is actually listening for the mouse. Claude's inline renderer
// (2.1.280 measured: alternate_on=0, mouse_any_flag=0), like older inline Codex and pi's
// `tuiMode: regular`, keeps its transcript in real scrollback; SGR reports are ignored, so
// forwarding made every swipe and wheel tick dead. Fullscreen (CLAUDE_CODE_NO_FLICKER=1, or
// "tui": "fullscreen" in ~/.claude/settings.json; pi's default since 1.0.0) turns on
// alt-screen + mouse tracking, which the server records as cliMouseTracking. That flag is
// what survives a tab switch or reload, where xterm's own mouse mode does not. A stale-false
// flag falls through to _maybePageCliTranscript (PageUp/PageDown for a CLI declaring
// `transcriptPageKeys`); pi declares none on purpose (the note in stock.ts), so there the
// wheel does nothing until the flag is back.
// GitHub Copilot CLI (and pi, fullscreen by default) scrolls its own transcript on SGR wheel
// reports (checked with xterm encoding them natively). Their mouse DECSETs are stripped
// server-side so a drag selects locally (strip-mux-and-mouse), which also means xterm no longer
// encodes the wheel: send the same reports by hand, but only while the CLI is actually tracking
// the mouse. Not gated on a version. On Copilot a stale-false flag falls through to the
// PageUp/PageDown fallback like claude's; pi has none on purpose (the `transcriptPageKeys` note
// in stock.ts), so there the wheel does nothing until the flag is back.
if (sessionMode === 'copilot' || sessionMode === 'pi') return session?.cliMouseTracking === true;
if (sessionMode !== 'claude' && sessionMode !== 'codex') return false;
if (sessionMode === 'claude' && !this._cliVersionAtLeast(session?.cliVersion, '2.1.187')) return false;
// Only while Claude or Codex is actually listening for the mouse. Claude's
// inline renderer (2.1.280 measured: alternate_on=0, mouse_any_flag=0), like
// older inline Codex, keeps its transcript in real scrollback; SGR reports are
// ignored, so forwarding made every swipe and wheel tick dead. Fullscreen
// (CLAUDE_CODE_NO_FLICKER=1, or "tui": "fullscreen" in ~/.claude/settings.json)
// turns on alt-screen + mode 1003/1006, which the server records as
// cliMouseTracking. A stale-false flag after a server restart falls through
// to _maybePageCliTranscript, so it never goes dead.
if (session?.cliMouseTracking !== true) return false;
// Deliberately NOT gated on _terminalViewportAtBottom(). It used to be, so
// that leaving the bottom handed the wheel back to local scrollback and both
-14
View File
@@ -2651,20 +2651,6 @@ Object.assign(CodemanApp.prototype, {
// Aborts any in-flight normal select at its next _isStaleSelect check.
const selectGen = ++this._selectGeneration;
this._hideWebviewLayer?.();
// The one CJK field follows tile focus, and Enter sends to the session
// active at that moment: a Send on Enter draft typed for one tile must not
// go to the next. Stash it for the tile left, show the one focused (also
// the draft openTileGrid's cleanup stashed for the session it parked).
if (typeof CjkInput !== 'undefined') {
if (this.activeSessionId && this.activeSessionId !== sessionId) {
// A tile closed from this tab is already gone from this.sessions and
// its draft discarded: stashing it again would leave it in the map
// until the page reloads.
if (this.sessions?.has(this.activeSessionId)) CjkInput.stashDraft?.(this.activeSessionId);
CjkInput.clear();
}
CjkInput.restoreDraft?.(sessionId);
}
this.activeSessionId = sessionId;
grid.focusedId = sessionId;
// Moving focus off a zoomed tile restores the grid, as selecting another
+9 -9
View File
@@ -1,13 +1,13 @@
{
"version": "1.51.1",
"version": "1.51.0",
"highlights": [
"Phone: Send on Enter for the input field (#820)",
"The terminal dashboard attaches by session name (#834)",
"Web tabs render the DeepSeek Harness web UI and Vite dashboards (#825)",
"Local model: Muse Glimmer 30B as its MLX build (#803)",
"A failing file watcher no longer floods the log (#818)",
"A password-protected Codeman installs as an app (#826)",
"A trusted web tab's WebSocket no longer sends Codeman's session cookie to the dashboard (#827)",
"Answers come back for a session on its own Claude config folder (#701, #812)"
"Local models: a library, more models, and the coding agent you choose (#803, #804, #806, #807, #808)",
"Mac app: With the Lid Closed no longer asks for a password",
"Auto-compact and auto-clear see the whole context (#777)",
"jcode as a run mode (#650)",
"The File Viewer edits `.env` files (#796, #797)",
"Response viewer: a Copy Markdown button (#810)",
"Firefox no longer pastes twice on Ctrl+V (#799)",
"An omp pane that asks for a tool approval alerts (#798)"
]
}
+5 -16
View File
@@ -14,12 +14,11 @@ import { execSync, spawn } from 'node:child_process';
import { randomBytes } from 'node:crypto';
import { dataPath } from '../../config/instance.js';
import { readHostSensors } from '../../host-sensors.js';
import { createCpuUsageMeter } from '../../cpu-usage.js';
import { ApiErrorCode, createErrorResponse, getErrorMessage, type NiceConfig } from '../../types.js';
import { isExplicitlyEnabled, isUnauthenticatedTunnelAcknowledged } from '../network-auth-policy.js';
import { isMultiUserMode } from '../../config/multiuser.js';
import { findUser, canUsernameRunPrivilegedCommands } from '../../user-store.js';
import { getAuthUser, isAdmin, requireAdmin, canAccessOwned, revokeUserSessions, ownerFor } from '../route-helpers.js';
import { getAuthUser, isAdmin, requireAdmin, canAccessOwned, revokeUserSessions } from '../route-helpers.js';
import {
ConfigUpdateSchema,
SettingsUpdateSchema,
@@ -94,15 +93,6 @@ const SCREENSHOTS_DIR = dataPath('screenshots');
/** Cached CPU count — doesn't change at runtime */
const CPU_COUNT = cpus().length;
/** Header CPU use; the 1-minute load average per core only when the platform reports no core times. */
const cpuUsagePercent = createCpuUsageMeter(
cpus,
() => performance.now(),
() =>
// That is also the platform where cpus() is empty, so CPU_COUNT can be 0 here.
CPU_COUNT > 0 ? Math.min(100, Math.round((loadavg()[0] / CPU_COUNT) * 100)) : 0
);
function parseOptionalNumber(value: string | undefined): number | undefined {
if (value === undefined || value.trim() === '') return undefined;
const parsed = Number(value);
@@ -135,7 +125,9 @@ function getSystemStats(): {
usedMem = totalMem - freemem();
}
const cpuPercent = cpuUsagePercent();
// CPU load average (1 min) as percentage (rough approximation)
const load = loadavg()[0];
const cpuPercent = Math.min(100, Math.round((load / CPU_COUNT) * 100));
return {
cpu: cpuPercent,
@@ -667,10 +659,7 @@ export function registerSystemRoutes(
if (!dir) return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getDeepSeekNotFoundMessage());
const { startDeepSeekWeb } = await import('../../deepseek-web-server.js');
// The launch cookie is bound to the identity whose request started the
// process, so `ownerFor` (undefined in single-user) is recorded here rather
// than the synthetic admin `getAuthUser` would report.
const result = await startDeepSeekWeb(dir, authority, ownerFor(req));
const result = await startDeepSeekWeb(dir, authority);
if (!result.ok) return createErrorResponse(ApiErrorCode.OPERATION_FAILED, result.error);
return { success: true, data: { port: result.port, url: result.url, reused: result.reused } };
});
+2 -66
View File
@@ -36,7 +36,6 @@ import { WebSocket as WsClient } from 'ws';
import type { ClientOptions as WsClientOptions, WebSocket } from 'ws';
import type { Response as UndiciResponse } from 'undici';
import { getDataDir } from '../../config/instance.js';
import { isMultiUserMode } from '../../config/multiuser.js';
import {
MAX_LIVE_WEBVIEW_FRAMES,
MAX_WEBVIEWS,
@@ -48,11 +47,9 @@ import {
WEBVIEW_WS_HANDSHAKE_TIMEOUT_MS,
} from '../../config/webview-limits.js';
import { readWebviews, writeWebviews } from '../../webview-store.js';
import { canUsernameRunPrivilegedCommands } from '../../user-store.js';
import { webviewCapabilities } from '../../webview-capabilities.js';
import { egressBlockedReason, webviewEgressLookup, webviewFetch, type EgressLookup } from '../webview-egress.js';
import { blockedWebviewHostReason } from '../webview-egress-policy.js';
import { getDeepSeekWebCookie } from '../../deepseek-web-server.js';
import { ApiErrorCode, createErrorResponse } from '../../types.js';
import type { Webview, WebviewOpenData, WebviewProbe } from '../../types.js';
import { AUTH_COOKIE_NAME } from '../middleware/auth.js';
@@ -67,10 +64,8 @@ import {
buildUpstreamRequestHeaders,
capabilityFromReferer,
extractFrameAncestors,
filterCookieHeader,
isFramableCrossOrigin,
isHtmlContentType,
mergeCookieHeader,
parseWebviewUrl,
proxyPrefixFor,
resolveUpstreamUrl,
@@ -431,51 +426,6 @@ function proxyHttp(
return proxyRequest(req, reply, req.params.cap, req.params['*'] ?? '', basePath);
}
/**
* The credential a Codeman-managed dashboard needs on every upstream request.
*
* `dsh web` now gates its index and `/api` behind a cookie minted for the
* authority it was started on, and only the URL it prints on boot carries the
* token that buys it. The managed DeepSeek tab deliberately stores the clean
* URL, so the browser can never hold that cookie: `deepseek-web-server.ts`
* exchanges the token at startup, and this is where the supervisor's result
* reaches the request.
*
* Strictly scoped to the exact loopback origin the cookie was minted for. A
* web tab the user repointed at another host, or a stale tab still naming a
* previous port, must not be handed a credential that is not its own.
*
* ⚠️ `managed` is accepted from the client on POST/PATCH /api/webviews, and the
* live port is published by GET /api/deepseek/web, so "this record is managed and
* points at the port" is NOT an entitlement: without the check below, any signed-in
* user could save `{ url: "http://127.0.0.1:<port>", managed: "deepseek-web" }` and
* be handed the cookie bought by the user allowed to start the server. The gate
* needs the owner's privileged-commands grant, which is the same bar
* `POST /api/deepseek/web` applies before it starts a server.
*
* @param webview - the saved tab being proxied.
* @param upstream - resolved upstream URL for this request.
* @returns `name=value` cookie pair, or undefined when none applies.
*/
async function managedDashboardCookie(webview: Webview, upstream: URL): Promise<string | undefined> {
if (webview.managed !== 'deepseek-web') return undefined;
if (upstream.hostname !== '127.0.0.1') return undefined;
if (isMultiUserMode()) {
// Fail closed on an ownerless legacy record: `canUsernameRunPrivilegedCommands`
// treats an absent username as privileged (right for a cron job with no owner,
// wrong here), so the owner must be present before it is asked.
if (!webview.owner) return undefined;
if (!(await canUsernameRunPrivilegedCommands(webview.owner))) return undefined;
}
const port = Number(upstream.port || (upstream.protocol === 'https:' ? 443 : 80));
// The second identity check is the supervisor's: even an entitled owner gets
// nothing from a process another user started (POST restarts it for a new
// starter, so that tab simply reopens with its own cookie). Only in multi-user
// mode: a record created there keeps its owner, while a single-user start has
// no starter, so comparing that owner would refuse the tab for good.
return getDeepSeekWebCookie(port, isMultiUserMode() ? webview.owner : undefined) ?? undefined;
}
/**
* Proxy one request to the dashboard behind `cap`, serving `wildcard` as the
* upstream path. Split out from the route handler so the 404 fallback (which has
@@ -518,14 +468,12 @@ async function proxyRequest(
}
const hasBody = req.method !== 'GET' && req.method !== 'HEAD';
const injectedCookie = await managedDashboardCookie(webview, upstream);
const headers = buildUpstreamRequestHeaders(req.headers, upstream, {
forwardCookies: webview.trusted,
sessionCookieName: AUTH_COOKIE_NAME,
refererPath:
typeof req.headers.referer === 'string' ? stripProxyPrefix(req.headers.referer, cap, basePath) : undefined,
relayBodyLength: hasBody && req.body !== undefined,
...(injectedCookie ? { injectedCookie } : {}),
});
// #237: the timeout bounds TIME-TO-HEADERS only. A plain AbortSignal.timeout on
@@ -647,9 +595,7 @@ async function proxyRequest(
// Buffer only HTML, only under the cap: `<base>` injection needs the whole
// document, and buffering an unbounded upstream body is a memory hazard.
const html = await response.text();
return reply.send(
html.length <= MAX_WEBVIEW_HTML_REWRITE_BYTES ? rewriteHtml(html, cap, basePath, wildcard) : html
);
return reply.send(html.length <= MAX_WEBVIEW_HTML_REWRITE_BYTES ? rewriteHtml(html, cap, basePath) : html);
}
return reply.send(Readable.fromWeb(response.body as Parameters<typeof Readable.fromWeb>[0]));
@@ -761,23 +707,13 @@ function proxyWebSocket(socket: WebSocket, req: FastifyRequest<{ Params: ProxyPa
};
const protocols = req.headers['sec-websocket-protocol'];
// The same credential the HTTP leg presents. A managed dashboard's realtime
// channel is gated exactly like its index, so without this the page loads
// and then sits there silently disconnected. Trusted dashboards get the
// browser's other cookies too, but never Codeman's own session cookie,
// with or without an injected one: the HTTP leg strips it the same way.
const injectedCookie = await managedDashboardCookie(webview, upstream);
const browserCookie = webview.trusted
? filterCookieHeader(req.headers.cookie ? String(req.headers.cookie) : undefined, [AUTH_COOKIE_NAME])
: undefined;
const cookie = injectedCookie ? mergeCookieHeader(browserCookie, injectedCookie) : browserCookie;
// `lookup` is absent from ws's ClientOptions typings but flows through
// http.request to net.connect untouched, which is where the resolved
// address is judged (see webview-egress.ts).
const upstreamOptions: WsClientOptions & { lookup: EgressLookup } = {
headers: {
origin: upstream.origin,
...(cookie ? { cookie } : {}),
...(webview.trusted && req.headers.cookie ? { cookie: String(req.headers.cookie) } : {}),
},
handshakeTimeout: WEBVIEW_WS_HANDSHAKE_TIMEOUT_MS,
lookup: webviewEgressLookup,
+1 -51
View File
@@ -269,7 +269,7 @@ import {
registerCliRegistryRoutes,
registerLocalModelRoutes,
} from './routes/index.js';
import { escapedWebviewAssetPath, isLostWebviewFrameNavigation } from './webview-proxy.js';
import { isLostWebviewFrameNavigation } from './webview-proxy.js';
import { CronService } from '../cron/cron-service.js';
import { caseSessionSettled } from '../case-rename.js';
@@ -361,38 +361,6 @@ function getOrCreateSelfSignedCert(): { key: string; cert: string } {
};
}
/**
* One warn per escaped path per few minutes.
*
* A page whose boot module 404s retries in a loop, so an undeduped warn would
* bury the log it is meant to explain. Capped so a page emitting unbounded
* unique paths cannot grow the map without limit.
*/
const escapedWebviewWarnedAt = new Map<string, number>();
const ESCAPED_WEBVIEW_WARN_TTL_MS = 5 * 60_000;
/**
* Name a root-absolute request that escaped a web tab's proxy prefix.
*
* Nothing is retried or rewritten here — the request genuinely has no capability
* to relay to. This exists because that failure is otherwise silent: the tab
* shows a blank page or a spinner that never resolves, and the log says nothing.
*
* @param path - request path already judged as that shape.
*/
function warnEscapedWebviewAsset(path: string): void {
const now = Date.now();
const last = escapedWebviewWarnedAt.get(path);
if (last !== undefined && now - last < ESCAPED_WEBVIEW_WARN_TTL_MS) return;
if (escapedWebviewWarnedAt.size >= 200) escapedWebviewWarnedAt.clear();
escapedWebviewWarnedAt.set(path, now);
console.warn(
`[Webview] ${path} escaped the proxy: a web tab asked for a root-absolute URL that no Codeman route serves. ` +
`Its URL is masked, so the Referer cannot identify the dashboard. Usual cause: a URL built at runtime ` +
`(dynamic import(), worker, service worker) or an import inside an external script. The tab will look blank or stuck.`
);
}
export class WebServer extends EventEmitter {
private app: FastifyInstance;
private sessions: Map<string, Session> = new Map();
@@ -1326,11 +1294,6 @@ export class WebServer extends EventEmitter {
// and the relay declines unless the Referer carries a live capability, so
// genuinely unknown `/api` paths still get the envelope below.
if (await tryWebviewRefererFallback(req, reply, this.basePath)) return reply;
// No capability in the Referer, so this cannot be relayed — but if it has
// the shape of a dashboard asset, say so once. Silent 404s here are what
// turned a boot-module failure into a "blank tab" mystery more than once.
const escaped = escapedWebviewAssetPath({ method: req.method, url: req.url, headers: req.headers });
if (escaped) warnEscapedWebviewAsset(escaped);
// An authenticated web-tab frame (Basic auth, or trusted mode with a cookie)
// that navigated itself off its proxy prefix: the runtime shim masks the
// prefix so the page's router sees its own path, and a reload of that page
@@ -2170,19 +2133,6 @@ export class WebServer extends EventEmitter {
'</head>',
() => `<script>window.__codemanKeyboardHoldModes=${JSON.stringify(keyboardHoldClis)};</script>\n</head>`
);
// Which run modes take the wheel as SGR reports while they track the mouse
// (`_shouldForwardWheelToApp`), keyed by id with the `wheelForward` rule itself, so a
// custom clis.json entry shaped like pi forwards under its own id. `never` is left out.
// Disabled entries are kept (`listClis`, not `enabledClis`): disabling a CLI never ends
// its running sessions, and their wheel must keep working across a reload.
// `minVersion` is a free string a user's clis.json sets, hence the script escaper.
const wheelForwardClis = Object.fromEntries(
listClis()
.filter((entry) => entry.capabilities.wheelForward.mode !== 'never')
.map((entry) => [entry.id, entry.capabilities.wheelForward])
);
const wheelForwardJson = escapeScriptJson(JSON.stringify(wheelForwardClis));
html = html.replace('</head>', () => `<script>window.__codemanWheelForward=${wheelForwardJson};</script>\n</head>`);
if (!soloSessionId && process.env.CODEMAN_GESTURE === '1') {
html = html.replace('</head>', () => `<script>window.__codemanGestureAvailable=true;</script>\n</head>`);
if (settings.gestureControlEnabled === true) {
+5 -194
View File
@@ -207,73 +207,6 @@ export function capabilityFromReferer(referer: string | undefined, basePath = ''
}
}
/** `Sec-Fetch-Dest` values that describe a page fetching for itself, not navigating. */
const ASSET_FETCH_DESTS = new Set([
'script',
'style',
'image',
'font',
'manifest',
'worker',
'sharedworker',
'audio',
'video',
'track',
'embed',
'object',
'empty',
]);
/** Codeman's own missing files: a 404 here says nothing about a web tab. */
const CODEMAN_OWN_404 =
/^\/(?:favicon\.ico|manifest\.json|manifest\.webmanifest|robots\.txt|apple-touch-icon[\w.-]*)$/i;
/**
* Whether a 404 looks like a proxied dashboard's root-absolute request that
* escaped the prefix.
*
* This decides NOTHING about the response — the request cannot be relayed (a
* masked frame's `Referer` carries no capability, which is exactly why the
* Referer fallback above declined). It exists so the failure is diagnosable:
* the symptom of an escaped URL is a blank page or a spinner that never
* resolves, with nothing in the log to say why. Naming the path turns that into
* one grep.
*
* Deliberately conservative — a masked landing frame (`Referer` path `/`), an
* asset-shaped `Sec-Fetch-Dest`, same origin, not the API, not one of Codeman's
* own files. A false positive is a log line, never a behaviour change.
*
* @param input - method, request URL and headers of the 404.
* @returns the escaped path (no query), or null when it is not that shape.
*/
export function escapedWebviewAssetPath(input: {
method: string;
url: string;
headers: Record<string, string | string[] | undefined>;
}): string | null {
if (input.method !== 'GET' && input.method !== 'HEAD') return null;
const path = input.url.split('?')[0] ?? '';
if (path.startsWith('/api') || CODEMAN_OWN_404.test(path)) return null;
const single = (value: string | string[] | undefined): string | undefined =>
Array.isArray(value) ? value[0] : value;
const dest = single(input.headers['sec-fetch-dest']);
if (!dest || !ASSET_FETCH_DESTS.has(dest.toLowerCase())) return null;
const host = single(input.headers.host);
const referer = single(input.headers.referer);
if (!host || !referer) return null;
try {
const from = new URL(referer);
// Same origin, and the masked landing path: a real Codeman page's assets all
// resolve, so a 404 from one is not this shape.
if (from.host !== host || from.pathname !== '/') return null;
} catch {
return null;
}
return path;
}
/** Remove the `frame-ancestors` directive from a CSP, preserving the rest. */
export function stripFrameAncestors(csp: string): string {
return csp
@@ -363,20 +296,6 @@ export function rewriteSetCookie(cookie: string, capability: string, secureConte
return out.join('; ');
}
/**
* Put a server-held credential in front of the cookies the browser sent.
*
* Order matters: a `Cookie` header can name the same cookie twice, and parsers
* that collapse it into a map keep the FIRST value (RFC 6265 §5.4 leaves the
* choice open; the common Node parsers take the first). The browser may still
* hold a stale copy of the same dsh cookie from an earlier proxied response, so
* the credential minted by the running process must lead, with everything else
* preserved behind it.
*/
export function mergeCookieHeader(browserCookie: string | undefined, injectedCookie: string): string {
return browserCookie ? `${injectedCookie}; ${browserCookie}` : injectedCookie;
}
/** Drop named cookies from a `Cookie` request header, returning undefined if none remain. */
export function filterCookieHeader(cookie: string | undefined, drop: string[]): string | undefined {
if (!cookie) return undefined;
@@ -392,21 +311,7 @@ export function filterCookieHeader(cookie: string | undefined, drop: string[]):
export function buildUpstreamRequestHeaders(
incoming: Record<string, string | string[] | undefined>,
upstream: URL,
opts: {
forwardCookies: boolean;
sessionCookieName: string;
refererPath?: string;
relayBodyLength?: boolean;
/**
* A credential the SERVER holds for this dashboard, put in front of whatever
* browser cookies were forwarded (see `mergeCookieHeader` for why the order
* matters). `dsh web` mints its session cookie for a loopback authority the
* browser never visits, so the proxy is the only party that can present it
* (see `deepseek-web-server.ts`); the managed tab is trusted, which means the
* browser may also carry other cookies dsh set, and those must survive.
*/
injectedCookie?: string;
}
opts: { forwardCookies: boolean; sessionCookieName: string; refererPath?: string; relayBodyLength?: boolean }
): Record<string, string> {
const headers: Record<string, string> = {};
@@ -438,14 +343,6 @@ export function buildUpstreamRequestHeaders(
if (cookie) headers['cookie'] = cookie;
}
// In front of the relayed cookies rather than after them, so a stale browser
// copy of the same cookie cannot shadow the one minted by the running process
// (the parser keeps the first value). Other cookies are kept: a managed dsh tab
// is trusted, so dsh's own non-auth cookies may legitimately be there.
if (opts.injectedCookie) {
headers['cookie'] = mergeCookieHeader(headers['cookie'], opts.injectedCookie);
}
// Present as if the browser were talking to the dashboard directly. Apps that
// check Origin on writes (CSRF defenses) need this to match their own origin.
headers['origin'] = upstream.origin;
@@ -749,79 +646,6 @@ try{
}catch(e){}})();</script>`;
}
/**
* Make a page's own RELATIVE `<base href>` absolute under the proxy prefix.
*
* A base element is resolved against the document's URL, and {@link runtimeUrlShim}
* deliberately rewrites that URL to strip the proxy prefix. So a page shipping
* `<base href="./">` — which is what a Vite build does, DeepSeek Harness among
* them — has its base re-resolved to Codeman's ROOT the moment the shim runs:
* every module script, stylesheet and `fetch('./api')` then asks the Codeman
* origin instead of the dashboard. The visible symptom is not an error page but
* a blank one: the markup and inline `<style>` paint (dsh paints a dark
* `#151517`), the module 404s, and nothing else ever renders.
*
* Resolving it here, while the prefix is still known, keeps the author's target
* (the document as it existed before masking) and is idempotent: an
* already-absolute path resolves to itself. Cross-origin bases are the author
* pointing at a CDN and are left exactly as written.
*
* The document path matters: a base in `/webview/<cap>/app/page.html` is
* relative to `/webview/<cap>/app/`, not to the proxy root, or a page served
* from a subdirectory would resolve its assets one level too high.
*
* @param html - document with attributes already rebased.
* @param prefix - proxy prefix the document was served from.
* @param documentPath - upstream path of the document, without the leading slash.
* @returns the document with a relative base href made absolute.
*/
function rebaseRelativeBase(html: string, prefix: string, documentPath: string): string {
const documentUrl = `http://codeman.invalid${prefix}${documentPath.replace(/^\/+/, '')}`;
return html.replace(
/(<base\b[^>]*?\bhref\s*=\s*)(["'])([^"']*)\2/i,
(match: string, head: string, quote: string, href: string) => {
let resolved: URL;
try {
// A stand-in origin: only the path is kept, and a different origin here
// is exactly the "absolute base" case this must not touch.
resolved = new URL(href, documentUrl);
} catch {
return match;
}
if (resolved.origin !== 'http://codeman.invalid') return match;
return `${head}${quote}${resolved.pathname}${resolved.search}${resolved.hash}${quote}`;
}
);
}
/**
* Rewrite root-absolute specifiers of dynamic `import()` calls in `<script>`
* bodies.
*
* A dynamic import is the one URL no other layer can reach: it is not an
* attribute, so `<base>` does not apply to it; it is not `fetch()`, so the runtime
* shim cannot rewrite it; and the browser resolves it against the ORIGIN root, not
* the document. SvelteKit's inline bootstrap is exactly this shape
* (`import("/_app/…")`), and the failure mode is silent: the module 404s against
* Codeman and the app's own loading spinner never resolves.
*
* ⚠️ Scoped to script bodies on purpose. Running the same regex over the whole
* document also rewrote visible text — `<pre>import("/x")</pre>` became a broken
* example — which is a rendering bug, not a loader the browser was going to run.
*
* @param html - document with attributes already rebased.
* @param prefix - proxy prefix to put in front of a `/`-rooted specifier.
*/
function rewriteScriptImports(html: string, prefix: string): string {
return html.replace(
/(<script\b[^>]*>)([^]*?)(<\/script>)/gi,
(_match: string, open: string, body: string, close: string) =>
open +
body.replace(/\bimport\s*\(\s*(["'])\/(?!\/)/g, (_import: string, quote: string) => `import(${quote}${prefix}`) +
close
);
}
/**
* Inject `<base href="/webview/<cap>/">` plus the runtime URL shim, and rebase
* root-absolute `src`/`href`/`action` attributes, which `<base>` alone does not
@@ -830,27 +654,14 @@ function rewriteScriptImports(html: string, prefix: string): string {
* Three layers, because no single one is sufficient: `<base>` for parser-resolved
* relative URLs, attribute rewriting for root-absolute markup, and the shim for
* URLs built at runtime.
*
* @param html - the upstream document.
* @param capability - capability the document is being served under.
* @param basePath - reverse-proxy mount prefix (`''` at root).
* @param documentPath - upstream path of the document, without the leading slash.
* Used to resolve the page's own relative `<base>` against its directory.
*/
export function rewriteHtml(html: string, capability: string, basePath = '', documentPath = ''): string {
export function rewriteHtml(html: string, capability: string, basePath = ''): string {
const prefix = proxyPrefixFor(capability, basePath);
// Fresh regexes per call: module-level /g patterns carry `lastIndex` between calls.
const rebased = rebaseRelativeBase(
rewriteScriptImports(
html
.replace(/(\s(?:src|href|action)\s*=\s*")\/(?!\/)/gi, `$1${prefix}`)
.replace(/(\s(?:src|href|action)\s*=\s*')\/(?!\/)/gi, `$1${prefix}`),
prefix
),
prefix,
documentPath
);
const rebased = html
.replace(/(\s(?:src|href|action)\s*=\s*")\/(?!\/)/gi, `$1${prefix}`)
.replace(/(\s(?:src|href|action)\s*=\s*')\/(?!\/)/gi, `$1${prefix}`);
// A page that ships its own <base> keeps it (overriding it would break the
// author's intent), but it STILL needs the shim, which is the layer that
+4 -3
View File
@@ -40,7 +40,6 @@ import { join } from 'node:path';
import { watch as chokidarWatch, type FSWatcher as ChokidarWatcher } from 'chokidar';
import type { WorkflowRunInfo, WorkflowRunSummary, WorkflowAgentInfo, WorkflowRunPhase } from './types/workflow-run.js';
import { closeWatcherOnError } from './utils/close-watcher-on-error.js';
import { LRUMap } from './utils/lru-map.js';
import {
WORKFLOW_RUN_POLL_INTERVAL_MS,
@@ -866,8 +865,10 @@ export class WorkflowRunWatcher extends EventEmitter {
// subagents/workflows/ children are wf_<id>/ DIRS — catch their add/remove too.
watcher.on('addDir', handler);
watcher.on('unlinkDir', handler);
// chokidar surfaced an error for this dir — drop the watcher; poll still covers it.
closeWatcherOnError(watcher, () => this.dirWatchers.delete(workflowsDir));
watcher.on('error', () => {
// chokidar surfaced an error for this dir — drop the watcher; poll still covers it.
this.removeDirWatcher(workflowsDir);
});
this.dirWatchers.set(workflowsDir, watcher);
} catch {
// Watch setup failed — periodic poll still discovers changes.
-201
View File
@@ -1,201 +0,0 @@
// test/cjk-hold-per-device-setting.test.ts
// Port: none (static analysis + vm, runs in CI, no browser/server).
//
// Send on Enter for the CJK input field (`cjkInputHoldUntilEnter`) is a
// PER-DEVICE setting like `cjkInputEnabled`: in settings-ui.js's displayKeys
// merge policy, stripped out of the object saveAppSettings() PUTs
// (SettingsUpdateSchema is .strict(), so sending it would 400 every save), and
// never declared in the schema. Plus the pieces around the mode: a held draft
// surviving a reload of the same session, the field staying one line tall with
// the keyboard down, and zh-CN strings for its placeholders.
import { describe, it, expect, vi } from 'vitest';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { join } from 'node:path';
import vm from 'node:vm';
const HERE = fileURLToPath(new URL('.', import.meta.url));
const PUBLIC = join(HERE, '../src/web/public');
const read = (file: string) => readFileSync(join(PUBLIC, file), 'utf8');
describe('cjkInputHoldUntilEnter stays per-device: display key, stripped from the PUT, absent from the schema', () => {
const settingsUi = read('settings-ui.js');
const schemas = readFileSync(join(HERE, '../src/web/schemas.ts'), 'utf8');
it('is in the client-side displayKeys merge policy', () => {
const start = settingsUi.indexOf('const displayKeys = new Set([');
const displayKeys = settingsUi.slice(start, settingsUi.indexOf('])', start));
expect(displayKeys).toContain("'cjkInputHoldUntilEnter'");
});
it('is stripped out of the object saveAppSettings() PUTs to the server', () => {
expect(settingsUi).toContain('cjkInputHoldUntilEnter: _cjkHold,');
});
it('is never declared in the .strict() SettingsUpdateSchema', () => {
expect(schemas).not.toContain('cjkInputHoldUntilEnter');
});
it('defaults OFF on handhelds, next to cjkInputEnabled', () => {
expect(settingsUi).toMatch(/cjkInputEnabled: false,\s*cjkInputHoldUntilEnter: false,/);
});
it('is loaded into and saved from its App Settings switch', () => {
expect(read('index.html')).toContain('id="appSettingsCjkHoldUntilEnter"');
expect(settingsUi).toContain("document.getElementById('appSettingsCjkHoldUntilEnter').checked =");
expect(settingsUi).toContain(
"cjkInputHoldUntilEnter: document.getElementById('appSettingsCjkHoldUntilEnter').checked,"
);
});
});
describe('a held draft survives a reload of the same session', () => {
// The REAL _cleanupPreviousSession from app.js. selectSession() nulls
// activeSessionId before calling it on a same-session forceReload (tapping the
// tab already shown, the geometry retry), so it is told through keepCjkDraft.
function cleanup(hold: boolean, keepCjkDraft: boolean, outgoing: string | null = null) {
const clear = vi.fn();
const stashDraft = vi.fn();
const context = vm.createContext({
console,
setTimeout,
clearTimeout,
setInterval: vi.fn(),
clearInterval: vi.fn(),
requestAnimationFrame: vi.fn(),
HTMLCanvasElement: class HTMLCanvasElement {},
WebSocket: { OPEN: 1 },
fetch: vi.fn(),
URLSearchParams,
document: { addEventListener: vi.fn(), documentElement: { dataset: {} }, getElementById: () => null },
localStorage: { length: 0, key: vi.fn(), getItem: vi.fn(), setItem: vi.fn(), removeItem: vi.fn() },
window: { addEventListener: vi.fn(), removeEventListener: vi.fn() },
MobileDetection: { isTouchDevice: () => true, isHandheldDevice: () => true, getDeviceType: () => 'mobile' },
CjkInput: { holdUntilEnter: hold, clear, stashDraft },
});
vm.runInContext(`${read('constants.js')}\n${read('app.js')}\nglobalThis.__CodemanApp = CodemanApp;`, context);
const CodemanApp = (context as unknown as { __CodemanApp: { prototype: object } }).__CodemanApp;
const app = Object.create(CodemanApp.prototype) as Record<string, unknown> & {
_cleanupPreviousSession(id: string, opts?: { keepCjkDraft?: boolean }): void;
};
app.activeSessionId = outgoing;
app.sessions = new Map();
app._clearTimer = vi.fn();
app._disconnectWs = vi.fn();
app._xtermSnapshots = new Map();
app.pendingWrites = [];
app._cleanupPreviousSession('s1', { keepCjkDraft });
return Object.assign(clear, { stashDraft });
}
it('keeps the draft on a same-session reload in Send on Enter mode', () => {
expect(cleanup(true, true)).not.toHaveBeenCalled();
});
it('still clears on a real switch', () => {
expect(cleanup(true, false)).toHaveBeenCalled();
});
it('still clears in live mode, where a pending flush could fire mid-reconnect', () => {
expect(cleanup(false, true)).toHaveBeenCalled();
});
it('stashes the held draft of the session being left before clearing', () => {
const clear = cleanup(true, false, 's0');
expect(clear.stashDraft).toHaveBeenCalledWith('s0');
expect(clear.stashDraft.mock.invocationCallOrder[0]).toBeLessThan(clear.mock.invocationCallOrder[0]);
});
it('selectSession restores the draft of the session it lands on', () => {
// After _activateFileBrowserSession: test/file-browser-search.test.ts pins
// that call as the line right after the activeSessionId assignment.
expect(read('app.js')).toContain(
"this.activeSessionId = sessionId;\n this._activateFileBrowserSession?.(sessionId);\n if (typeof CjkInput !== 'undefined') CjkInput.restoreDraft?.(sessionId);"
);
});
it('leaving the tile grid for another session stashes the focused tile draft', () => {
// selectSession nulls activeSessionId there, which hides the tile from
// _cleanupPreviousSession.
expect(read('app.js')).toMatch(
/CjkInput\.stashDraft\?\.\(this\.activeSessionId\);\n(?:\s*\/\/.*\n)*\s*this\.activeSessionId = null;/
);
});
it('tile focus does not stash again for a tile closed from this tab', () => {
// removeSession discards the closed session's draft first; a stash after
// that would keep it in the map until the page reloads.
expect(read('tile-grid.js')).toContain(
'if (this.sessions?.has(this.activeSessionId)) CjkInput.stashDraft?.(this.activeSessionId);'
);
});
it('tile focus stashes the draft of the tile left and restores the focused one', () => {
const tiles = read('tile-grid.js');
const start = tiles.indexOf(' _selectTiledSession(sessionId, options = {}) {');
const body = tiles.slice(start, tiles.indexOf('grid.focusedId = sessionId;', start));
expect(body).toMatch(
/CjkInput\.stashDraft\?\.\(this\.activeSessionId\);\s*CjkInput\.clear\(\);\s*\}\s*CjkInput\.restoreDraft\?\.\(sessionId\);\s*\}\s*this\.activeSessionId = sessionId;/
);
});
it('going Home stashes the draft of the session it leaves', () => {
const appJs = read('app.js');
const start = appJs.indexOf(' goHome() {');
const body = appJs.slice(start, appJs.indexOf('this.activeSessionId = null;', start));
expect(body).toContain('CjkInput.stashDraft?.(this.activeSessionId);');
});
it('a removed session drops its stashed draft', () => {
expect(read('app.js')).toMatch(
/discardComposerDraft\?\.\(sessionId\);\n\s*if \(typeof CjkInput !== 'undefined'\) CjkInput\.discardDraft\?\.\(sessionId\);/
);
});
it('selectSession passes the same-session flag it captured before nulling activeSessionId', () => {
const appJs = read('app.js');
expect(appJs).toMatch(
/if \(this\.activeSessionId === sessionId && forceReload\) \{\s*reloadingSameSession = true;/
);
expect(appJs).toContain('this._cleanupPreviousSession(sessionId, { keepCjkDraft: reloadingSameSession });');
});
});
describe('Send on Enter field layout and strings', () => {
it('keeps the field one line tall while the keyboard is down', () => {
// .main reserves a fixed 84px there; a grown field would cover the terminal.
expect(read('styles.css')).toMatch(
/\.touch-device:not\(\.keyboard-visible\) #cjkInput\.cjk-input-visible \{\s*max-height: 34px;\s*\}/
);
});
it('caps the field on every device, not only in the .touch-device rule', () => {
// The setting is not limited to phones; on desktop an uncapped field grew to
// 502px at 25 lines and resized the PTY on every step.
const css = read('styles.css');
const base = css.slice(css.indexOf('#cjkInput {'), css.indexOf('}', css.indexOf('#cjkInput {')));
expect(base).toContain('max-height: 68px;');
expect(base).toContain('overflow-y: auto;');
});
it('the phone toolbar Enter presses Enter in the visible CJK field', () => {
// onData drops everything while cjkActive, so the xterm path does nothing.
const sessionUi = read('session-ui.js');
const start = sessionUi.indexOf(' sendEnterKey() {');
const body = sessionUi.slice(start, sessionUi.indexOf('triggerDataEvent', start));
expect(body).toContain("classList.contains('cjk-input-visible')");
expect(body).toContain('CjkInput.submit?.();');
});
it('has zh-CN strings for both field placeholders', () => {
const i18n = read('i18n.js');
const cjk = read('input-cjk.js');
for (const placeholder of [
'CJK input (Enter = send, Esc = clear)',
'Type, Enter to send (Shift+Enter: new line, Esc: clear)',
]) {
expect(cjk).toContain(`'${placeholder}'`);
expect(i18n.split(`'${placeholder}':`).length - 1).toBe(1);
}
});
});
+1 -1
View File
@@ -172,7 +172,7 @@ describe('registered arguments', () => {
['attach', ['path']],
['start', []],
// Optional: bare `codeman tui` opens the dashboard.
['tui', ['session']],
['tui', ['n']],
])('declares the operands of `%s`', (name, expected) => {
const args = find(program, name)!.registeredArguments.map((arg) => arg.name());
expect(args).toEqual(expected);
@@ -435,6 +435,7 @@ describe('declared-for-later fields', () => {
const DECLARED_FOR_LATER = [
'accent',
'capabilities.echo',
'capabilities.wheelForward',
'capabilities.keyboardAccessory',
'capabilities.maxFrameBytes',
// The Docker credential-seeding path still reads its own CRED_STORES table: this shape
-77
View File
@@ -1,77 +0,0 @@
/**
* @fileoverview The header CPU reading's meter: busy time over all cores between readings, the minimum window
* that keeps several browsers from shrinking it, and the fallback when no usable core times exist.
*/
import { describe, expect, it } from 'vitest';
import { createCpuUsageMeter } from '../src/cpu-usage.js';
const core = (busy: number, idle: number) => ({ times: { user: busy, nice: 0, sys: 0, idle, irq: 0 } });
function meterOver(samples: ReturnType<typeof core>[][], fallback = () => 999) {
let at = 0;
let index = 0;
const meter = createCpuUsageMeter(
() => samples[Math.min(index, samples.length - 1)],
() => at,
fallback
);
return (ms: number) => {
at += ms;
index += 1;
return meter();
};
}
describe('createCpuUsageMeter', () => {
it('reports busy time over all cores between readings', () => {
const next = meterOver([
[core(0, 0), core(0, 0)],
[core(50, 50), core(50, 50)],
[core(150, 50), core(50, 150)],
]);
expect(next(2000)).toBe(50);
expect(next(2000)).toBe(50);
});
it('counts nice, system and interrupt time as busy', () => {
const times = (user: number, nice: number, sys: number, irq: number, idle: number) => ({
times: { user, nice, sys, idle, irq },
});
const meter = createCpuUsageMeter(
(() => {
let calls = 0;
return () => [calls++ === 0 ? times(0, 0, 0, 0, 0) : times(10, 20, 30, 15, 25)];
})(),
(() => {
let at = 0;
return () => (at += 2000);
})(),
() => 999
);
expect(meter()).toBe(75);
});
it('reads idle cores as idle however long the run queue is', () => {
expect(meterOver([[core(0, 0)], [core(40, 60)]])(5000)).toBe(40);
});
it('reuses the last value for readings under a second apart and keeps the baseline', () => {
const next = meterOver([[core(0, 0)], [core(30, 70)], [core(30, 170)], [core(130, 170)]]);
expect(next(2000)).toBe(30);
expect(next(200)).toBe(30);
expect(next(2000)).toBe(50);
});
it('falls back without a bogus reading when there are no core times or the counters go backwards', () => {
expect(meterOver([[], []], () => 7)(2000)).toBe(7);
const next = meterOver([[core(100, 100)], [core(10, 10)], [core(60, 60)]], () => 7);
expect(next(2000)).toBe(7);
expect(next(2000)).toBe(50);
});
it('answers a whole number from 0 to 100', () => {
expect(meterOver([[core(0, 0)], [core(2, 1)]])(2000)).toBe(67);
expect(meterOver([[core(0, 0)], [core(0, 9)]])(2000)).toBe(0);
expect(meterOver([[core(0, 0)], [core(9, 0)]])(2000)).toBe(100);
});
});
+2 -362
View File
@@ -12,25 +12,10 @@
* 2. The supervisor tracks at most ONE server. The status accessor is what every
* caller reads to decide whether to start another, so "no server" must report
* as absent rather than as a half-populated record.
* 3. `dsh web` now gates its index behind a launch token it prints on boot. The
* supervisor is the only party that can trade it, and the cookie it produces
* is authority-bound: getting that wrong is a blank tab, not a visible error.
*/
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import http from 'node:http';
import { describe, expect, it, beforeEach } from 'vitest';
import { DeepSeekWebStartSchema } from '../src/web/schemas.js';
import {
getDeepSeekWebCookie,
getDeepSeekWebStatus,
launchUrlTargetsServer,
parseLaunchUrl,
resetDeepSeekWebForTest,
startDeepSeekWeb,
stopDeepSeekWeb,
} from '../src/deepseek-web-server.js';
import { getDeepSeekWebStatus, resetDeepSeekWebForTest, stopDeepSeekWeb } from '../src/deepseek-web-server.js';
describe('DeepSeekWebStartSchema: the authority reaching --trusted-host', () => {
it('accepts the authority shapes a browser can actually report', () => {
@@ -86,348 +71,3 @@ describe('DeepSeek web supervisor: status', () => {
expect(getDeepSeekWebStatus().running).toBe(false);
});
});
describe('parseLaunchUrl: the one-time token dsh prints on boot', () => {
it('pulls the URL out of the banner a real boot writes', () => {
const output = ['dsh web: http://127.0.0.1:3080/?token=0Yb3sJk9Qm2xLd7Tf1Vc', 'ready'].join('\n');
expect(parseLaunchUrl(output)).toBe('http://127.0.0.1:3080/?token=0Yb3sJk9Qm2xLd7Tf1Vc');
});
it('sees through SGR colouring, which would otherwise hide the token', () => {
const output = '\u001b[36mdsh web:\u001b[0m \u001b[4mhttp://127.0.0.1:3080/?token=abc123\u001b[0m\n';
expect(parseLaunchUrl(output)).toBe('http://127.0.0.1:3080/?token=abc123');
});
// dsh prints diagnostics under the same prefix before the banner. Taking the
// FIRST match made the real URL invisible and boot gave up 4 seconds later.
it('skips a diagnostic line and keeps scanning for the URL', () => {
expect(parseLaunchUrl('dsh web: loading profiles\ndsh web: http://127.0.0.1:3080/?token=abc\n')).toBe(
'http://127.0.0.1:3080/?token=abc'
);
});
it('skips a URL without a token and keeps scanning for the token one', () => {
expect(parseLaunchUrl('dsh web: http://127.0.0.1:3080/\ndsh web: http://127.0.0.1:3080/?token=abc\n')).toBe(
'http://127.0.0.1:3080/?token=abc'
);
});
it('returns null for a token-less banner, which is the older dsh', () => {
expect(parseLaunchUrl('dsh web: http://127.0.0.1:3080/\n')).toBeNull();
});
it('refuses anything that is not an http(s) URL carrying a token', () => {
expect(parseLaunchUrl('')).toBeNull();
expect(parseLaunchUrl('booting...')).toBeNull();
expect(parseLaunchUrl('dsh web: javascript:alert(1)?token=x')).toBeNull();
expect(parseLaunchUrl('dsh web: not a url?token=x')).toBeNull();
});
});
describe('launchUrlTargetsServer: the exchange must hit the spawned port', () => {
it('accepts only 127.0.0.1 on the port that was just spawned', () => {
expect(launchUrlTargetsServer('http://127.0.0.1:3080/?token=x', 3080)).toBe(true);
expect(launchUrlTargetsServer('http://127.0.0.1:3081/?token=x', 3080)).toBe(false);
expect(launchUrlTargetsServer('http://localhost:3080/?token=x', 3080)).toBe(false);
expect(launchUrlTargetsServer('http://evil.example:3080/?token=x', 3080)).toBe(false);
expect(launchUrlTargetsServer('not a url', 3080)).toBe(false);
});
});
describe('DeepSeek web supervisor: the launch-token cookie', () => {
let dir: string;
beforeEach(() => {
resetDeepSeekWebForTest();
dir = mkdtempSync(join(tmpdir(), 'codeman-dsh-web-'));
});
afterEach(async () => {
await stopDeepSeekWeb();
rmSync(dir, { recursive: true, force: true });
});
/**
* A stand-in for `dsh web` with the browser-auth gate: prints the banner,
* refuses `/` without a cookie, and trades the token for one 303.
*/
const FAKE_DSH = `#!/usr/bin/env node
const http = require('node:http');
const portArg = process.argv.indexOf('--port');
const port = Number(process.argv[portArg + 1]);
const token = 'test-launch-token';
const cookie = 'dsh-auth-test=v1.payload.sig';
process.stdout.write('dsh web: http://127.0.0.1:' + port + '/?token=' + token + '\\n');
http
.createServer((req, res) => {
const url = new URL(req.url, 'http://127.0.0.1:' + port);
if (url.pathname === '/' && url.searchParams.get('token') === token) {
res.writeHead(303, { location: './', 'set-cookie': cookie + '; Path=/; HttpOnly' });
res.end();
return;
}
if (req.headers.cookie === cookie) {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
res.end('<!doctype html><title>harness</title>');
return;
}
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1');
`;
it('trades the boot token for the cookie, scoped to its own port', async () => {
writeFileSync(join(dir, 'dsh'), FAKE_DSH, { mode: 0o755 });
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
// Before the exchange this page is exactly the blank tab being fixed: 401.
expect((await fetch(`http://127.0.0.1:${result.port}/`)).status).toBe(401);
expect(getDeepSeekWebCookie(result.port)).toBe('dsh-auth-test=v1.payload.sig');
// A credential minted for this authority must never travel to another port.
expect(getDeepSeekWebCookie(result.port + 1)).toBeNull();
const authed = await fetch(`http://127.0.0.1:${result.port}/`, {
headers: { cookie: getDeepSeekWebCookie(result.port) as string },
});
expect(authed.status).toBe(200);
}, 20_000);
// `managed` is a client-supplied field and the port is published by
// GET /api/deepseek/web, so the supervisor additionally binds the cookie to the
// identity whose request started the process: another user's tab must not be
// handed it, and their POST must not reuse bob's server either.
it('hands the cookie only to the identity that started the server', async () => {
writeFileSync(join(dir, 'dsh'), FAKE_DSH, { mode: 0o755 });
const bob = await startDeepSeekWeb(dir, 'localhost:3000', 'bob');
expect(bob.ok).toBe(true);
if (!bob.ok) return;
expect(getDeepSeekWebCookie(bob.port, 'bob')).toBe('dsh-auth-test=v1.payload.sig');
expect(getDeepSeekWebCookie(bob.port)).toBeNull();
expect(getDeepSeekWebCookie(bob.port, 'alice')).toBeNull();
// A different owner restarts rather than reusing bob's cookie.
const alice = await startDeepSeekWeb(dir, 'localhost:3000', 'alice');
expect(alice.ok).toBe(true);
if (!alice.ok) return;
expect(alice.reused).toBe(false);
expect(getDeepSeekWebCookie(alice.port, 'alice')).toBe('dsh-auth-test=v1.payload.sig');
expect(getDeepSeekWebCookie(alice.port, 'bob')).toBeNull();
}, 20_000);
// A failed exchange leaves a server that answers 401 to everything. Reuse used
// to hand that same server back on every POST, so the restart the warning asks
// for could never happen. The next start request must perform it.
it('restarts rather than reusing a server whose exchange failed', async () => {
writeFileSync(
join(dir, 'dsh'),
`#!/usr/bin/env node
const fs = require('node:fs');
const http = require('node:http');
const path = require('node:path');
const port = Number(process.argv[process.argv.indexOf('--port') + 1]);
const token = 'retry-token';
const cookie = 'dsh-auth-retry=v1.sig';
const marker = path.join(__dirname, '.exchange-failed');
const failedBefore = fs.existsSync(marker);
if (!failedBefore) fs.writeFileSync(marker, '1');
process.stdout.write('dsh web: http://127.0.0.1:' + port + '/?token=' + token + '\\n');
http
.createServer((req, res) => {
const url = new URL(req.url, 'http://127.0.0.1:' + port);
if (url.searchParams.get('token') === token) {
if (!failedBefore) {
res.writeHead(500, { 'content-type': 'text/plain' });
res.end('temporary failure');
return;
}
res.writeHead(303, { location: './', 'set-cookie': cookie + '; Path=/' });
res.end();
return;
}
if (req.headers.cookie === cookie) {
res.writeHead(200, { 'content-type': 'text/html' });
res.end('<html>ok</html>');
return;
}
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1');
`,
{ mode: 0o755 }
);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
const first = await startDeepSeekWeb(dir, 'localhost:3000');
expect(first.ok).toBe(true);
if (!first.ok) return;
expect(getDeepSeekWebCookie(first.port)).toBeNull();
expect(warn).toHaveBeenCalledWith(expect.stringContaining('could not be exchanged'));
} finally {
warn.mockRestore();
}
const second = await startDeepSeekWeb(dir, 'localhost:3000');
expect(second.ok).toBe(true);
if (!second.ok) return;
expect(second.reused).toBe(false);
expect(getDeepSeekWebCookie(second.port)).toBe('dsh-auth-retry=v1.sig');
// The recovered server is healthy again, so ordinary reuse resumes.
const third = await startDeepSeekWeb(dir, 'localhost:3000');
expect(third.ok).toBe(true);
if (!third.ok) return;
expect(third.reused).toBe(true);
}, 20_000);
// The exchange is a request made by the SERVER. A banner naming another local
// port would let captured child output aim it, so the URL is judged before it
// is fetched at all.
it('does not fetch a banner naming another port', async () => {
const hits: string[] = [];
const target = http.createServer((req, res) => {
hits.push(req.url ?? '');
res.writeHead(200, { 'content-type': 'text/plain' });
res.end('should never be reached');
});
await new Promise<void>((resolve) => target.listen(0, '127.0.0.1', resolve));
const address = target.address();
if (!address || typeof address === 'string') throw new Error('target has no address');
try {
writeFileSync(
join(dir, 'dsh'),
`#!/usr/bin/env node
const http = require('node:http');
const port = Number(process.argv[process.argv.indexOf('--port') + 1]);
process.stdout.write('dsh web: http://127.0.0.1:${address.port}/?token=stolen\\n');
http
.createServer((_req, res) => {
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1');
`,
{ mode: 0o755 }
);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(getDeepSeekWebCookie(result.port)).toBeNull();
expect(warn).toHaveBeenCalledWith(expect.stringContaining('not fetching it'));
} finally {
warn.mockRestore();
}
expect(hits).toEqual([]);
} finally {
await new Promise<void>((resolve) => target.close(() => resolve()));
}
}, 20_000);
it('leaves the old, ungated dsh working: no token means no cookie, not a failure', async () => {
writeFileSync(
join(dir, 'dsh'),
'#!/usr/bin/env node\nconst http = require("node:http");\nconst port = Number(process.argv[process.argv.indexOf("--port") + 1]);\nprocess.stdout.write("dsh web: http://127.0.0.1:" + port + "/\\n");\nhttp.createServer((_q, s) => s.end("ok")).listen(port, "127.0.0.1");\n',
{ mode: 0o755 }
);
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(getDeepSeekWebCookie(result.port)).toBeNull();
}, 20_000);
// The error-tail buffer is capped at 16 KB, and a chatty plugin tree can fill
// it before dsh prints its banner. Scanning that buffer alone lost the token
// and put the tab back on the 401 page, so the banner is matched on its own
// (larger) budget.
// The banner can arrive in two stdout writes: `capture()` sees two chunks and
// neither is a complete line. Scanning the raw buffer either missed it or, with
// a partial URL that happened to parse, exchanged a truncated token.
it('waits for a banner split across two output chunks', async () => {
writeFileSync(
join(dir, 'dsh'),
`#!/usr/bin/env node
const http = require('node:http');
const port = Number(process.argv[process.argv.indexOf('--port') + 1]);
const token = 'split-token';
const cookie = 'dsh-auth-split=v1.sig';
process.stdout.write('dsh web: loading profiles\\n');
http
.createServer((req, res) => {
const url = new URL(req.url, 'http://127.0.0.1:' + port);
if (url.searchParams.get('token') === token) {
res.writeHead(303, { location: './', 'set-cookie': cookie + '; Path=/' });
res.end();
return;
}
if (req.headers.cookie === cookie) {
res.writeHead(200, { 'content-type': 'text/html' });
res.end('<html>ok</html>');
return;
}
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1', () => {
const line = 'dsh web: http://127.0.0.1:' + port + '/?token=' + token + '\\n';
process.stdout.write(line.slice(0, 30));
setTimeout(() => process.stdout.write(line.slice(30)), 150);
});
`,
{ mode: 0o755 }
);
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(getDeepSeekWebCookie(result.port)).toBe('dsh-auth-split=v1.sig');
}, 20_000);
it('still finds a banner printed after more than the error-tail cap', async () => {
writeFileSync(
join(dir, 'dsh'),
`#!/usr/bin/env node
const http = require('node:http');
const port = Number(process.argv[process.argv.indexOf('--port') + 1]);
const token = 'late-banner-token';
const cookie = 'dsh-auth-late=v1.sig';
process.stdout.write('warn: plugin noise '.repeat(1100) + '\\n');
http
.createServer((req, res) => {
const url = new URL(req.url, 'http://127.0.0.1:' + port);
if (url.searchParams.get('token') === token) {
res.writeHead(303, { location: './', 'set-cookie': cookie + '; Path=/' });
res.end();
return;
}
if (req.headers.cookie === cookie) {
res.writeHead(200, { 'content-type': 'text/html' });
res.end('<html>ok</html>');
return;
}
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1');
setTimeout(() => process.stdout.write('dsh web: http://127.0.0.1:' + port + '/?token=' + token + '\\n'), 300);
`,
{ mode: 0o755 }
);
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(getDeepSeekWebCookie(result.port)).toBe('dsh-auth-late=v1.sig');
}, 20_000);
});
+40
View File
@@ -164,6 +164,46 @@ async function everyState(browser: Browser) {
await native({ type: 'init', servers: [{ url: 'http://127.0.0.1:3000/' }], autoConnect: true, version: '0.1.0' });
check('manual=1 suppresses auto-connect', (await posted()).length === 1, await posted());
// 3b. A server tab opened again at launch: its own server, connected to on its own
// (manual=1 holds for any other server), and only shown when connectNow is off.
const saved = [
{ url: 'http://127.0.0.1:3000/' },
{ url: 'https://box.tail.ts.net/', username: 'admin', hasSavedPassword: true },
];
await page.goto('http://app.test/index.html?manual=1');
await native({
type: 'init',
servers: saved,
autoConnect: true,
version: '0.1.0',
target: saved[1].url,
connectNow: true,
});
p = await posted();
check(
'a restored tab connects to its own server, with its saved login',
p.length === 2 && p[1].cmd === 'connect' && p[1].url === 'https://box.tail.ts.net/' && p[1].username === 'admin',
p
);
check('and shows it on the Another machine tab', await visible('#form'));
await page.goto('http://app.test/index.html?manual=1');
await native({
type: 'init',
servers: saved,
autoConnect: false,
version: '0.1.0',
target: 'http://192.168.1.40:3000/',
connectNow: false,
});
check('connectNow off only fills the address in', (await posted()).length === 1, await posted());
check(
'a server not in the list still fills the address',
(await page.inputValue('#url')) === 'http://192.168.1.40:3000/'
);
// Back to step 3's page, which the steps below build on.
await page.goto('http://app.test/index.html?manual=1');
await native({ type: 'init', servers: [{ url: 'http://127.0.0.1:3000/' }], autoConnect: true, version: '0.1.0' });
// 4. Needs login -> login fields, then a typed password goes out.
await native({
type: 'probeResult',
+850
View File
@@ -0,0 +1,850 @@
/**
* @fileoverview The Codeman Desktop server-tab pages (packages/desktop/assets/tabs.html, the strip
* across the top of the window, and packages/desktop/assets/overview.html, "All servers"), driven
* in a real browser.
*
* Both pages ask the native side for things with `window.ipc.postMessage(JSON)` and hear back
* through `window.__codemanTabs.onNative(msg)` / `window.__codemanOverview.onNative(msg)`: here a
* stub records the first and the test plays the second. The pages are served with the
* Content-Security-Policy the app serves them with, read out of packages/desktop/src/assets.rs, so
* a script that policy would block fails here as it would in the app.
*
* Chromium stands in for the app's WKWebView, so what this pins is the pages' own logic and layout,
* not WebKit's rendering.
*
* Each test is one ordered walk (a later step builds on the state the earlier ones left), so a walk
* collects every check that fails and reports them together.
*
* Browser-driven, so excluded from `npm test` (config/test-suites.ts). Run locally:
* npm run test:browser -- test/desktop-tabs-pages.browser.test.ts
*
* Port: N/A (the pages are served by request interception; nothing listens).
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { chromium, type Browser, type Page } from 'playwright';
const PKG = resolve(import.meta.dirname, '../packages/desktop');
const PAGES: Record<string, string> = {
'tabs.html': readFileSync(resolve(PKG, 'assets/tabs.html'), 'utf8'),
'overview.html': readFileSync(resolve(PKG, 'assets/overview.html'), 'utf8'),
};
const assetsRs = readFileSync(resolve(PKG, 'src/assets.rs'), 'utf8');
// The app's real CSP (assets::CSP, shared by every bundled page).
const CSP = /const CSP: &str = "([^"]*)";/.exec(assetsRs)![1];
// The native side as the page sees it: `ipc.postMessage` records what the page asks for.
const IPC_STUB = `window.__posted = []; Object.defineProperty(window, 'ipc', { value: Object.freeze({ postMessage: function (s) { window.__posted.push(JSON.parse(s)); } }) });`;
/* eslint-disable @typescript-eslint/no-explicit-any */
declare global {
interface Window {
__posted: any[];
__codemanTabs: { onNative(msg: unknown): void };
__codemanOverview: { onNative(msg: unknown): void };
ipc: { postMessage(message: string): void };
}
}
/** The checks of the walk under way that did not hold, as `name -> what was seen`. */
const failed: string[] = [];
function check(name: string, cond: unknown, extra?: unknown) {
if (!cond) failed.push(extra === undefined ? name : `${name} -> ${JSON.stringify(extra)}`);
}
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
const HOSTILE = '<img src=x onerror=alert(1)>';
const BAD_COLOR = 'red;background:url(x)';
const FALLBACK_RGB = 'rgb(148, 163, 184)';
interface Opened {
page: Page;
close(): Promise<void>;
/** What the page posted since the last call, then forgets it. */
take(): Promise<any[]>;
native(msg: unknown): Promise<void>;
errors: string[];
cspViolations: string[];
dialogs: string[];
}
async function open(
browser: Browser,
file: 'tabs.html' | 'overview.html',
viewport: { width: number; height: number },
reducedMotion: 'reduce' | 'no-preference' = 'no-preference'
): Promise<Opened> {
const ctx = await browser.newContext({ viewport, deviceScaleFactor: 1, reducedMotion });
const page = await ctx.newPage();
const errors: string[] = [];
const cspViolations: string[] = [];
const dialogs: string[] = [];
page.on('pageerror', (e) => errors.push(e.message));
page.on('console', (m) => {
if (/Content Security Policy/i.test(m.text())) cspViolations.push(m.text());
});
page.on('dialog', (d) => {
dialogs.push(d.message());
void d.dismiss();
});
await page.route('http://app.test/**', (route) =>
route.fulfill({
body: PAGES[file],
contentType: 'text/html; charset=utf-8',
headers: { 'Content-Security-Policy': CSP },
})
);
await page.addInitScript(IPC_STUB);
await page.goto('http://app.test/' + file);
const global = file === 'tabs.html' ? '__codemanTabs' : '__codemanOverview';
return {
page,
close: () => ctx.close(),
take: () => page.evaluate(() => window.__posted.splice(0)),
native: (msg) => page.evaluate(([g, m]) => (window as any)[g as string].onNative(m), [global, msg] as const),
errors,
cspViolations,
dialogs,
};
}
// ---------------------------------------------------------------------------------------------
// The strip
function tab(id: number, name: string, extra: Record<string, unknown> = {}, status: Record<string, unknown> = {}) {
return {
id,
name,
color: '#22d3ee',
active: false,
kind: 'server',
local: false,
url: `http://${name.replace(/\W/g, '') || 'host'}.lan:3000`,
key: id <= 9 ? id : null,
status: { working: 0, waiting: 0, needsYou: 0, offline: false, ...status },
...extra,
};
}
const STRIP_TABS = [
tab(1, 'This Mac', { color: '#a78bfa', local: true, url: 'http://127.0.0.1:3000' }, { working: 2 }),
tab(2, 'atlas', { active: true }),
tab(
3,
'studio',
{ color: '#34d399', url: 'https://studio.example.ts.net' },
{
needsYou: 1,
waiting: 1,
working: 3,
offline: true,
}
),
tab(4, 'build-01', { color: '#f472b6' }, { waiting: 1, working: 2, offline: true }),
tab(5, 'pi-lab', { color: BAD_COLOR }, { offline: true }),
tab(6, HOSTILE, { color: '#64748b' }, { working: 1, offline: true }),
tab(7, 'New server tab', { kind: 'connect', url: null }),
tab(8, 'loading.lan', { kind: 'loading' }),
];
async function stripWalk(browser: Browser) {
const o = await open(browser, 'tabs.html', { width: 1280, height: 38 });
const { page, take, native } = o;
const sel = (id: number, inner = '') => `.tab[data-id="${id}"]${inner ? ' ' + inner : ''}`;
const box = async (s: string) => (await page.locator(s).boundingBox())!;
// 1. Before the first state: only the two buttons.
check('posts ready on load', same(await take(), [{ cmd: 'ready' }]));
check(
'before a state: no tabs, both buttons shown',
(await page.locator('[role=tab]').count()) === 0 &&
(await page.isVisible('#overview')) &&
(await page.isVisible('#new'))
);
check('the strip is 38px tall', (await box('#strip')).height === 38, await box('#strip'));
check(
'room for the traffic lights',
(await page.evaluate(() => getComputedStyle(document.getElementById('strip')!).paddingLeft)) === '78px'
);
// 2. A state.
await native({ type: 'state', tabs: STRIP_TABS, overviewActive: false, fullscreen: false });
check('one tab per entry', (await page.locator('[role=tab]').count()) === 8);
check('a tablist owns them', (await page.locator('[role=tablist] [role=tab]').count()) === 8);
const selected = await page.$$eval('[role=tab]', (els) => els.map((e) => e.getAttribute('aria-selected')));
check(
'only the active tab is aria-selected',
same(selected, ['false', 'true', 'false', 'false', 'false', 'false', 'false', 'false']),
selected
);
check('the active tab is marked', (await page.locator('.tab.active').getAttribute('data-id')) === '2');
const active = await page.$eval(sel(2), (e) => {
const cs = getComputedStyle(e);
return { bg: cs.backgroundColor, shadow: cs.boxShadow, color: cs.color };
});
check(
'the active tab joins the page and carries its colour stripe',
active.bg === 'rgb(11, 12, 15)' &&
active.shadow.includes('rgb(34, 211, 238)') &&
active.color === 'rgb(232, 234, 237)',
active
);
check(
'an inactive tab is transparent',
(await page.$eval(sel(1), (e) => getComputedStyle(e).backgroundColor)) === 'rgba(0, 0, 0, 0)'
);
// Badge precedence.
const badge = (id: number) =>
page.$eval(sel(id, '.badge'), (e) => ({
cls: e.className,
text: e.textContent,
shown: getComputedStyle(e).display,
}));
const b3 = await badge(3);
check('needs you beats waiting, working and offline', b3.cls === 'badge needs' && b3.text === '1', b3);
check(
'the needs-you pill is red',
(await page.$eval(sel(3, '.badge'), (e) => getComputedStyle(e).backgroundColor)) === 'rgb(248, 113, 113)'
);
check('waiting beats working and offline', (await badge(4)).cls === 'badge waiting', await badge(4));
check('working beats offline', (await badge(6)).cls === 'badge working', await badge(6));
check('offline alone: the dashed circle', (await badge(5)).cls === 'badge offline', await badge(5));
check('nothing going on: no badge', (await badge(2)).shown === 'none', await badge(2));
check(
'an offline tab has its name dimmed, a needs-you one does not',
(await page.$eval(sel(5, '.name'), (e) => getComputedStyle(e).color)) === 'rgb(107, 112, 121)' &&
(await page.$eval(sel(3, '.name'), (e) => getComputedStyle(e).color)) !== 'rgb(107, 112, 121)'
);
check(
'a working ring turns',
(await page.$eval(sel(1, '.badge'), (e) => getComputedStyle(e).animationName)) === 'spin'
);
// Icons.
const icons = await page.$$eval('.tab .ico', (els) =>
els.map((e) => (e.querySelector('.spin') ? 'spin' : (e.querySelector('svg')?.childElementCount ?? 0)))
);
check(
'laptop for this Mac, rack for a server, + for new, spinner while loading',
same(icons, [2, 3, 3, 3, 3, 3, 1, 'spin']),
icons
);
check(
'the + of a new tab is blue',
(await page.$eval(sel(7, '.ico'), (e) => getComputedStyle(e).color)) === 'rgb(96, 165, 250)'
);
// Untrusted text and colours.
check('a hostile name is text', (await page.textContent(sel(6, '.name'))) === HOSTILE);
check('no element came out of it', (await page.locator('img').count()) === 0);
check(
'a bad colour falls back',
(await page.$eval(sel(5, '.ico'), (e) => getComputedStyle(e).color)) === FALLBACK_RGB &&
!((await page.getAttribute(sel(5), 'style')) || '').includes('url'),
await page.getAttribute(sel(5), 'style')
);
// Labels and the tooltip.
check(
'aria-label carries the status',
(await page.getAttribute(sel(3, '[role=tab]'), 'aria-label'))?.startsWith('studio, 1 needs you')
);
const title3 = await page.getAttribute(sel(3, '[role=tab]'), 'title');
check(
'the tooltip: name and shortcut, URL, one line per status',
title3 === 'studio ⌘3\nhttps://studio.example.ts.net\n1 needs you\n1 waiting\n3 working\nNot answering',
title3
);
check(
'the loading tab says it is connecting',
(await page.getAttribute(sel(8, '[role=tab]'), 'aria-label')) === 'loading.lan, Connecting'
);
check(
'icon buttons are named',
(await page.getAttribute('#overview', 'aria-label')) === 'All servers' &&
(await page.getAttribute('#new', 'aria-label')) === 'New server tab' &&
(await page.getAttribute(sel(2, '.close'), 'aria-label')) === 'Close tab'
);
check(
'nothing in the strip takes the keyboard focus',
await page.$$eval('button', (els) => els.every((e) => e.getAttribute('tabindex') === '-1'))
);
// 3. Clicks.
await take();
await page.click(sel(1));
check('a click selects', same(await take(), [{ cmd: 'select', id: 1 }]));
check(
'the strip does not take the focus on a click',
await page.evaluate(() => document.activeElement === document.body)
);
check('the close button shows on the active tab', await page.isVisible(sel(2, '.close')));
check('and not on an inactive one', !(await page.isVisible(sel(4, '.close'))));
await page.hover(sel(4));
check('hovering shows it', await page.isVisible(sel(4, '.close')));
await page.click(sel(4, '.close'));
check('the close button closes, and only that', same(await take(), [{ cmd: 'close', id: 4 }]));
await page.click(sel(3), { button: 'middle' });
check('a middle click closes', same(await take(), [{ cmd: 'close', id: 3 }]));
await page.click(sel(5), { button: 'right' });
check('a right click asks for the menu', same(await take(), [{ cmd: 'menu', id: 5 }]));
// WebKit's own menu never shows on the strip: every contextmenu is cancelled, and only a
// tab asks for one. Seen from window, after the page's own listener on document.
await page.evaluate(() => {
(window as any).__menus = [];
window.addEventListener('contextmenu', (e) => (window as any).__menus.push(e.defaultPrevented));
});
await page.click('#new', { button: 'right' });
await page.click('#overview', { button: 'right' });
await page.mouse.click(30, 19, { button: 'right' });
await page.click(sel(2, '.close'), { button: 'right' });
check(
'a right click on a button or empty strip asks for nothing; on a close button, the tab menu',
same(await take(), [{ cmd: 'menu', id: 2 }])
);
check(
'and none of them shows the WebKit menu',
same(await page.evaluate(() => (window as any).__menus), [true, true, true, true]),
await page.evaluate(() => (window as any).__menus)
);
await page.click('#new');
check('+ opens a new tab', same(await take(), [{ cmd: 'new' }]));
await page.click('#overview');
check('the grid button asks for the overview', same(await take(), [{ cmd: 'overview' }]));
// 4. Empty strip: window drag and zoom.
const fill = await box('#fill');
check('there is empty strip to drag by', fill.width >= 48, fill);
const fx = fill.x + fill.width / 2;
await page.mouse.click(fx, 19);
check('a press on empty strip drags the window', same(await take(), [{ cmd: 'drag' }]));
await page.mouse.click(30, 19);
check('so does a press under the traffic lights', same(await take(), [{ cmd: 'drag' }]));
await page.waitForTimeout(600);
await page.mouse.dblclick(fx, 19);
check(
'a double click zooms on its second press (one drag, for the first)',
same(await take(), [{ cmd: 'drag' }, { cmd: 'zoom' }])
);
const t1 = await box(sel(1));
await page.mouse.move(t1.x + t1.width / 2, 22);
await page.mouse.down();
await page.mouse.up();
check('a press on a tab is not a window drag', same(await take(), [{ cmd: 'select', id: 1 }]));
// 5. Overview on, fullscreen.
await native({ type: 'state', tabs: STRIP_TABS, overviewActive: true, fullscreen: true });
check(
'the grid button is lit while the overview shows',
(await page.$eval('#overview', (e) => getComputedStyle(e).backgroundColor)) === 'rgb(37, 99, 235)' &&
(await page.getAttribute('#overview', 'aria-pressed')) === 'true'
);
check(
'fullscreen has no traffic lights to make room for',
(await page.evaluate(() => getComputedStyle(document.getElementById('strip')!).paddingLeft)) === '10px'
);
// 6. Rename.
await native({ type: 'state', tabs: STRIP_TABS, overviewActive: false, fullscreen: false });
await take();
await page.dblclick(sel(2));
const input = sel(2, 'input.rename');
check(
'a double click on a tab starts a rename',
(await page.isVisible(input)) &&
(await page.inputValue(input)) === 'atlas' &&
(await page.evaluate(() => document.activeElement?.className)) === 'rename'
);
await page.keyboard.type(' prod box ');
await page.keyboard.press('Enter');
check(
'Enter commits it, trimmed (the clicks of the double click selected)',
same(await take(), [
{ cmd: 'select', id: 2 },
{ cmd: 'select', id: 2 },
{ cmd: 'editing' },
{ cmd: 'rename', id: 2, name: 'prod box' },
])
);
check(
'and shows it at once',
!(await page.isVisible(input)) && (await page.textContent(sel(2, '.name'))) === 'prod box'
);
await native({ type: 'rename', id: 1 });
check('the native menu starts a rename too', (await page.inputValue(sel(1, 'input.rename'))) === 'This Mac');
await page.keyboard.type('zzz');
await page.keyboard.press('Escape');
const cancelled = await take();
check(
'Escape cancels, and still says the rename is over (with the old name)',
same(cancelled, [{ cmd: 'editing' }, { cmd: 'rename', id: 1, name: 'This Mac' }]) &&
(await page.locator('input.rename').count()) === 0 &&
(await page.textContent(sel(1, '.name'))) === 'This Mac',
cancelled
);
await native({ type: 'rename', id: 1 });
await page.keyboard.press('Enter');
check(
'an unchanged name posts the old name',
same(await take(), [{ cmd: 'editing' }, { cmd: 'rename', id: 1, name: 'This Mac' }])
);
await native({ type: 'rename', id: 1 });
await page.keyboard.press('Backspace');
await page.keyboard.press('Enter');
check(
'an empty name asks for the default',
same(await take(), [{ cmd: 'editing' }, { cmd: 'rename', id: 1, name: '' }])
);
await native({ type: 'rename', id: 3 });
check('a rename asks the native side for the keyboard', same(await take(), [{ cmd: 'editing' }]));
await page.keyboard.type('x'.repeat(50));
check('at most 40 characters', (await page.inputValue(sel(3, 'input.rename'))).length === 40);
await page.click(sel(3, 'input.rename'), { button: 'right' });
check(
'a right click in the rename field shows no menu at all and keeps the rename going',
(await page.evaluate(() => (window as any).__menus.at(-1))) === true &&
(await page.locator(sel(3, 'input.rename')).count()) === 1 &&
(await take()).length === 0
);
// A state arriving mid-rename (statuses change all the time) keeps the field and its text.
const moved = [STRIP_TABS[2], ...STRIP_TABS.filter((t) => t.id !== 3)];
await native({ type: 'state', tabs: moved, overviewActive: false, fullscreen: false });
check(
'a state mid-rename keeps the field, its text and the focus',
(await page.inputValue(sel(3, 'input.rename'))) === 'x'.repeat(40) &&
(await page.evaluate(() => document.activeElement?.className)) === 'rename' &&
(await page.$eval('#tabs', (e) => e.firstElementChild?.getAttribute('data-id'))) === '3'
);
await page.mouse.click(fx, 19);
const committed = await take();
check(
'a click elsewhere commits it',
same(committed, [{ cmd: 'rename', id: 3, name: 'x'.repeat(40) }, { cmd: 'drag' }]),
committed
);
// 7. Drag to reorder.
const four = [tab(11, 'one', { active: true }), tab(12, 'two'), tab(13, 'three'), tab(14, 'four')];
await native({ type: 'state', tabs: four, overviewActive: false, fullscreen: false });
await take();
const widths = await page.$$eval('.tab', (els) => els.map((e) => e.getBoundingClientRect().width));
check(
'a few tabs are 200px wide',
widths.every((w) => w === 200),
widths
);
const centre = async (id: number) => {
const b = await box(sel(id));
return b.x + b.width / 2;
};
await page.mouse.move(await centre(11), 22);
await page.mouse.down();
await page.mouse.move((await centre(11)) + 2, 22);
await page.mouse.up();
check('a press that moves under 4px is still a click', same(await take(), [{ cmd: 'select', id: 11 }]));
const target = (await centre(13)) + 10;
await page.mouse.move(await centre(11), 22);
await page.mouse.down();
await page.mouse.move(target, 22, { steps: 12 });
const shifted = await page.$eval(sel(12), (e) => (e as HTMLElement).style.transform);
check('the tabs passed over slide aside', shifted === 'translateX(-202px)', shifted);
await page.mouse.up();
const order = () => page.$$eval('.tab', (els) => els.map((e) => Number(e.getAttribute('data-id'))));
check('a drag posts the new place, and no select', same(await take(), [{ cmd: 'move', id: 11, to: 2 }]));
check('and shows it at once', same(await order(), [12, 13, 11, 14]), await order());
check(
'nothing stays shifted',
await page.$$eval('.tab', (els) => els.every((e) => !(e as HTMLElement).style.transform))
);
// A state that arrives during a drag waits for the drop.
await page.mouse.move(await centre(14), 22);
await page.mouse.down();
await page.mouse.move((await centre(12)) - 20, 22, { steps: 12 });
const renamed = [four[1], four[2], four[0], four[3]].map((t) => (t.id === 12 ? { ...t, name: 'twelve' } : t));
await native({ type: 'state', tabs: renamed, overviewActive: false, fullscreen: false });
check('mid-drag, the row holds still', (await page.textContent(sel(12, '.name'))) === 'two');
await page.mouse.up();
check('dropped at the front', same(await take(), [{ cmd: 'move', id: 14, to: 0 }]));
check(
'then the waiting state shows, in the new order',
same(await order(), [14, 12, 13, 11]) && (await page.textContent(sel(12, '.name'))) === 'twelve',
await order()
);
// 8. Many tabs and long names.
const many = Array.from({ length: 30 }, (_, i) => tab(100 + i, 'server-' + i, { active: i === 0 }));
many[0].name = 'a very long server name that cannot possibly fit in a tab';
await native({ type: 'state', tabs: many, overviewActive: false, fullscreen: false });
const geo = await page.evaluate(() => {
const tabs = Array.from(document.querySelectorAll('.tab')).map((e) => e.getBoundingClientRect());
const plus = document.getElementById('new')!.getBoundingClientRect();
const name = document.querySelector('.tab .name') as HTMLElement;
return {
minWidth: Math.min(...tabs.map((r) => r.width)),
tops: new Set(tabs.map((r) => r.top)).size,
plusRight: plus.right,
plusLeft: plus.left,
pageWidth: document.documentElement.scrollWidth,
ellipsis: name.scrollWidth > name.clientWidth && getComputedStyle(name).textOverflow === 'ellipsis',
fill: document.getElementById('fill')!.getBoundingClientRect().width,
};
});
check(
'thirty tabs: 72px each, one row, + still on screen, the page never scrolls',
geo.minWidth === 72 && geo.tops === 1 && geo.plusRight <= 1280 && geo.plusLeft > 0 && geo.pageWidth <= 1280,
geo
);
check('a long name ends in an ellipsis', geo.ellipsis, geo);
check('and some strip stays empty to drag the window by', geo.fill >= 48, geo);
await native({
type: 'state',
tabs: [tab(1, 'busy', { active: true }, { needsYou: 250 })],
overviewActive: false,
fullscreen: false,
});
check('a big count is capped', (await page.textContent(sel(1, '.badge'))) === '99+');
check('no page errors', o.errors.length === 0, o.errors);
check('no CSP violations', o.cspViolations.length === 0, o.cspViolations);
check('no dialogs', o.dialogs.length === 0, o.dialogs);
await o.close();
}
// ---------------------------------------------------------------------------------------------
// The overview
function server(tabId: number, name: string, extra: Record<string, unknown> = {}) {
return {
tab: tabId,
name,
color: '#22d3ee',
url: `http://${name.replace(/\W/g, '')}.lan:3000`,
local: false,
key: tabId,
version: '1.51.0',
kind: 'server',
offline: false,
refused: false,
sessions: [] as unknown[],
counts: { needsYou: 0, waiting: 0, working: 0, sessions: 0 },
...extra,
};
}
const sess = (id: string, name: string, state: string, text: string) => ({ id, name, state, text });
const SERVERS = [
server(3, 'studio', {
color: '#34d399',
url: 'https://studio.example.ts.net',
sessions: [
sess('s-billing', 'billing', 'needs', 'Allow Bash(npm run migrate)?'),
sess('s-docs', HOSTILE, 'needs', HOSTILE),
],
counts: { needsYou: 2, waiting: 0, working: 0, sessions: 2 },
}),
server(2, 'atlas', {
url: 'http://192.168.1.40:3000',
sessions: [
sess('s-api', 'api-gateway', 'waiting', 'finished 3 min ago'),
sess('s-shop', 'webshop', 'working', 'Refactoring… 1m 12s'),
sess('s-ingest', 'ingest-pipeline', 'working', 'Running tests… 20s'),
sess('s-a', 'landing', 'idle', 'idle'),
sess('s-b', 'extra', 'idle', 'idle'),
],
counts: { needsYou: 0, waiting: 1, working: 2, sessions: 7 },
}),
server(1, 'This Mac', {
color: BAD_COLOR,
local: true,
url: 'http://127.0.0.1:3000',
sessions: [sess('s-sb', 'sandbox-3f9a', 'working', 'Writing tests… 4m 40s')],
counts: { needsYou: 0, waiting: 0, working: 1, sessions: 1 },
}),
server(5, 'pi-lab', { offline: true, counts: { needsYou: 4, waiting: 0, working: 0, sessions: 3 } }),
server(6, 'old-nas', { refused: true, version: null }),
server(7, 'New server tab', { kind: 'connect', url: null, version: null }),
server(8, 'build-01', { kind: 'loading', version: null, key: null }),
];
async function overviewWalk(browser: Browser) {
const o = await open(browser, 'overview.html', { width: 1280, height: 800 });
const { page, take, native } = o;
const card = (n: number) => `#grid > .card:nth-child(${n})`;
check('posts ready on load', same(await take(), [{ cmd: 'ready' }]));
check(
'before a state: just the Add card, nothing needs you',
(await page.locator('#grid > *').count()) === 1 &&
(await page.isVisible('#grid > button.add')) &&
(await page.textContent('#summary')) === 'Nothing needs you'
);
await native({ type: 'state', servers: SERVERS });
const names = await page.$$eval('#grid > .card .name', (els) => els.map((e) => e.textContent));
check(
'one card per server, in the order given, then Add',
same(names, ['studio', 'atlas', 'This Mac', 'pi-lab', 'old-nas', 'New server tab', 'build-01']) &&
(await page.$eval('#grid', (g) => g.lastElementChild!.classList.contains('add'))),
names
);
check(
'the summary counts what is up (an offline server counts as offline only)',
(await page.textContent('#summary')) === '2 need you · 1 waiting · 3 working · 1 offline',
await page.textContent('#summary')
);
check(
'need you and waiting are coloured',
(await page.$eval('#summary .needs', (e) => getComputedStyle(e).color)) === 'rgb(252, 165, 165)' &&
(await page.$eval('#summary .waiting', (e) => getComputedStyle(e).color)) === 'rgb(252, 211, 77)'
);
// A card that needs you.
const studio = card(1);
check(
'needs you: red border, Answer in red',
(await page.$eval(studio, (e) => getComputedStyle(e).borderTopColor)) === 'rgba(248, 113, 113, 0.45)' &&
(await page.textContent(studio + ' .action')) === 'Answer' &&
(await page.$eval(studio + ' .action', (e) => getComputedStyle(e).backgroundColor)) === 'rgb(239, 68, 68)'
);
check(
'header: name, URL, shortcut',
(await page.textContent(studio + ' .url')) === 'https://studio.example.ts.net' &&
(await page.textContent(studio + ' .key')) === '⌘3'
);
check(
'its colour is the stripe',
(await page.$eval(studio, (e) => getComputedStyle(e).boxShadow)).includes('rgb(52, 211, 153)')
);
check('footer: sessions and version', (await page.textContent(studio + ' .meta')) === '2 sessions · 1.51.0');
check(
'hostile session text stays text',
(await page
.locator(studio + ' .row .sname')
.nth(1)
.textContent()) === HOSTILE &&
(await page
.locator(studio + ' .row .stext')
.nth(1)
.textContent()) === HOSTILE &&
(await page.locator('img').count()) === 0
);
check(
'the needs mark is a red !',
(await page
.locator(studio + ' .row .mark')
.first()
.textContent()) === '!' &&
(await page
.locator(studio + ' .row .mark')
.first()
.evaluate((e) => getComputedStyle(e).backgroundColor)) === 'rgb(248, 113, 113)'
);
await page.click(studio + ' .action');
check(
'Answer goes to the first session that needs you',
same(await take(), [{ cmd: 'openSession', tab: 3, session: 's-billing' }])
);
// A busy card with more sessions than fit.
const atlas = card(2);
check('at most four rows', (await page.locator(atlas + ' .row').count()) === 4);
check('the rest as +N more', (await page.textContent(atlas + ' .more')) === '+3 more');
check(
'rows are buttons, in the order given',
same(await page.$$eval(atlas + ' .row', (els) => els.map((e) => e.tagName + ':' + e.className)), [
'BUTTON:row waiting',
'BUTTON:row working',
'BUTTON:row working',
'BUTTON:row idle',
])
);
check('Open when nothing needs you', (await page.textContent(atlas + ' .action')) === 'Open');
check('no red border', (await page.$eval(atlas, (e) => getComputedStyle(e).borderTopColor)) === 'rgb(35, 37, 43)');
await page.click(atlas + ' .action');
await page.click(atlas + ' .head');
await page
.locator(atlas + ' .row')
.nth(1)
.click();
check(
'Open, the header and a row post what they should',
same(await take(), [
{ cmd: 'open', tab: 2 },
{ cmd: 'open', tab: 2 },
{ cmd: 'openSession', tab: 2, session: 's-shop' },
])
);
// A bad colour.
const mac = card(3);
check(
'a bad colour falls back',
(await page.$eval(mac, (e) => getComputedStyle(e).boxShadow)).includes(FALLBACK_RGB) &&
!((await page.getAttribute(mac, 'style')) || '').includes('url'),
await page.getAttribute(mac, 'style')
);
check('one session, singular', (await page.textContent(mac + ' .meta')) === '1 session · 1.51.0');
// Offline, refused, new, loading.
const pi = card(4);
check(
'offline: dashed, says so, offers Retry',
(await page.$eval(pi, (e) => getComputedStyle(e).borderTopStyle)) === 'dashed' &&
(await page.textContent(pi + ' .note')) === 'Not answering, the app keeps trying' &&
(await page.textContent(pi + ' .action')) === 'Retry' &&
(await page.locator(pi + ' .row').count()) === 0
);
await page.click(pi + ' .action');
check('Retry retries', same(await take(), [{ cmd: 'retry', tab: 5 }]));
const nas = card(5);
check(
'refused: says so, offers Open',
(await page.textContent(nas + ' .note')) === 'The login was refused' &&
(await page.textContent(nas + ' .action')) === 'Open'
);
await page.click(nas + ' .action');
check('which opens the tab', same(await take(), [{ cmd: 'open', tab: 6 }]));
check(
'a new tab: a small card with Open',
(await page.textContent(card(6) + ' .name')) === 'New server tab' &&
(await page.textContent(card(6) + ' .action')) === 'Open' &&
(await page.locator(card(6) + ' .url').count()) === 0
);
check(
'loading: Connecting with a spinner',
(await page.textContent(card(7) + ' .note')) === 'Connecting…' &&
(await page.locator(card(7) + ' .spin').count()) === 1 &&
(await page.$eval(card(7) + ' .spin', (e) => getComputedStyle(e).animationName)) === 'spin'
);
await page.click('#grid > .add');
check('Add asks for a new tab', same(await take(), [{ cmd: 'new' }]));
// Keyboard: real buttons, a visible ring, and the focus survives a state.
await page.focus(atlas + ' .head');
await page.keyboard.press('Tab');
const ring = await page.evaluate(() => {
const a = document.activeElement as HTMLElement;
const cs = getComputedStyle(a);
return { cls: a.className, outline: cs.outlineStyle + ' ' + cs.outlineWidth + ' ' + cs.outlineColor };
});
check(
'Tab reaches the first row, with a blue ring',
ring.cls === 'row waiting' && ring.outline === 'solid 2px rgb(59, 130, 246)',
ring
);
await page.keyboard.press('Enter');
check('Enter on a row opens that session', same(await take(), [{ cmd: 'openSession', tab: 2, session: 's-api' }]));
const changed = SERVERS.map((s) =>
s.tab === 2
? { ...s, sessions: [sess('s-api', 'api-gateway', 'waiting', 'finished 4 min ago'), ...s.sessions.slice(1)] }
: s
);
await native({ type: 'state', servers: changed });
check(
'a new state keeps the focus on the same row',
(await page.evaluate(() => (document.activeElement as HTMLElement).dataset.focus)) === 'row:2:s-api' &&
(await page.textContent(atlas + ' .row .stext')) === 'finished 4 min ago'
);
// Back to nothing.
await native({ type: 'state', servers: [] });
check(
'no servers: just the Add card',
(await page.locator('#grid > *').count()) === 1 && (await page.textContent('#summary')) === 'Nothing needs you'
);
const tooNarrow = await page.evaluate(() => document.documentElement.scrollWidth > window.innerWidth);
check('no sideways scroll', !tooNarrow);
check('no page errors', o.errors.length === 0, o.errors);
check('no CSP violations', o.cspViolations.length === 0, o.cspViolations);
check('no dialogs', o.dialogs.length === 0, o.dialogs);
await o.close();
}
// ---------------------------------------------------------------------------------------------
// Both: reduced motion, the globals, the text of the files
async function bothPages(browser: Browser) {
for (const [file, text] of Object.entries(PAGES)) {
check(`${file}: no em dash`, !text.includes(String.fromCharCode(0x2014)));
check(`${file}: no innerHTML`, !/innerHTML|insertAdjacentHTML|outerHTML/.test(text));
}
const strip = await open(browser, 'tabs.html', { width: 900, height: 38 }, 'reduce');
await strip.native({
type: 'state',
tabs: [tab(1, 'busy', { active: true }, { working: 1 }), tab(2, 'starting', { kind: 'loading' })],
overviewActive: false,
fullscreen: false,
});
check(
'reduced motion: the strip does not spin',
(await strip.page.$eval('.badge.working', (e) => getComputedStyle(e).animationName)) === 'none' &&
(await strip.page.$eval('.spin', (e) => getComputedStyle(e).animationName)) === 'none'
);
const desc = await strip.page.evaluate(() => {
const d = Object.getOwnPropertyDescriptor(window, '__codemanTabs')!;
const before = window.__codemanTabs;
try {
(window as any).__codemanTabs = null;
} catch {
/* strict code would throw; the page's own is the point */
}
return { writable: d.writable, configurable: d.configurable, kept: window.__codemanTabs === before };
});
check('the strip global cannot be replaced', !desc.writable && !desc.configurable && desc.kept, desc);
await strip.native('{"type":"state","tabs":[{"id":9,"name":"from a string"}]}');
check('a message as a JSON string works too', (await strip.page.textContent('.tab .name')) === 'from a string');
await strip.native({ type: 'state', tabs: 'nonsense' });
await strip.native(null);
check(
'junk empties the strip without an error',
(await strip.page.locator('.tab').count()) === 0 && strip.errors.length === 0,
strip.errors
);
await strip.close();
const ov = await open(browser, 'overview.html', { width: 1280, height: 800 }, 'reduce');
await ov.native({ type: 'state', servers: SERVERS });
check(
'reduced motion: the overview does not spin',
(await ov.page.$eval('.row.working .mark', (e) => getComputedStyle(e, '::before').animationName)) === 'none' &&
(await ov.page.$eval('.spin', (e) => getComputedStyle(e).animationName)) === 'none'
);
const odesc = await ov.page.evaluate(() => {
const d = Object.getOwnPropertyDescriptor(window, '__codemanOverview')!;
return { writable: d.writable, configurable: d.configurable };
});
check('the overview global cannot be replaced', !odesc.writable && !odesc.configurable, odesc);
check('no page errors', ov.errors.length === 0, ov.errors);
await ov.close();
}
describe('Codeman Desktop server tab pages', () => {
let browser: Browser;
beforeAll(async () => {
browser = await chromium.launch({ headless: true });
});
afterAll(async () => {
await browser?.close();
});
const walk = (name: string, steps: (browser: Browser) => Promise<void>) =>
it(
name,
async () => {
failed.length = 0;
await steps(browser);
expect(failed).toEqual([]);
},
120_000
);
walk('the strip: tabs, badges, clicks, window drag, rename and reorder', stripWalk);
walk('the overview: cards, rows, buttons and the summary', overviewWalk);
walk('both: reduced motion, the globals, junk from the native side', bothPages);
});
+3 -69
View File
@@ -448,72 +448,6 @@ describe('DiscordBridge', () => {
return b;
}
it('deduplicates replayed real gateway IDs across restart while new replies still work', async () => {
const b = await ready();
const m = reply({ id: '555555555555555555' });
await b.onGatewayMessage(m);
b.stop();
t += 10_000;
const next = await ready();
await next.onGatewayMessage(m);
expect(sendInput).toHaveBeenCalledTimes(1);
await next.onGatewayMessage(reply({ id: '555555555555555556', content: 'continue' }));
expect(sendInput).toHaveBeenCalledTimes(2);
next.stop();
});
it('claims rate-limited snowflake replies so replays remain refused across restart', async () => {
const b = await ready();
await b.onGatewayMessage(reply({ id: '555555555555555555' }));
t += 200;
const refused = reply({ id: '555555555555555556', content: 'too soon' });
await b.onGatewayMessage(refused);
expect(sendInput).toHaveBeenCalledTimes(1);
expect(posts.some((p) => p.path.includes(encodeURIComponent('⏳')))).toBe(true);
t += 5_000;
const count = posts.length;
await b.onGatewayMessage(refused);
expect(sendInput).toHaveBeenCalledTimes(1);
expect(posts).toHaveLength(count);
b.stop();
const next = await ready();
await next.onGatewayMessage(refused);
expect(sendInput).toHaveBeenCalledTimes(1);
await next.onGatewayMessage(reply({ id: '555555555555555557', content: 'new attempt' }));
expect(sendInput).toHaveBeenCalledTimes(2);
next.stop();
});
it('ignores an immediate replay without adding an hourglass to a successful reply', async () => {
const b = await ready();
const m = reply({ id: '555555555555555555' });
await b.onGatewayMessage(m);
t += 200;
await b.onGatewayMessage(m);
expect(sendInput).toHaveBeenCalledTimes(1);
expect(posts.filter((p) => p.method === 'PUT')).toHaveLength(1);
expect(posts.some((p) => p.path.includes(encodeURIComponent('⏳')))).toBe(false);
b.stop();
});
it('delivers replies and alerts when metadata is corrupt and recovers without restarting', async () => {
const b = await ready();
writeFileSync(join(dir, 'discord-reply-dedupe.json'), '{');
const log = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
await b.onGatewayMessage(reply({ id: '555555555555555555' }));
expect(sendInput).toHaveBeenCalledTimes(1);
t += 10_000;
expect((await b.notify(MSG))?.ok).toBe(true);
rmSync(join(dir, 'discord-reply-dedupe.json'));
await b.onGatewayMessage(reply({ id: '555555555555555556' }));
expect(sendInput).toHaveBeenCalledTimes(2);
expect(log).toHaveBeenCalledTimes(1);
} finally {
log.mockRestore();
b.stop();
}
});
it('types an allowed reply into the mapped session and ticks it', async () => {
const b = await ready();
await b.onGatewayMessage(reply());
@@ -1209,7 +1143,7 @@ describe('DiscordBridge files and startup hint', () => {
it('types a reply that waits on a download before a later text reply', async () => {
const b = await make();
const slow = b.onGatewayMessage(reply({ content: 'first' }));
await vi.waitFor(() => expect(downloads).toHaveLength(1)); // wait for the claim and rate-limit gate
await new Promise((r) => setTimeout(r, 0)); // the first reply is under way (gate passed) before the clock moves
t += 5_000;
const fast = b.onGatewayMessage(reply({ id: '555555555555555556', content: 'second', attachments: [] }));
await Promise.all([slow, fast]);
@@ -1223,11 +1157,11 @@ describe('DiscordBridge files and startup hint', () => {
await b.onGatewayMessage(reply({ content: '2', attachments: [] }));
expect(sent.at(-1)?.[1]).toBe('2');
t += 5_000;
await b.onGatewayMessage(reply({ id: '555555555555555556', content: 'yes', attachments: [] }));
await b.onGatewayMessage(reply({ content: 'yes', attachments: [] }));
expect(sent.at(-1)?.[1]).toBe('yes\r');
t += 5_000;
waiting = false;
await b.onGatewayMessage(reply({ id: '555555555555555557', content: '2', attachments: [] }));
await b.onGatewayMessage(reply({ content: '2', attachments: [] }));
expect(sent.at(-1)?.[1]).toBe('2\r');
b.stop();
});
-151
View File
@@ -1,151 +0,0 @@
import { lstat, mkdir, mkdtemp, readFile, rm, symlink, writeFile, stat } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { DiscordReplyDedupe } from '../src/discord-reply-dedupe.js';
import fs from 'node:fs/promises';
let dir: string;
const guild = '111111111111111111',
channel = '222222222222222222',
message = '333333333333333333';
beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), 'discord-replies-'));
});
afterEach(async () => {
await rm(dir, { recursive: true, force: true });
});
it('claims once across concurrent events and restarts, without storing message content', async () => {
const store = new DiscordReplyDedupe(dir);
expect(await Promise.all([store.claim(guild, channel, message), store.claim(guild, channel, message)])).toEqual([
true,
false,
]);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
expect((await stat(join(dir, 'discord-reply-dedupe.json'))).mode & 0o777).toBe(0o600);
expect(JSON.parse(await readFile(join(dir, 'discord-reply-dedupe.json'), 'utf8'))).toEqual([
[`${guild}:${channel}:${message}`, expect.any(Number)],
]);
});
it('falls back on corrupt metadata, logs once, retries after recovery, and retains memory claims', async () => {
const path = join(dir, 'discord-reply-dedupe.json');
await writeFile(path, '{');
const warn = vi.fn(),
store = new DiscordReplyDedupe(dir, Date.now, warn);
expect(await store.claim(guild, channel, message)).toBe(true);
expect(await store.claim(guild, channel, message)).toBe(false);
expect(warn).toHaveBeenCalledTimes(1);
await rm(path);
expect(await store.claim(guild, channel, '444444444444444444')).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
});
it('does not poison metadata with incomplete restored configuration', async () => {
const store = new DiscordReplyDedupe(dir);
expect(await store.claim('', channel, message)).toBe(true);
expect(await store.claim(guild, channel, message)).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
});
it('keeps accepting new replies during ENOSPC and persists memory claims when writes recover', async () => {
const warn = vi.fn();
const store = new DiscordReplyDedupe(dir, Date.now, warn);
const rename = vi.spyOn(fs, 'rename').mockRejectedValueOnce(Object.assign(new Error('full'), { code: 'ENOSPC' }));
try {
expect(await store.claim(guild, channel, message)).toBe(true);
expect(await store.claim(guild, channel, message)).toBe(false);
expect(await store.claim(guild, channel, '444444444444444444')).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
expect(warn).toHaveBeenCalledTimes(1);
} finally {
rename.mockRestore();
}
});
it('evicts old records rather than refusing replies at capacity', async () => {
await writeFile(
join(dir, 'discord-reply-dedupe.json'),
JSON.stringify(
Array.from({ length: 2048 }, (_, i) => [
`${guild}:${channel}:${String(100000000000000000n + BigInt(i))}`,
Date.now(),
])
)
);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(true);
expect(JSON.parse(await readFile(join(dir, 'discord-reply-dedupe.json'), 'utf8'))).toHaveLength(2048);
});
it.each(['{', '{}', '[null]'])(
'heals readable invalid metadata %s and keeps the claim across restart',
async (invalid) => {
const path = join(dir, 'discord-reply-dedupe.json');
await writeFile(path, invalid);
const warn = vi.fn(),
store = new DiscordReplyDedupe(dir, Date.now, warn);
expect(await store.claim(guild, channel, message)).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
expect(warn).toHaveBeenCalledTimes(1);
}
);
it('retains newer outage claims when disk recovery reaches capacity, without overwriting an unread file', async () => {
const path = join(dir, 'discord-reply-dedupe.json');
const rows = Array.from({ length: 2048 }, (_, i) => [
`${guild}:${channel}:${100000000000000000n + BigInt(i)}`,
Date.now(),
]);
const original = JSON.stringify(rows);
await writeFile(path, original);
const warn = vi.fn(),
store = new DiscordReplyDedupe(dir, Date.now, warn);
const read = vi
.spyOn(fs, 'readFile')
.mockRejectedValueOnce(Object.assign(new Error('descriptor limit'), { code: 'EMFILE' }));
expect(await store.claim(guild, channel, message)).toBe(true);
read.mockRestore();
expect(await readFile(path, 'utf8')).toBe(original);
expect(await store.claim(guild, channel, '444444444444444444')).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
const saved = JSON.parse(await readFile(path, 'utf8'));
expect(saved).toHaveLength(2048);
expect(saved.some((row: [string, number]) => row[0] === rows[0][0])).toBe(false);
});
it('heals an over-cap readable store rather than remaining memory-only until manual deletion', async () => {
const path = join(dir, 'discord-reply-dedupe.json');
await writeFile(
path,
JSON.stringify(
Array.from({ length: 2049 }, (_, i) => [`${guild}:${channel}:${100000000000000000n + BigInt(i)}`, Date.now()])
)
);
const warn = vi.fn();
expect(await new DiscordReplyDedupe(dir, Date.now, warn).claim(guild, channel, message)).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
expect(warn).toHaveBeenCalledTimes(1);
});
it('heals oversized regular metadata and persists replay protection across restart', async () => {
const path = join(dir, 'discord-reply-dedupe.json');
await writeFile(path, ' '.repeat(512 * 1024 + 1));
const warn = vi.fn();
expect(await new DiscordReplyDedupe(dir, Date.now, warn).claim(guild, channel, message)).toBe(true);
expect(await new DiscordReplyDedupe(dir).claim(guild, channel, message)).toBe(false);
expect((await stat(path)).size).toBeLessThan(512 * 1024);
expect(warn).toHaveBeenCalledTimes(1);
});
it('never replaces a symlink or a folder at the metadata path, and still accepts replies', async () => {
const path = join(dir, 'discord-reply-dedupe.json');
const target = join(dir, 'target');
await writeFile(target, 'keep');
await symlink(target, path);
const warn = vi.fn(),
store = new DiscordReplyDedupe(dir, Date.now, warn);
expect(await store.claim(guild, channel, message)).toBe(true);
expect(await store.claim(guild, channel, message)).toBe(false);
expect(await store.claim(guild, channel, '444444444444444444')).toBe(true);
expect((await lstat(path)).isSymbolicLink()).toBe(true);
expect(await readFile(target, 'utf8')).toBe('keep');
expect(warn).toHaveBeenCalledTimes(1);
await rm(path);
await mkdir(path);
expect(await new DiscordReplyDedupe(dir, Date.now, warn).claim(guild, channel, message)).toBe(true);
expect((await lstat(path)).isDirectory()).toBe(true);
});
+1 -68
View File
@@ -38,7 +38,7 @@ import {
symlinkSync,
readdirSync,
} from 'node:fs';
import { spawn, execFileSync, spawnSync } from 'node:child_process';
import { execFileSync, spawnSync } from 'node:child_process';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { diffRequiredEnvKeys, parseEnvKeys } from '../src/web/self-update.js';
@@ -639,70 +639,3 @@ describe('version_older_than', () => {
expect(out).toBe(older ? 'yes' : 'no');
});
});
/**
* A listener whose accept queue is full, so the kernel drops further SYNs and a
* connect to it gets no answer, the same thing a WSL host does for a CLOSED
* 127.0.0.1 port. Held by a python3 child, since Node accepts every connection
* as it arrives and so can never leave its own queue full.
*/
const HAS_PYTHON = spawnSync('python3', ['-c', 'pass']).status === 0;
const SILENT_LISTENER = [
'import socket, sys, time',
's = socket.socket(); s.bind(("127.0.0.1", 0)); s.listen(0)',
'port = s.getsockname()[1]; held = []',
'for _ in range(3):',
' c = socket.socket(); c.setblocking(False)',
' try: c.connect(("127.0.0.1", port))',
' except BlockingIOError: pass',
' held.append(c)',
'time.sleep(0.3); print(port, flush=True); time.sleep(60)',
].join('\n');
describe.skipIf(process.platform !== 'linux' || !HAS_PYTHON)('port_answers', () => {
/** Runs the script's own port_answers on host/port, returning its status and how long it took. */
function probe(host: string, port: number): { status: number | null; ms: number } {
const script = [
'set -euo pipefail',
`eval "$(sed -n '/^port_answers() {/,/^}/p' "$1")"`,
'if port_answers "$2" "$3"; then exit 0; else exit 1; fi',
].join('\n');
const started = Date.now();
const res = spawnSync('bash', ['-c', script, '_', join(ROOT, 'docker/Start-Codeman.sh'), host, String(port)], {
encoding: 'utf-8',
timeout: 10_000,
});
return { status: res.status, ms: Date.now() - started };
}
it('gives up on a connect that gets no answer within about a second, and reads it as free', async () => {
const child = spawn('python3', ['-I', '-c', SILENT_LISTENER], { stdio: ['ignore', 'pipe', 'ignore'] });
try {
const port = await new Promise<number>((resolve, reject) => {
child.stdout!.once('data', (chunk: Buffer) => resolve(Number(String(chunk).trim())));
child.once('exit', () => reject(new Error('listener exited')));
});
const { status, ms } = probe('127.0.0.1', port);
expect(status).toBe(1);
expect(ms).toBeLessThan(3000);
} finally {
child.kill();
}
});
it('still answers at once for a listening port and a closed one', async () => {
const server = createServer();
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const port = (server.address() as { port: number }).port;
try {
const open = probe('127.0.0.1', port);
expect(open.status).toBe(0);
expect(open.ms).toBeLessThan(1000);
} finally {
await new Promise<void>((resolve) => server.close(() => resolve()));
}
const closed = probe('::1', port);
expect(closed.status).toBe(1);
expect(closed.ms).toBeLessThan(1000);
});
});
-617
View File
@@ -1,617 +0,0 @@
/**
* @fileoverview Send-on-Enter mode of the CJK input field (input-cjk.js,
* setting cjkInputHoldUntilEnter): typed text stays in the field until Enter,
* so a phone user can scroll the terminal and edit an answer before sending.
*
* Same vm-sandbox approach as input-cjk.test.ts, with a stub textarea that also
* carries the attributes and style the mode touches.
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const PHANTOM = '​';
function makeTextarea() {
const listeners = new Map<string, Array<(e?: unknown) => void>>();
const attrs: Record<string, string> = {};
return {
value: '',
placeholder: '',
style: { height: '' } as Record<string, string>,
scrollHeight: 34,
// border-box with a 1px border: offsetHeight - clientHeight is the borders.
offsetHeight: 36,
clientHeight: 34,
attrs,
blur: vi.fn(),
focus: vi.fn(),
getClientRects: (): unknown[] => [{}],
classList: { contains: (c: string) => c === 'cjk-input-visible' },
setSelectionRange: () => {},
setAttribute: vi.fn((k: string, v: string) => {
attrs[k] = v;
}),
addEventListener: (ev: string, fn: (e?: unknown) => void) => {
listeners.set(ev, [...(listeners.get(ev) ?? []), fn]);
},
removeEventListener: (ev: string, fn: (e?: unknown) => void) => {
listeners.set(
ev,
(listeners.get(ev) ?? []).filter((f) => f !== fn)
);
},
fire(ev: string, arg: Record<string, unknown> = {}) {
const base = { preventDefault: () => {}, stopPropagation: () => {}, ...arg };
for (const fn of listeners.get(ev) ?? []) fn(base);
},
};
}
function load({
hold = true,
promptResult = true,
touch = true,
translate,
}: { hold?: boolean; promptResult?: boolean; touch?: boolean; translate?: (s: string) => string } = {}) {
const textarea = makeTextarea();
const sent: string[] = [];
const prompts: string[] = [];
const layout = vi.fn();
// The shell bar's one-shot Ctrl, reduced to its armed flag.
const bar = {
armed: false,
isCtrlArmed() {
return this.armed;
},
clearCtrl() {
this.armed = false;
},
};
const context = vm.createContext({
window: translate ? { CodemanI18n: { t: translate } } : {},
document: {
getElementById: (id: string) => (id === 'cjkInput' ? textarea : null),
activeElement: null,
body: { classList: { contains: (c: string) => touch && c === 'touch-device' } },
},
navigator: { userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X)' },
KeyboardHandler: { updateLayoutForKeyboard: layout },
KeyboardAccessoryBar: bar,
setTimeout: (fn: () => void, ms?: number) => setTimeout(fn, ms),
clearTimeout: (t: ReturnType<typeof setTimeout>) => clearTimeout(t),
performance: { now: () => performance.now() },
console,
});
const src = readFileSync(resolve(import.meta.dirname, '../src/web/public/input-cjk.js'), 'utf8');
vm.runInContext(src, context, { filename: 'input-cjk.js' });
const CjkInput = vm.runInContext('CjkInput', context);
CjkInput.init({
send: (t: string) => sent.push(t),
sendPrompt: (t: string) => {
prompts.push(t);
return promptResult;
},
});
CjkInput.setHoldUntilEnter(hold);
textarea.fire('focus');
return { CjkInput, textarea, sent, prompts, layout, bar };
}
function type(textarea: ReturnType<typeof makeTextarea>, text: string) {
textarea.value = PHANTOM + text;
textarea.fire('input', { isComposing: false, inputType: 'insertText' });
}
function backspace(textarea: ReturnType<typeof makeTextarea>, valueAfter: string) {
textarea.value = valueAfter;
textarea.fire('input', { isComposing: false, inputType: 'deleteContentBackward' });
}
const enter = (textarea: ReturnType<typeof makeTextarea>) =>
textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false });
describe('CJK input: Send on Enter', () => {
beforeEach(() => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] });
});
afterEach(() => {
vi.useRealTimers();
});
it('keeps typed text in the field instead of streaming it', () => {
const { textarea, sent } = load();
type(textarea, 'use Postgres');
vi.advanceTimersByTime(5000);
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM + 'use Postgres');
});
it('keeps text after a physical keystroke (no zero-latency flush)', () => {
const { textarea, sent } = load();
textarea.fire('keydown', { key: 'a', keyCode: 65, ctrlKey: false, altKey: false, metaKey: false });
type(textarea, 'a');
vi.advanceTimersByTime(1000);
expect(sent).toEqual([]);
});
it('keeps text across a composition cycle and autocorrect rewrites', () => {
const { textarea, sent } = load();
textarea.fire('compositionstart');
textarea.value = PHANTOM + 'teh';
textarea.fire('input', { isComposing: true, inputType: 'insertCompositionText' });
textarea.fire('compositionend');
textarea.value = PHANTOM + 'the';
textarea.fire('input', { isComposing: false, inputType: 'insertReplacementText' });
vi.advanceTimersByTime(5000);
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM + 'the');
});
it('sends one line on Enter through the prompt path, then clears the field', () => {
const { textarea, sent, prompts } = load();
type(textarea, 'yes, use Postgres');
const preventDefault = vi.fn();
textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false, preventDefault });
expect(preventDefault).toHaveBeenCalled();
expect(prompts).toEqual(['yes, use Postgres']);
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM);
});
it('never writes text and Enter together, whatever the length', () => {
// Codex takes characters arriving in one burst as a paste and folds an Enter
// inside it into the paste, so even `1\r` in one write stays unsent; Claude
// Code does the same for a long burst. terminal-ui.js _sendCjkPrompt types a
// single character and pastes anything longer, Enter always on its own.
const { textarea, sent, prompts } = load();
for (const answer of ['2', 'yes', 'a'.repeat(64), 'b'.repeat(150)]) {
type(textarea, answer);
enter(textarea);
}
expect(sent).toEqual([]);
expect(prompts).toEqual(['2', 'yes', 'a'.repeat(64), 'b'.repeat(150)]);
expect(textarea.value).toBe(PHANTOM);
});
it('keeps a short answer in the field when it is refused (no session)', () => {
const { textarea, prompts } = load({ promptResult: false });
type(textarea, 'yes');
enter(textarea);
expect(prompts).toEqual(['yes']);
expect(textarea.value).toBe(PHANTOM + 'yes');
});
it('sends several lines as a prompt (bracketed paste + session-bound Enter)', () => {
const { textarea, sent, prompts } = load();
type(textarea, 'line one\nline two');
enter(textarea);
vi.advanceTimersByTime(500);
expect(prompts).toEqual(['line one\nline two']);
expect(sent).toEqual([]);
});
it('keeps the text in the field when the prompt is refused (too long, no session)', () => {
const { textarea, prompts } = load({ promptResult: false });
type(textarea, 'line one\nline two');
enter(textarea);
expect(prompts).toHaveLength(1);
expect(textarea.value).toBe(PHANTOM + 'line one\nline two');
});
it('treats Shift+Enter as a newline, never a send', () => {
const { textarea, sent } = load();
type(textarea, 'first');
const preventDefault = vi.fn();
textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: true, preventDefault });
vi.advanceTimersByTime(10);
expect(preventDefault).not.toHaveBeenCalled();
expect(sent).toEqual([]);
});
it('sends a bare Enter when the field is empty (accepting a default answer)', () => {
const { textarea, sent } = load();
textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false });
expect(sent).toEqual(['\r']);
});
it('still forwards Backspace on an empty field to the PTY', () => {
const { textarea, sent } = load();
textarea.fire('keydown', { key: 'Backspace', keyCode: 8 });
expect(sent).toEqual(['\x7f']);
});
it('does not send Backspace when deleting the last held character', () => {
// The CLI's own composer may hold text (Attach, image paste, Path, mic):
// a stray DEL would eat its last character.
const { textarea, sent } = load();
type(textarea, 'a');
type(textarea, 'ab');
backspace(textarea, PHANTOM + 'a');
backspace(textarea, PHANTOM);
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM);
});
it('sends Backspace once the field is empty and the phantom itself is deleted', () => {
const { textarea, sent } = load();
type(textarea, 'a');
backspace(textarea, PHANTOM);
backspace(textarea, '');
expect(sent).toEqual(['\x7f']);
expect(textarea.value).toBe(PHANTOM);
});
it('does not send Backspace for select-all + delete of held text', () => {
const { textarea, sent } = load();
type(textarea, 'abc');
backspace(textarea, '');
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM);
});
it('deletes held text right after typing it, before any debounce, without a DEL', () => {
const { textarea, sent } = load();
type(textarea, 'a');
backspace(textarea, PHANTOM);
vi.advanceTimersByTime(2000);
expect(sent).toEqual([]);
});
it('puts the phantom back when Backspace at the start of the text deleted it', () => {
const { textarea, sent } = load();
type(textarea, 'abc');
backspace(textarea, 'abc');
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM + 'abc');
});
it('one-shot Ctrl: the next typed character goes out instead of being held', () => {
// _handleCjkInput turns the single character into the control byte.
const { textarea, sent, bar } = load();
bar.armed = true;
type(textarea, 'c');
expect(sent).toEqual(['c']);
expect(textarea.value).toBe(PHANTOM);
});
it('one-shot Ctrl: held text stays and only the new character leaves the field', () => {
const { textarea, sent, bar } = load();
type(textarea, 'ab');
bar.armed = true;
type(textarea, 'abc');
expect(sent).toEqual(['c']);
expect(textarea.value).toBe(PHANTOM + 'ab');
});
it('one-shot Ctrl: a character committed by an IME composition also goes out', () => {
const { textarea, sent, bar } = load();
bar.armed = true;
textarea.fire('compositionstart');
textarea.value = PHANTOM + 'c';
textarea.fire('input', { isComposing: true, inputType: 'insertCompositionText' });
textarea.fire('compositionend');
vi.advanceTimersByTime(10);
expect(sent).toEqual(['c']);
expect(textarea.value).toBe(PHANTOM);
});
it('one-shot Ctrl: a multi-character commit stays held and spends the modifier', () => {
const { textarea, sent, bar } = load();
bar.armed = true;
type(textarea, 'hello');
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM + 'hello');
expect(bar.armed).toBe(false);
});
it('Escape clears the held text without sending', () => {
const { textarea, sent } = load();
type(textarea, 'never mind');
textarea.fire('keydown', { key: 'Escape', keyCode: 27 });
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM);
});
it('turning the mode off drops the held draft and the stashes, so live mode sends only new keys', () => {
const { CjkInput, textarea, sent } = load();
CjkInput.restoreDraft('session-a');
type(textarea, 'rm -rf build\nsecond line');
CjkInput.stashDraft('session-b');
CjkInput.setHoldUntilEnter(false);
expect(textarea.value).toBe(PHANTOM);
type(textarea, 'x');
vi.advanceTimersByTime(1000);
expect(sent).toEqual(['x']);
CjkInput.setHoldUntilEnter(true);
CjkInput.clear();
CjkInput.restoreDraft('session-b');
expect(textarea.value).toBe(PHANTOM);
});
it('stays one line on a desktop, where growing would resize the PTY', () => {
const { textarea, layout } = load({ touch: false });
layout.mockClear();
textarea.scrollHeight = 60;
type(textarea, 'a\nb\nc');
vi.advanceTimersByTime(1000);
expect(textarea.style.height).toBe('');
expect(layout).not.toHaveBeenCalled();
});
it('translates its placeholder itself, since i18n.js skips textareas', () => {
const { CjkInput, textarea } = load({ translate: (s) => `zh:${s}` });
expect(textarea.placeholder).toBe('zh:Type, Enter to send (Shift+Enter: new line, Esc: clear)');
CjkInput.setHoldUntilEnter(false);
expect(textarea.placeholder).toBe('zh:CJK input (Enter = send, Esc = clear)');
});
it('turns autocorrect on in the mode and back off without it', () => {
const { CjkInput, textarea } = load();
expect(textarea.attrs.autocorrect).toBe('on');
expect(textarea.attrs.spellcheck).toBe('true');
CjkInput.setHoldUntilEnter(false);
expect(textarea.attrs.autocorrect).toBe('off');
expect(textarea.attrs.spellcheck).toBe('false');
expect(CjkInput.holdUntilEnter).toBe(false);
});
it('grows the field with its text and re-runs the keyboard layout', () => {
const { textarea, layout } = load();
layout.mockClear();
textarea.scrollHeight = 60;
type(textarea, 'a\nb\nc');
vi.advanceTimersByTime(1000);
// scrollHeight + the 2px of border, so a two-line draft does not scroll inside.
expect(textarea.style.height).toBe('62px');
expect(layout).toHaveBeenCalled();
});
it('leaves the field alone when the mode is set again unchanged', () => {
// Runs on every session select and SSE reconnect, possibly mid-composition.
const { CjkInput, textarea } = load();
textarea.setAttribute.mockClear();
const placeholder = textarea.placeholder;
let writes = 0;
Object.defineProperty(textarea, 'placeholder', {
get: () => placeholder,
set: () => {
writes++;
},
});
CjkInput.setHoldUntilEnter(true);
expect(textarea.setAttribute).not.toHaveBeenCalled();
expect(writes).toBe(0);
CjkInput.setHoldUntilEnter(false);
expect(textarea.setAttribute).toHaveBeenCalled();
});
it('follows a live language switch with the mode unchanged', () => {
// App Settings runs applyLocalization(), then _updateCjkInputState(), which
// calls setHoldUntilEnter() with the same mode.
let lang = 'en';
const { CjkInput, textarea } = load({ translate: (s) => (lang === 'zh' ? `zh:${s}` : s) });
expect(textarea.placeholder).toBe('Type, Enter to send (Shift+Enter: new line, Esc: clear)');
textarea.setAttribute.mockClear();
lang = 'zh';
CjkInput.setHoldUntilEnter(true);
expect(textarea.placeholder).toBe('zh:Type, Enter to send (Shift+Enter: new line, Esc: clear)');
expect(textarea.setAttribute).not.toHaveBeenCalled();
});
it('submit() from outside the field (toolbar Enter) sends like Enter', () => {
const { CjkInput, textarea, prompts, sent } = load();
type(textarea, 'go ahead');
expect(CjkInput.submit()).toBe(true);
expect(prompts).toEqual(['go ahead']);
expect(textarea.value).toBe(PHANTOM);
expect(CjkInput.submit()).toBe(true);
expect(sent).toEqual(['\r']);
});
it('submit() keeps a refused answer and reports it', () => {
const { CjkInput, textarea } = load({ promptResult: false });
type(textarea, 'go ahead');
expect(CjkInput.submit()).toBe(false);
expect(textarea.value).toBe(PHANTOM + 'go ahead');
});
it('a draft stashed on a switch comes back for its own session only', () => {
const { CjkInput, textarea, sent, prompts } = load();
type(textarea, 'half an answer');
CjkInput.stashDraft('session-a');
CjkInput.clear();
expect(textarea.value).toBe(PHANTOM);
CjkInput.restoreDraft('session-b');
expect(textarea.value).toBe(PHANTOM);
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM + 'half an answer');
// Restored once: the stash is consumed, so once the user empties the
// field (Esc here) a second visit does not bring it back. A draft still in
// the field when the session is left is stashed again by clear().
textarea.fire('keydown', { key: 'Escape', keyCode: 27 });
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
expect(sent).toEqual([]);
expect(prompts).toEqual([]);
});
it('a restored draft is held text: Backspace edits it without a DEL', () => {
const { CjkInput, textarea, sent } = load();
type(textarea, 'ok');
CjkInput.stashDraft('session-a');
CjkInput.clear();
CjkInput.restoreDraft('session-a');
backspace(textarea, PHANTOM + 'o');
backspace(textarea, PHANTOM);
expect(sent).toEqual([]);
});
it('an empty field stashes nothing, and a discarded draft is gone', () => {
const { CjkInput, textarea } = load();
type(textarea, 'draft');
CjkInput.stashDraft('session-a');
CjkInput.discardDraft('session-a');
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
CjkInput.stashDraft('session-b');
CjkInput.restoreDraft('session-b');
expect(textarea.value).toBe(PHANTOM);
});
it('a switch with an empty field keeps the draft already stashed for that session', () => {
// The tile grid stashes the session it parks, then may stash it again from
// tile focus with the field already cleared.
const { CjkInput, textarea } = load();
type(textarea, 'keep me');
CjkInput.stashDraft('session-a');
CjkInput.clear();
CjkInput.stashDraft('session-a');
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM + 'keep me');
});
it('clear() stashes a held draft for the session it was typed for, with no stash call', () => {
// goHome(), _replaceTileGrid and _onTileAdoptedElsewhere drop the active
// session before the next cleanup, which then has no session to stash for.
const { CjkInput, textarea, sent } = load();
CjkInput.restoreDraft('session-a');
type(textarea, 'typed for a');
CjkInput.clear();
expect(textarea.value).toBe(PHANTOM);
CjkInput.restoreDraft('session-b');
expect(textarea.value).toBe(PHANTOM);
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM + 'typed for a');
expect(sent).toEqual([]);
});
it('clear({ discard }) throws the draft away: a same-tab restore and a switch back stay empty', () => {
// The keyboard bar's clear-line key (terminal-ui.js clearTerminalInput).
const { CjkInput, textarea } = load();
CjkInput.restoreDraft('session-a');
type(textarea, 'thrown away');
CjkInput.clear({ discard: true });
expect(textarea.value).toBe(PHANTOM);
expect(CjkInput.draftOwner).toBe('session-a');
// Tapping the session's own tab: the field is kept, then restoreDraft runs.
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
// Switching away and back.
CjkInput.clear();
CjkInput.restoreDraft('session-b');
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
});
it('clear({ discard }) also drops an older stash of the same session', () => {
const { CjkInput, textarea } = load();
CjkInput.restoreDraft('session-a');
type(textarea, 'old');
CjkInput.stashDraft('session-a');
CjkInput.clear({ discard: true });
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
});
it('a removed session loses its field text: discardDraft drops the owner', () => {
const { CjkInput, textarea } = load();
CjkInput.restoreDraft('session-a');
type(textarea, 'for a closed tile');
CjkInput.discardDraft('session-a');
expect(CjkInput.draftOwner).toBe(null);
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
});
it('a field still holding text keeps its owner when another session is shown', () => {
const { CjkInput, textarea } = load();
CjkInput.restoreDraft('session-a');
type(textarea, 'still for a');
CjkInput.restoreDraft('session-b');
expect(CjkInput.draftOwner).toBe('session-a');
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM + 'still for a');
});
it('Ctrl shortcuts stay in the field while it holds a draft', () => {
// Ctrl+Z is undo, Ctrl+A select all, Ctrl+C copy: never a control byte to
// the CLI while there is a draft to act on.
const { textarea, sent } = load();
type(textarea, 'draft');
for (const key of ['z', 'a', 'c']) {
const preventDefault = vi.fn();
textarea.fire('keydown', { key, keyCode: key.toUpperCase().charCodeAt(0), ctrlKey: true, preventDefault });
expect(preventDefault).not.toHaveBeenCalled();
}
expect(sent).toEqual([]);
});
it('Ctrl shortcuts reach the CLI from an empty field', () => {
const { textarea, sent } = load();
const preventDefault = vi.fn();
textarea.fire('keydown', { key: 'c', keyCode: 67, ctrlKey: true, preventDefault });
expect(preventDefault).toHaveBeenCalled();
expect(sent).toEqual(['\x03']);
});
it('live mode keeps sending Ctrl shortcuts with text in the field', () => {
const { textarea, sent } = load({ hold: false });
textarea.value = PHANTOM + 'x';
textarea.fire('keydown', { key: 'c', keyCode: 67, ctrlKey: true });
expect(sent).toEqual(['\x03']);
});
it('sends a bare Enter when the field holds only blank lines', () => {
const { textarea, sent, prompts } = load();
type(textarea, '\n');
enter(textarea);
expect(prompts).toEqual([]);
expect(sent).toEqual(['\r']);
});
it('submit() mid-composition commits it first (blur, focus) and sends what landed', () => {
const { CjkInput, textarea, prompts } = load();
textarea.fire('compositionstart');
textarea.value = PHANTOM + 'yes';
textarea.fire('input', { isComposing: true, inputType: 'insertCompositionText' });
expect(CjkInput.submit()).toBe(true);
expect(textarea.blur).toHaveBeenCalled();
expect(textarea.focus).toHaveBeenCalled();
expect(prompts).toEqual(['yes']);
expect(textarea.value).toBe(PHANTOM);
});
it('a hidden field does not get a 0px height (no session shown yet)', () => {
const { CjkInput, textarea } = load({ hold: false });
textarea.getClientRects = () => [];
textarea.scrollHeight = 0;
textarea.style.height = '40px';
CjkInput.setHoldUntilEnter(true);
expect(textarea.style.height).toBe('');
});
it('live mode stashes no drafts', () => {
const { CjkInput, textarea } = load({ hold: false });
textarea.value = PHANTOM + 'abc';
CjkInput.stashDraft('session-a');
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
});
it('live mode is unchanged: text streams after the debounce', () => {
const { textarea, sent } = load({ hold: false });
type(textarea, 'hi');
vi.advanceTimersByTime(1000);
expect(sent).toEqual(['hi']);
});
});
-174
View File
@@ -1,174 +0,0 @@
// Port: none (pure logic in a vm context — no browser, no server).
//
// KeyboardHandler scrolls a newly focused text field into view (scrollInputIntoView,
// `scrollIntoView({ block: 'center' })`) once the keyboard is up. The pinned CJK /
// Send on Enter field (#cjkInput) is position:fixed and already lifted above the
// keyboard by updateLayoutForKeyboard(), so scrolling it into view only centred it in
// its scrollable ancestors and pushed the terminal off screen. It must be skipped,
// like xterm's own inputs, while ordinary inputs keep the behaviour.
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { describe, expect, it } from 'vitest';
const SOURCE = readFileSync(resolve(import.meta.dirname, '../src/web/public/mobile-handlers.js'), 'utf8');
function loadHandler() {
const context = vm.createContext({
console,
navigator: { userAgent: 'test', maxTouchPoints: 1 },
window: { addEventListener: () => {}, matchMedia: () => ({ matches: false }), scrollTo: () => {} },
document: {
body: { classList: { add: () => {}, remove: () => {} } },
addEventListener: () => {},
getElementById: () => null,
querySelector: () => null,
},
setTimeout: () => 1,
clearTimeout: () => {},
});
vm.runInContext(`${SOURCE}\nglobalThis.__KH = KeyboardHandler;`, context, { filename: 'mobile-handlers.js' });
return (context as { __KH: any }).__KH;
}
function element(tagName: string, { id = '', inside = '' }: { id?: string; inside?: string } = {}) {
return { tagName, id, type: '', isContentEditable: false, closest: (sel: string) => (sel === inside ? {} : null) };
}
describe('KeyboardHandler.isInputElement', () => {
it('skips the pinned CJK field, which the keyboard layout positions itself', () => {
expect(loadHandler().isInputElement(element('TEXTAREA', { id: 'cjkInput' }))).toBe(false);
});
it('still skips xterm inputs and still scrolls ordinary fields into view', () => {
const kh = loadHandler();
expect(kh.isInputElement(element('TEXTAREA', { inside: '.xterm' }))).toBe(false);
expect(kh.isInputElement(element('TEXTAREA', { id: 'someOtherField' }))).toBe(true);
expect(kh.isInputElement(element('INPUT'))).toBe(true);
});
});
function loadLayout({
focused = 'cjkInput',
offsetTop,
height = 458,
width = 390,
innerHeight = 744,
clientHeight = 744,
}: {
focused?: string;
offsetTop: number;
height?: number;
width?: number;
innerHeight?: number;
clientHeight?: number;
}) {
const el = (offsetHeight = 36) => ({
style: {} as Record<string, string>,
offsetHeight,
classList: { contains: () => true },
});
// .app is sized to the visual viewport (--app-height), which is what its fixed
// children are placed against once it carries a transform.
const nodes: Record<string, any> = {
'.app': el(height),
'.toolbar': el(),
'.main': el(),
'.keyboard-accessory-bar': el(),
'.mobile-case-picker.active .mobile-case-picker-sheet': el(300),
};
const cjk = { ...el(), id: 'cjkInput' };
const context = vm.createContext({
console,
navigator: { userAgent: 'test', maxTouchPoints: 1 },
window: {
addEventListener: () => {},
matchMedia: () => ({ matches: false }),
scrollTo: () => {},
innerHeight,
innerWidth: width, // MobileDetection (defined in the module) reads this
visualViewport: { offsetTop, height },
},
document: {
body: { classList: { add: () => {}, remove: () => {} } },
documentElement: { clientHeight },
addEventListener: () => {},
activeElement: focused === 'cjkInput' ? cjk : { id: focused },
getElementById: (id: string) => (id === 'cjkInput' ? cjk : null),
querySelector: (sel: string) => nodes[sel] || null,
},
setTimeout: () => 1,
clearTimeout: () => {},
});
vm.runInContext(`${SOURCE}\nglobalThis.__KH = KeyboardHandler;`, context, { filename: 'mobile-handlers.js' });
const kh = (context as { __KH: any }).__KH;
kh.keyboardVisible = true;
kh.initialViewportHeight = 744;
return { kh, nodes, cjk };
}
describe('KeyboardHandler follows the visual-viewport pan on phones', () => {
it('moves the app down by the pan and lifts nothing more (measured Android case)', () => {
const { kh, nodes, cjk } = loadLayout({ offsetTop: 285 });
kh.updateLayoutForKeyboard();
expect(nodes['.app'].style.transform).toBe('translateY(285px)');
// .app bottom = 285 + 458 = 743, visual bottom = 743: the bars already sit on it.
expect(nodes['.toolbar'].style.transform).toBe('');
expect(nodes['.keyboard-accessory-bar'].style.transform).toBe('');
expect(cjk.style.transform).toBe('');
});
it('does not lift the bars twice on a partial pan', () => {
// Mid-animation: offsetTop 100 in a 744 layout. Lifting by the layout gap (186px)
// inside the shifted .app would float the bars 186px above the keyboard.
const { kh, nodes, cjk } = loadLayout({ offsetTop: 100 });
kh.updateLayoutForKeyboard();
expect(nodes['.app'].style.transform).toBe('translateY(100px)');
expect(nodes['.toolbar'].style.transform).toBe('');
expect(nodes['.keyboard-accessory-bar'].style.transform).toBe('');
expect(cjk.style.transform).toBe('');
// The open case sheet is inside .app too (index.html #mobileCasePickerModal):
// the layout gap on top of the shift floated it 186px above the keyboard.
expect(nodes['.mobile-case-picker.active .mobile-case-picker-sheet'].style.transform).toBe('');
});
it('keeps the old lift when there is no pan', () => {
const { kh, nodes } = loadLayout({ offsetTop: 0 });
kh.updateLayoutForKeyboard();
expect(nodes['.app'].style.transform).toBe('');
expect(nodes['.toolbar'].style.transform).toBe('translateY(-286px)');
// Without a pan insideLift is the layout gap, so the case sheet keeps its lift
// (test/mobile-case-sheet-keyboard-lift.test.ts).
expect(nodes['.mobile-case-picker.active .mobile-case-picker-sheet'].style.transform).toBe('translateY(-286px)');
});
it('follows a pan whatever has focus, so a focus change cannot drop the shift', () => {
const { kh, nodes } = loadLayout({ focused: 'someOtherField', offsetTop: 285 });
kh.updateLayoutForKeyboard();
expect(nodes['.app'].style.transform).toBe('translateY(285px)');
});
it('never shifts the app outside the phone layout (tablet landscape)', () => {
const { kh, nodes } = loadLayout({ offsetTop: 285, width: 1024 });
nodes['.app'].style.transform = 'translateY(285px)'; // left over from portrait
kh.updateLayoutForKeyboard();
expect(nodes['.app'].style.transform).toBe('');
});
it('lifts the bars when iOS reports innerHeight as the shrunk visual height', () => {
// Measured on an iPhone, first keyboard open: innerHeight 323 = visual height,
// documentElement.clientHeight 640. Lifting by innerHeight - visual bottom gave 0.
const { kh, nodes, cjk } = loadLayout({ offsetTop: 0, height: 323, innerHeight: 323, clientHeight: 640 });
kh.updateLayoutForKeyboard();
expect(nodes['.toolbar'].style.transform).toBe('translateY(-317px)');
expect(nodes['.keyboard-accessory-bar'].style.transform).toBe('translateY(-317px)');
expect(cjk.style.transform).toBe('translateY(-317px)');
});
it('clears the shift when the layout resets', () => {
const { kh, nodes } = loadLayout({ offsetTop: 285 });
kh.updateLayoutForKeyboard();
kh.resetLayout();
expect(nodes['.app'].style.transform).toBe('');
});
});
+2 -138
View File
@@ -41,9 +41,8 @@ function loadTerminalModule(): TerminalModule {
console,
setInterval: vi.fn(),
clearInterval: vi.fn(),
// Looked up per call, so a test's vi.useFakeTimers() reaches the cached module.
setTimeout: (fn: () => void, ms?: number) => setTimeout(fn, ms),
clearTimeout: (t: ReturnType<typeof setTimeout>) => clearTimeout(t),
setTimeout,
clearTimeout,
requestAnimationFrame: vi.fn(),
HTMLCanvasElement: class HTMLCanvasElement {},
WebSocket: { OPEN: 1 },
@@ -548,141 +547,6 @@ describe('one-shot Ctrl through the CJK input field', () => {
});
});
describe('Send on Enter: a held answer goes out with Enter as its own write', () => {
// _sendCjkPrompt is CjkInput's sendPrompt callback. Anything longer than one
// character goes to the composer's _sendComposedPrompt with the session
// captured at Enter, so the delayed Enter cannot follow a tab switch.
function promptApp() {
const { CodemanApp, bar } = loadTerminalModule();
bar.clearCtrl();
const app = Object.create(CodemanApp.prototype) as {
activeSessionId: string | null;
_sendCjkPrompt(text: string): boolean;
};
app.activeSessionId = 'session-a';
const composed = vi
.spyOn(bar as unknown as { _sendComposedPrompt: (s: string, t: string) => boolean }, '_sendComposedPrompt')
.mockReturnValue(true);
return { app, bar, composed };
}
it('sends through the composer path, bound to the session active at Enter', () => {
const { app, composed } = promptApp();
expect(app._sendCjkPrompt('line one\nline two')).toBe(true);
app.activeSessionId = 'session-b';
expect(composed).toHaveBeenCalledWith('session-a', 'line one\nline two');
composed.mockRestore();
});
it('spends an armed one-shot Ctrl, like any multi-character chunk', () => {
const { app, bar, composed } = promptApp();
bar.toggleCtrl();
app._sendCjkPrompt('x'.repeat(100));
expect(bar.isCtrlArmed()).toBe(false);
composed.mockRestore();
});
it('types a single character, then Enter ~120 ms later to the same session', () => {
// Codex folds an Enter that arrives in the same burst as the text into a
// paste, even for `1\r`; a selection dialog ignores a pasted digit. Same
// split as TmuxManager.sendInput (submitsAsKeys).
vi.useFakeTimers();
try {
const { app, composed } = promptApp();
const writes: Array<[string, string, unknown]> = [];
(app as unknown as { _sendInputAsync: unknown })._sendInputAsync = (id: string, input: string, opts?: unknown) =>
writes.push([id, input, opts]);
expect(app._sendCjkPrompt('1')).toBe(true);
expect(writes).toEqual([['session-a', '1', undefined]]);
app.activeSessionId = 'session-b';
vi.advanceTimersByTime(119);
expect(writes).toHaveLength(1);
vi.advanceTimersByTime(1);
expect(writes[1]).toEqual(['session-a', '\r', { useMux: true }]);
expect(composed).not.toHaveBeenCalled();
composed.mockRestore();
} finally {
vi.useRealTimers();
}
});
it('sends a lone digit without Enter while a permission or question dialog waits', () => {
// The dialog acts on the digit keypress itself; an Enter 120 ms later would
// confirm whatever the CLI shows next (a second permission prompt, unseen).
// Same rule as the Approvals Inbox and the Discord bridge (awaitingChoice).
vi.useFakeTimers();
try {
for (const hook of ['permission_prompt', 'elicitation_dialog']) {
const { app, composed } = promptApp();
const writes: Array<[string, string, unknown]> = [];
(app as unknown as { _sendInputAsync: unknown })._sendInputAsync = (
id: string,
input: string,
opts?: unknown
) => writes.push([id, input, opts]);
(app as unknown as { pendingHooks: Map<string, Set<string>> }).pendingHooks = new Map([
['session-a', new Set([hook])],
]);
expect(app._sendCjkPrompt('2')).toBe(true);
vi.advanceTimersByTime(500);
expect(writes).toEqual([['session-a', '2', undefined]]);
composed.mockRestore();
}
} finally {
vi.useRealTimers();
}
});
it('keeps the delayed Enter for a digit when only an idle prompt is pending, or for a letter in a dialog', () => {
vi.useFakeTimers();
try {
const cases: Array<[string, string]> = [
['idle_prompt', '1'],
['permission_prompt', 'y'],
];
for (const [hook, text] of cases) {
const { app, composed } = promptApp();
const writes: Array<[string, string, unknown]> = [];
(app as unknown as { _sendInputAsync: unknown })._sendInputAsync = (
id: string,
input: string,
opts?: unknown
) => writes.push([id, input, opts]);
(app as unknown as { pendingHooks: Map<string, Set<string>> }).pendingHooks = new Map([
['session-a', new Set([hook])],
]);
expect(app._sendCjkPrompt(text)).toBe(true);
vi.advanceTimersByTime(120);
expect(writes).toEqual([
['session-a', text, undefined],
['session-a', '\r', { useMux: true }],
]);
composed.mockRestore();
}
} finally {
vi.useRealTimers();
}
});
it('pastes even a short word: only one character is typed', () => {
const { app, composed } = promptApp();
expect(app._sendCjkPrompt('yes')).toBe(true);
expect(composed).toHaveBeenCalledWith('session-a', 'yes');
composed.mockRestore();
});
it('reports a refusal so the field keeps the text', () => {
const { app, composed } = promptApp();
composed.mockReturnValue(false);
expect(app._sendCjkPrompt('x'.repeat(100))).toBe(false);
app.activeSessionId = null;
expect(app._sendCjkPrompt('x'.repeat(100))).toBe(false);
expect(app._sendCjkPrompt('1')).toBe(false);
expect(composed).toHaveBeenCalledTimes(1);
composed.mockRestore();
});
});
describe('armed styling survives the light-skin overrides', () => {
const mobileCss = readFileSync(resolve('src/web/public/mobile.css'), 'utf8');
-18
View File
@@ -1,18 +0,0 @@
/**
* @fileoverview The manifest link must be fetched with credentials. Browsers fetch the web app
* manifest without cookies unless the link says `crossorigin="use-credentials"`, and every
* non-exempt path needs the `codeman_session` cookie when a password is set, so without the
* attribute the manifest answers 401 and the browser refuses to install Codeman as an app.
*/
import { describe, expect, it } from 'vitest';
import { readFileSync } from 'node:fs';
const HTML = readFileSync(new URL('../src/web/public/index.html', import.meta.url), 'utf-8');
describe('PWA manifest link', () => {
it('requests the manifest with credentials so a password-protected install can be installed', () => {
const links = HTML.match(/<link\b[^>]*rel="manifest"[^>]*>/g) ?? [];
expect(links).toHaveLength(1);
expect(links[0]).toContain('crossorigin="use-credentials"');
});
});
-72
View File
@@ -181,78 +181,6 @@ describe('WebServer.renderIndexHtml', () => {
}
});
it('injects the wheelForward rules of every CLI that forwards, custom and disabled entries included', async () => {
// A custom clis.json entry shaped like pi (its mouse DECSETs stripped, wheel forwarded)
// must reach the browser's gate by its own id, and every `never` stays out. A DISABLED
// entry stays in: disabling a CLI never ends its running sessions, so a fullscreen copilot
// tab opened before the switch still needs its wheel after a reload (and an entry enabled
// after the page loaded already has its rule). A solo window scrolls a terminal too, so
// it gets the same map.
const path = dataPath('clis.json');
mkdirSync(dirname(path), { recursive: true });
const custom = {
label: 'PiD',
shortBadge: 'PL',
accent: '#6b7280',
enabled: true,
order: 120,
kind: 'agent',
discovery: { binaries: ['pi-locked'], searchDirs: [], install: { command: {} } },
launch: { params: {}, variants: [{ id: 'default', args: [{ lit: 'pi-locked' }] }] },
env: { exports: [], unset: [], tmuxSetenvKeys: [], dockerExecEnvNames: [], allowedPrefixes: [], allowedKeys: [] },
capabilities: {
external: true,
requiresMux: true,
hooks: 'none',
transcript: 'none',
altScreen: 'strip-mux-and-mouse',
echo: { policy: 'buffer', anchor: { kind: 'none' } },
wheelForward: { mode: 'always' },
keyboardAccessory: 'agent',
privilegedCommandGate: false,
startMode: 'interactive',
stripInkBloat: false,
ralph: false,
respawn: false,
effort: false,
agentSkillInjection: false,
statusLineTelemetry: false,
model: { source: 'none' },
privilegedParams: [],
privilegedEnvKeys: [],
gates: {},
customModelInjection: { kind: 'unsupported' },
},
overlays: {},
};
writeFileSync(
path,
JSON.stringify({ schemaVersion: 1, clis: { copilot: { enabled: false }, 'pi-locked': custom } }),
{
mode: 0o600,
}
);
reloadCliRegistry();
try {
for (const solo of [undefined, 'sess-123']) {
const { server } = makeServer({});
const html = await render(server, solo);
const match = html.match(/window\.__codemanWheelForward=(\{[^<]*\});/);
expect(match, String(solo)).not.toBeNull();
expect(JSON.parse(match![1])).toEqual({
claude: { mode: 'version-gated', minVersion: '2.1.187' },
codex: { mode: 'always' },
pi: { mode: 'always' },
copilot: { mode: 'always' },
'pi-locked': { mode: 'always' },
});
}
} finally {
writeFileSync(path, JSON.stringify({ clis: {} }, null, 2), { mode: 0o600 });
reloadCliRegistry();
}
});
it('injects the keyboard-hold modes from the keyboardHold capability: inline Claude, never full-height codex', async () => {
for (const solo of [undefined, 'sess-123']) {
const { server } = makeServer();
-339
View File
@@ -9,11 +9,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import Fastify, { type FastifyInstance } from 'fastify';
import fastifyCookie from '@fastify/cookie';
import fastifyWebsocket from '@fastify/websocket';
import WebSocket, { WebSocketServer } from 'ws';
import { once } from 'node:events';
import type { AddressInfo } from 'node:net';
import fs from 'node:fs/promises';
import http, { createServer, type IncomingHttpHeaders, type Server } from 'node:http';
import os from 'node:os';
import path from 'node:path';
import { registerWebviewRoutes } from '../../src/web/routes/webview-routes.js';
@@ -21,28 +17,12 @@ import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
import { webviewCapabilities } from '../../src/webview-capabilities.js';
import { capabilityFromProxyPath } from '../../src/web/webview-proxy.js';
import { writeWebviews } from '../../src/webview-store.js';
import { readUsers } from '../../src/user-store.js';
import { TabLayoutService } from '../../src/tab-layout-service.js';
import type { TabLayout } from '../../src/tab-layout.js';
/**
* The supervisor is the one process-spawning piece in this path. Its own tests
* cover the launch-token exchange and the starter binding; here a stub stands in
* for "this port has a cookie" so the route-level question stays what the proxy
* actually puts on the upstream request.
*/
const { getDeepSeekWebCookie } = vi.hoisted(() => ({
getDeepSeekWebCookie: vi.fn((_port: number, _owner?: string): string | null => null),
}));
vi.mock('../../src/deepseek-web-server.js', () => ({ getDeepSeekWebCookie }));
let app: FastifyInstance;
let tmpDir: string;
let savedDataDir: string | undefined;
let savedMultiUser: string | undefined;
/** Stands in for what the auth middleware decorates on the request. */
let currentUser: { username: string; role: 'admin' | 'user' } | undefined;
const broadcasts: Array<{ event: string; data: unknown }> = [];
const webviewCreated = vi.fn(async () => {});
const webviewDeleted = vi.fn(async () => {});
@@ -50,23 +30,15 @@ const webviewDeleted = vi.fn(async () => {});
beforeEach(async () => {
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'codeman-webviews-'));
savedDataDir = process.env.CODEMAN_DATA_DIR;
savedMultiUser = process.env.CODEMAN_MULTIUSER;
process.env.CODEMAN_DATA_DIR = tmpDir;
delete process.env.CODEMAN_MULTIUSER;
currentUser = undefined;
broadcasts.length = 0;
webviewCreated.mockClear();
webviewDeleted.mockClear();
getDeepSeekWebCookie.mockReset();
getDeepSeekWebCookie.mockReturnValue(null);
app = Fastify({ logger: false });
await app.register(fastifyCookie);
// The proxy route declares a wsHandler, so the plugin must be present.
await app.register(fastifyWebsocket);
app.addHook('onRequest', async (req) => {
if (currentUser) (req as unknown as { authUser: typeof currentUser }).authUser = currentUser;
});
registerWebviewRoutes(app, {
broadcast: (event: string, data: unknown) => broadcasts.push({ event, data }),
tabLayouts: { webviewCreated, webviewDeleted },
@@ -79,22 +51,11 @@ afterEach(async () => {
await app.close();
if (savedDataDir === undefined) delete process.env.CODEMAN_DATA_DIR;
else process.env.CODEMAN_DATA_DIR = savedDataDir;
if (savedMultiUser === undefined) delete process.env.CODEMAN_MULTIUSER;
else process.env.CODEMAN_MULTIUSER = savedMultiUser;
await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
});
const create = (payload: Record<string, unknown>) => app.inject({ method: 'POST', url: '/api/webviews', payload });
/** Wait for something a relayed connection reports asynchronously. */
async function waitUntil(check: () => boolean, timeoutMs = 2000): Promise<void> {
const deadline = Date.now() + timeoutMs;
while (!check()) {
if (Date.now() > deadline) throw new Error('condition not met in time');
await new Promise((resolve) => setTimeout(resolve, 10));
}
}
describe('GET /api/webviews', () => {
it('starts empty and reports the frame budget the client must honour', async () => {
const res = await app.inject({ method: 'GET', url: '/api/webviews' });
@@ -307,306 +268,6 @@ describe('proxy route', () => {
});
});
describe('proxy route: WebSocket cookie forwarding', () => {
let upstream: Server;
let upstreamPort: number;
let wss: WebSocketServer;
let appPort: number;
let upgradeHeaders: Promise<IncomingHttpHeaders>;
let client: WebSocket | undefined;
beforeEach(async () => {
let resolveUpgrade!: (headers: IncomingHttpHeaders) => void;
upgradeHeaders = new Promise((resolve) => {
resolveUpgrade = resolve;
});
// A real loopback dashboard: its upgrade handler is what records the cookie
// the proxy put on the handshake.
upstream = createServer();
wss = new WebSocketServer({ noServer: true });
upstream.on('upgrade', (req, socket, head) => {
resolveUpgrade(req.headers);
wss.handleUpgrade(req, socket, head, (upstreamSocket) => {
wss.emit('connection', upstreamSocket, req);
});
});
await new Promise<void>((resolve) => upstream.listen(0, '127.0.0.1', resolve));
upstreamPort = (upstream.address() as AddressInfo).port;
// WebSocket upgrades cannot go through inject(); this app needs a real port.
await app.listen({ port: 0, host: '127.0.0.1' });
appPort = (app.server.address() as AddressInfo).port;
});
afterEach(async () => {
client?.terminate();
client = undefined;
for (const socket of wss.clients) socket.terminate();
await new Promise<void>((resolve) => wss.close(() => resolve()));
await new Promise<void>((resolve) => upstream.close(() => resolve()));
await app.close();
});
/** Wait for a promise without letting a missing handshake hang the test until vitest's timeout. */
function within<T>(promise: Promise<T>, timeoutMs = 5000): Promise<T> {
let timer!: NodeJS.Timeout;
const timeout = new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new Error('timed out waiting for the upstream WebSocket handshake')), timeoutMs);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
/** Create a trusted tab, open it for a capability, and connect the browser leg with `cookie`. */
async function connectThroughProxy(cookie: string): Promise<void> {
const created = await create({
name: 'Trusted dashboard',
url: `http://127.0.0.1:${upstreamPort}/`,
trusted: true,
});
expect(created.statusCode).toBe(200);
const opened = await app.inject({ method: 'POST', url: `/api/webviews/${created.json().data.id}/open` });
const cap = capabilityFromProxyPath(opened.json().data.embedUrl)!;
client = await new Promise<WebSocket>((resolve, reject) => {
const socket = new WebSocket(`ws://127.0.0.1:${appPort}/webview/${cap}/ws`, { headers: { cookie } });
socket.once('open', () => resolve(socket));
socket.once('error', reject);
});
}
it('forwards only the dashboard cookie, never the Codeman session cookie', async () => {
await connectThroughProxy('codeman_session=SECRET; theme=dark');
const headers = await within(upgradeHeaders);
expect(headers.cookie).toBe('theme=dark');
expect(headers.cookie).not.toContain('codeman_session');
});
it('sends no cookie header when the browser only has the Codeman session cookie', async () => {
await connectThroughProxy('codeman_session=SECRET');
const headers = await within(upgradeHeaders);
expect(headers.cookie).toBeUndefined();
});
});
describe('managed DeepSeek web cookie', () => {
const COOKIE = 'dsh-auth-test=v1.payload.sig';
const upstreams: Array<{ port: number; cookies: Array<string | undefined>; close: () => Promise<void> }> = [];
/** A real loopback listener, so the assertion is on the bytes dsh would receive. */
async function startUpstream() {
const cookies: Array<string | undefined> = [];
const server = http.createServer((req, res) => {
cookies.push(req.headers.cookie);
res.writeHead(200, { 'content-type': 'text/plain' });
res.end('ok');
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('upstream has no address');
const upstream = {
port: address.port,
cookies,
close: () => new Promise<void>((resolve) => server.close(() => resolve())),
};
upstreams.push(upstream);
return upstream;
}
/** The stub answers for one port and one owner, like the supervisor's two checks. */
function mintCookieOn(port: number, owner: string | undefined): void {
getDeepSeekWebCookie.mockImplementation((askedPort, askedOwner) =>
askedPort === port && askedOwner === owner ? COOKIE : null
);
}
async function openManaged(url: string): Promise<string> {
const created = (await create({ name: 'DeepSeek Harness', url, managed: 'deepseek-web', trusted: true })).json()
.data;
const opened = (await app.inject({ method: 'POST', url: `/api/webviews/${created.id}/open` })).json().data;
return capabilityFromProxyPath(opened.embedUrl)!;
}
const getThrough = (cap: string) => app.inject({ method: 'GET', url: `/webview/${cap}/` });
async function writeUsersFixture(users: Array<{ username: string; role: string; canBypassPermissions: boolean }>) {
await fs.writeFile(
path.join(tmpDir, 'users.json'),
JSON.stringify({
version: 1,
users: users.map((user) => ({
...user,
password: { algo: 'scrypt', N: 1, r: 1, p: 1, salt: '00', hash: '00' },
createdAt: 1,
})),
})
);
// The store keeps a short cache; write through it instead of waiting for the TTL.
await readUsers(true);
}
afterEach(async () => {
await Promise.all(upstreams.splice(0).map((upstream) => upstream.close()));
});
it('presents it to a managed tab on 127.0.0.1 at the minted port', async () => {
const upstream = await startUpstream();
mintCookieOn(upstream.port, undefined);
const cap = await openManaged(`http://127.0.0.1:${upstream.port}/`);
expect((await getThrough(cap)).statusCode).toBe(200);
expect(upstream.cookies).toEqual([COOKIE]);
expect(getDeepSeekWebCookie).toHaveBeenCalledWith(upstream.port, undefined);
});
it('presents nothing to a managed tab on another port', async () => {
const minted = await startUpstream();
const other = await startUpstream();
mintCookieOn(minted.port, undefined);
const cap = await openManaged(`http://127.0.0.1:${other.port}/`);
expect((await getThrough(cap)).statusCode).toBe(200);
expect(other.cookies).toEqual([undefined]);
});
it('presents nothing to an unmanaged tab on the same port', async () => {
const upstream = await startUpstream();
mintCookieOn(upstream.port, undefined);
const created = (await create({ name: 'Not managed', url: `http://127.0.0.1:${upstream.port}/` })).json().data;
const opened = (await app.inject({ method: 'POST', url: `/api/webviews/${created.id}/open` })).json().data;
const cap = capabilityFromProxyPath(opened.embedUrl)!;
expect((await getThrough(cap)).statusCode).toBe(200);
expect(upstream.cookies).toEqual([undefined]);
expect(getDeepSeekWebCookie).not.toHaveBeenCalled();
});
// `managed` comes from the client and the port is public, so this is the case
// the gate exists for: a regular user must not receive the starter's cookie.
it('presents nothing in multi-user mode when the owner has no privileged grant', async () => {
process.env.CODEMAN_MULTIUSER = '1';
currentUser = { username: 'bob', role: 'user' };
await writeUsersFixture([{ username: 'bob', role: 'user', canBypassPermissions: false }]);
const upstream = await startUpstream();
mintCookieOn(upstream.port, 'bob');
const cap = await openManaged(`http://127.0.0.1:${upstream.port}/`);
expect((await getThrough(cap)).statusCode).toBe(200);
expect(upstream.cookies).toEqual([undefined]);
expect(getDeepSeekWebCookie).not.toHaveBeenCalled();
});
it('presents it in multi-user mode to a granted owner who started the server', async () => {
process.env.CODEMAN_MULTIUSER = '1';
currentUser = { username: 'carol', role: 'user' };
await writeUsersFixture([{ username: 'carol', role: 'user', canBypassPermissions: true }]);
const upstream = await startUpstream();
mintCookieOn(upstream.port, 'carol');
const cap = await openManaged(`http://127.0.0.1:${upstream.port}/`);
expect((await getThrough(cap)).statusCode).toBe(200);
expect(upstream.cookies).toEqual([COOKIE]);
expect(getDeepSeekWebCookie).toHaveBeenCalledWith(upstream.port, 'carol');
});
// A record keeps the owner it was created under. Back in single-user mode the
// server is started with no starter, so comparing that stale owner would leave
// the tab on dsh's 401 for good.
it('presents it in single-user mode to a managed tab created under multi-user mode', async () => {
process.env.CODEMAN_MULTIUSER = '1';
currentUser = { username: 'carol', role: 'user' };
await writeUsersFixture([{ username: 'carol', role: 'user', canBypassPermissions: true }]);
const upstream = await startUpstream();
const cap = await openManaged(`http://127.0.0.1:${upstream.port}/`);
delete process.env.CODEMAN_MULTIUSER;
currentUser = undefined;
mintCookieOn(upstream.port, undefined);
expect((await getThrough(cap)).statusCode).toBe(200);
expect(upstream.cookies).toEqual([COOKIE]);
expect(getDeepSeekWebCookie).toHaveBeenCalledWith(upstream.port, undefined);
});
/**
* A loopback listener that completes the upgrade and records the cookie on the
* handshake. The realtime leg is a separate code path from `proxyRequest`, so
* the HTTP assertions above say nothing about what it puts on the wire.
*/
async function startWebSocketUpstream() {
const cookies: Array<string | undefined> = [];
const server = http.createServer();
const wss = new WebSocketServer({ noServer: true });
server.on('upgrade', (req, socket, head) => {
cookies.push(req.headers.cookie);
wss.handleUpgrade(req, socket, head, (client) => client.close());
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('ws upstream has no address');
const upstream = {
port: address.port,
cookies,
close: () =>
new Promise<void>((resolve) => {
wss.close();
server.close(() => resolve());
}),
};
upstreams.push(upstream);
return upstream;
}
it('presents it on the websocket leg too, ahead of the browser cookies', async () => {
const upstream = await startWebSocketUpstream();
mintCookieOn(upstream.port, undefined);
const cap = await openManaged(`http://127.0.0.1:${upstream.port}/`);
// Upgrades need a real listener: inject() cannot carry them.
await app.listen({ port: 0, host: '127.0.0.1' });
const { port } = app.server.address() as AddressInfo;
const client = new WebSocket(`ws://127.0.0.1:${port}/webview/${cap}/ws`, {
headers: { cookie: 'codeman_session=SECRET; dsh-ui=dark' },
});
await once(client, 'open');
await waitUntil(() => upstream.cookies.length > 0);
// The credential leads so a stale browser copy cannot win, other dashboard
// cookies survive, and Codeman's own session cookie never goes upstream.
expect(upstream.cookies).toEqual([`${COOKIE}; dsh-ui=dark`]);
client.close();
});
});
describe('proxy HTML rewrite', () => {
// The request path is what the page's relative URLs are relative to. Proving
// it here (rather than only on rewriteHtml) pins that proxyRequest passes it.
it("resolves the document's relative base against its own directory", async () => {
const server = http.createServer((_req, res) => {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
res.end('<html><head><base href="./"></head><body>app</body></html>');
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('upstream has no address');
try {
const created = (await create({ name: 'App', url: `http://127.0.0.1:${address.port}/app/page.html` })).json()
.data;
const opened = (await app.inject({ method: 'POST', url: `/api/webviews/${created.id}/open` })).json().data;
const cap = capabilityFromProxyPath(opened.embedUrl)!;
const res = await app.inject({ method: 'GET', url: `/webview/${cap}/app/page.html` });
expect(res.statusCode).toBe(200);
expect(res.body).toContain(`<base href="/webview/${cap}/app/">`);
} finally {
await new Promise<void>((resolve) => server.close(() => resolve()));
}
});
});
describe('POST /api/webviews/probe', () => {
it('reports an unreachable target as a normal answer, not a 500', async () => {
// Port 1 is reserved and refuses instantly.
+1 -3
View File
@@ -117,9 +117,7 @@ describe('WebServer index.html <title> templating (#82)', () => {
// Likewise the page-key mode list: an array, possibly empty, always injected.
.replace(/<script>window\.__codemanTranscriptPageKeys=\[.*?\];<\/script>\n/, '')
// And the keyboard-hold mode list, built the same way.
.replace(/<script>window\.__codemanKeyboardHoldModes=\[.*?\];<\/script>\n/, '')
// And the wheel-forwarding rules: an object keyed by run mode, always injected.
.replace(/<script>window\.__codemanWheelForward=\{.*?\};<\/script>\n/, '');
.replace(/<script>window\.__codemanKeyboardHoldModes=\[.*?\];<\/script>\n/, '');
const beforeTitle = rawTemplate.split('<title>Codeman</title>')[0];
const afterTitle = rawTemplate.split('<title>Codeman</title>')[1];
expect(html.startsWith(beforeTitle)).toBe(true);
+1 -102
View File
@@ -28,19 +28,8 @@ import { STOCK_CLIS } from '../src/config/cli-registry/stock.js';
*/
const PAGE_KEY_MODES = STOCK_CLIS.filter((e) => e.capabilities.transcriptPageKeys === true).map((e) => e.id);
/**
* The run modes that take the wheel as SGR reports, read off the shipped registry the way
* the server builds `__codemanWheelForward` (every `wheelForward` other than `never`).
*/
const WHEEL_FORWARD = Object.fromEntries(
STOCK_CLIS.filter((e) => e.capabilities.wheelForward.mode !== 'never').map((e) => [e.id, e.capabilities.wheelForward])
);
function loadTerminalUiHarness(
windowGlobals: Record<string, unknown> = {
__codemanTranscriptPageKeys: PAGE_KEY_MODES,
__codemanWheelForward: WHEEL_FORWARD,
}
windowGlobals: Record<string, unknown> = { __codemanTranscriptPageKeys: PAGE_KEY_MODES }
) {
const CodemanApp = function CodemanApp(this: any) {};
const logs: string[] = [];
@@ -938,96 +927,6 @@ describe('pi wheel forwarding (fullscreen by default since 1.0.0)', () => {
});
});
describe('wheel forwarding read from the injected wheelForward map, for any CLI id', () => {
// A custom CLI (clis.json, e.g. a pi wrapper under its own id) that strips its mouse
// DECSETs gets `cliMouseTracking` like pi, but the gate used to name copilot and pi by id,
// so its wheel hit an empty local buffer after every tab switch or reload.
function customApp(
map: Record<string, unknown> | undefined,
session: { mode: string; cliMouseTracking?: boolean; cliVersion?: string }
) {
const globals: Record<string, unknown> = { __codemanTranscriptPageKeys: PAGE_KEY_MODES };
if (map) globals.__codemanWheelForward = map;
const { app } = loadTerminalUiHarness(globals);
app.activeSessionId = 'sess-1';
app.sessions = new Map([['sess-1', session]]);
app.terminal = {
rows: 36,
modes: { mouseTrackingMode: 'none' },
buffer: { active: { type: 'normal', viewportY: 0, baseY: 0, length: 36 } },
};
return app;
}
it('forwards a custom id the map lists as always, only while it tracks the mouse', () => {
const map = { 'pi-locked': { mode: 'always' } };
const tracking = customApp(map, { mode: 'pi-locked', cliMouseTracking: true });
expect(tracking._shouldForwardWheelToApp({ shiftKey: false })).toBe(true);
expect(tracking._shouldForwardWheelToApp({ shiftKey: true })).toBe(false);
expect(customApp(map, { mode: 'pi-locked', cliMouseTracking: false })._shouldForwardWheelToApp({})).toBe(false);
expect(customApp(map, { mode: 'pi-locked' })._shouldForwardWheelToApp({})).toBe(false);
});
it('applies a version-gated rule to a custom id: at or above minVersion only, unknown version never', () => {
const map = { 'my-cli': { mode: 'version-gated', minVersion: '2.0.0' } };
const at = (cliVersion?: string) =>
customApp(map, { mode: 'my-cli', cliMouseTracking: true, cliVersion })._shouldForwardWheelToApp({});
expect(at('1.9.9')).toBe(false);
expect(at('2.0.0')).toBe(true);
expect(at('2.0.1')).toBe(true);
expect(at(undefined)).toBe(false);
});
it('a version-gated rule whose minVersion is not three numbers forwards nothing, whatever the CLI version', () => {
// The schema takes any string up to 20 characters. A minimum that cannot be read as
// MAJOR.MINOR.PATCH must refuse, the conservative answer an unreadable session version gets.
for (const minVersion of ['', '0', '2.0', '1.2.3.4', '0.bad.999', 'x.y.z', '2..0', '+2.0.0', '0x1.0.0']) {
const app = customApp(
{ 'my-cli': { mode: 'version-gated', minVersion } },
{ mode: 'my-cli', cliMouseTracking: true, cliVersion: '9.9.9' }
);
expect(app._shouldForwardWheelToApp({}), JSON.stringify(minVersion)).toBe(false);
}
// A well-formed minimum keeps working, a leading `v` and surrounding spaces included.
for (const minVersion of ['9.9.9', 'v2.0.0', ' 2.0.0 ']) {
const app = customApp(
{ 'my-cli': { mode: 'version-gated', minVersion } },
{ mode: 'my-cli', cliMouseTracking: true, cliVersion: '9.9.9' }
);
expect(app._shouldForwardWheelToApp({}), JSON.stringify(minVersion)).toBe(true);
}
});
it('a version-gated rule with no minVersion (the schema allows it) forwards nothing and does not throw', () => {
const app = customApp(
{ 'my-cli': { mode: 'version-gated' } },
{ mode: 'my-cli', cliMouseTracking: true, cliVersion: '9.9.9' }
);
expect(app._shouldForwardWheelToApp({})).toBe(false);
});
it('never forwards an id the map leaves out, and nothing at all from a page rendered without the map', () => {
expect(
customApp(
{ 'pi-locked': { mode: 'always' } },
{ mode: 'other', cliMouseTracking: true }
)._shouldForwardWheelToApp({})
).toBe(false);
for (const mode of ['claude', 'codex', 'copilot', 'pi']) {
expect(
customApp(undefined, { mode, cliMouseTracking: true, cliVersion: '9.9.9' })._shouldForwardWheelToApp({}),
mode
).toBe(false);
}
});
it('a map entry of mode never forwards, even for a stock id', () => {
expect(
customApp({ pi: { mode: 'never' } }, { mode: 'pi', cliMouseTracking: true })._shouldForwardWheelToApp({})
).toBe(false);
});
});
describe('the paging gates asked for another pane (a TerminalTile)', () => {
it('exports the paging math, and the primary pane runs on it', () => {
const { app, sent, windowRef } = hollowApp();
-6
View File
@@ -49,11 +49,6 @@ const fetchMock = vi.fn();
*/
const PAGE_KEY_MODES = STOCK_CLIS.filter((e) => e.capabilities.transcriptPageKeys === true).map((e) => e.id);
/** The wheel-forwarding rules, read off the registry as the server builds `window.__codemanWheelForward`. */
const WHEEL_FORWARD = Object.fromEntries(
STOCK_CLIS.filter((e) => e.capabilities.wheelForward.mode !== 'never').map((e) => [e.id, e.capabilities.wheelForward])
);
/**
* The clock both panes read gesture gaps from (`performance.now()`). Real time by
* default; a test that needs a pause or a burst moves it by hand.
@@ -67,7 +62,6 @@ function loadContext() {
removeEventListener: vi.fn(),
CodemanBase: { base: '' },
__codemanTranscriptPageKeys: PAGE_KEY_MODES,
__codemanWheelForward: WHEEL_FORWARD,
};
const context = vm.createContext({
console: { ...console, log: vi.fn(), debug: vi.fn() },
+2 -48
View File
@@ -2,12 +2,6 @@ import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { describe, expect, it, vi } from 'vitest';
import { STOCK_CLIS } from '../src/config/cli-registry/stock.js';
/** The wheel-forwarding rules, read off the registry as the server builds `window.__codemanWheelForward`. */
const WHEEL_FORWARD = Object.fromEntries(
STOCK_CLIS.filter((e) => e.capabilities.wheelForward.mode !== 'never').map((e) => [e.id, e.capabilities.wheelForward])
);
function loadTerminalUiHarness() {
const CodemanApp = function CodemanApp(this: any) {};
@@ -16,7 +10,7 @@ function loadTerminalUiHarness() {
let activeElement: unknown = null;
// The module hangs its constants off window (CodemanTerminalInput) and the URL branch of
// the link provider opens through window.open, so tests need a handle on the same object.
const windowRef: Record<string, any> = { __codemanWheelForward: WHEEL_FORWARD };
const windowRef: Record<string, any> = {};
const context = vm.createContext({
window: windowRef,
document: {
@@ -145,28 +139,6 @@ describe('terminal touch tap mouse guard', () => {
expect(app._isMobileTerminalInputFocused()).toBe(true);
});
it('a content touchstart blurs xterm input but leaves the pinned CJK field focused', () => {
const { app, setActiveElement } = loadTerminalUiHarness();
setActiveElement({ id: '', classList: { contains: (c: string) => c === 'xterm-helper-textarea' } });
expect(app._contentTouchStartBlurs()).toBe(true);
// A swipe that starts on the live screen must not close the keyboard the field owns.
setActiveElement({ id: 'cjkInput', classList: { contains: () => false } });
expect(app._contentTouchStartBlurs()).toBe(false);
setActiveElement(null);
expect(app._contentTouchStartBlurs()).toBe(true);
});
it('the content touchstart only blurs through _contentTouchStartBlurs()', () => {
// The touchstart listener lives in initTerminal, which this harness does not run,
// so pin its one line: an unconditional blur there closes the pinned field's
// keyboard on every swipe that starts on the live screen.
const code = readFileSync(resolve(import.meta.dirname, '../src/web/public/terminal-ui.js'), 'utf8');
const branch = code.slice(code.indexOf("if (touchStartIntent === 'content') {"));
const body = branch.slice(0, branch.indexOf('// Hold still and this press becomes a text selection.'));
expect(body).toContain('if (this._contentTouchStartBlurs()) this._blurMobileTerminalInput();');
expect(body.match(/_blurMobileTerminalInput\(\)/g)).toHaveLength(1);
});
it('routes a readback row to the TUI while keeping the prompt row as keyboard input', () => {
const { app } = loadTerminalUiHarness();
app.activeSessionId = 'sess-1';
@@ -995,27 +967,9 @@ describe('terminal link tap', () => {
app._isOutsideWorktreePath = () => false;
windowRef.open = vi.fn();
app.registerFilePathLinkProvider();
return { app, windowRef, sent, setActiveElement: harness.setActiveElement };
return { app, windowRef, sent };
}
it('a link tap closes the keyboard of the pinned CJK field, which touchstart left focused', () => {
const line = 'Login at https://claude.ai/oauth/authorize?code=true&client_id=abc to finish';
const { app, setActiveElement } = linkHarness([line, '', '❯ ']);
const cjk = { id: 'cjkInput', classList: { contains: () => false }, blur: vi.fn() };
setActiveElement(cjk);
expect(app._handleMobileTerminalTap(at(line.indexOf('https')), false, 'content')).toBe('link');
expect(cjk.blur).toHaveBeenCalled();
});
it('a link tap leaves focus alone otherwise (touchstart already blurred xterm input)', () => {
const line = 'Login at https://claude.ai/oauth/authorize?code=true&client_id=abc to finish';
const { app, setActiveElement } = linkHarness([line, '', '❯ ']);
const other = { id: '', classList: { contains: () => false }, blur: vi.fn() };
setActiveElement(other);
expect(app._handleMobileTerminalTap(at(line.indexOf('https')), false, 'content')).toBe('link');
expect(other.blur).not.toHaveBeenCalled();
});
it('opens a URL under the finger in a new tab', () => {
const line = 'Login at https://claude.ai/oauth/authorize?code=true&client_id=abc to finish';
const { app, windowRef } = linkHarness([line, '', '❯ ']);
+4 -48
View File
@@ -115,32 +115,6 @@ describe('restrictTmuxPrefixTable (recorded commands)', () => {
expect(restrictTmuxPrefixTable(`tmux -L 'codeman'`, tmux.run)).toBe(false);
expect(tmux.calls.filter((c) => c.includes('bind-key'))).toEqual([]);
});
it('reads a one-binding table from the full listing when `list-keys -T prefix` prints nothing', () => {
// tmux 3.7 through 3.7c list a table holding exactly one binding as nothing at
// all on stdout (fixed in 3.8). The reduced table must still read as reduced, or every call resets it.
const tmux = fakeTmux({
'show-options -gv prefix': 'C-b\n',
'list-keys -T prefix': '',
'list-keys':
'bind-key -T copy-mode C-a send-keys -X start-of-line\n' +
'bind-key -T prefix C-b send-prefix\n' +
'bind-key -T root F1 detach-client\n',
});
expect(restrictTmuxPrefixTable(`tmux -L 'codeman'`, tmux.run)).toBe(false);
expect(tmux.calls).toContain(`tmux -L 'codeman' list-keys`);
expect(tmux.calls.filter((c) => c.includes('bind-key') || c.includes('unbind-key'))).toEqual([]);
});
it('still resets when the full listing shows a stock prefix binding', () => {
const tmux = fakeTmux({
'show-options -gv prefix': 'C-b\n',
'list-keys -T prefix': '',
'list-keys': 'bind-key -T prefix ) switch-client -n\n',
});
expect(restrictTmuxPrefixTable(`tmux -L 'codeman'`, tmux.run)).toBe(true);
expect(tmux.calls).toContain(`tmux -L 'codeman' unbind-key -a -T prefix`);
});
});
const hasTmux = (() => {
@@ -152,29 +126,12 @@ const hasTmux = (() => {
}
})();
/**
* One key table as `list-keys -T <table>` prints it. tmux 3.7 through 3.7c (fixed in
* 3.8) print NOTHING there when the table holds exactly one binding,
* which is the shape every reset in this file produces, so a blank answer is read from
* the full listing instead, its padding folded to the `-T <table>` form.
*/
function listKeyTable(base: string, table: string): string {
const run = (cmd: string): string => execSync(cmd, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
const direct = run(`${base} list-keys -T ${table}`);
if (direct.trim()) return direct;
return run(`${base} list-keys`)
.split('\n')
.filter((line) => new RegExp(`^bind-key\\s+(?:-\\S+\\s+)*?-T\\s+${table}\\s`).test(line.trim()))
.map((line) => line.trim().replace(/-T\s+(\S+)\s+/, '-T $1 '))
.join('\n');
}
describe.skipIf(!hasTmux)('restrictTmuxPrefixTable against a real tmux (private socket)', () => {
// Throwaway server, never Codeman's socket; -f /dev/null keeps the user's config out.
const socket = `codeman-prefix-test-${process.pid}`;
const tmux = `tmux -L ${socket} -f /dev/null`;
const run = (cmd: string): string => execSync(cmd, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
const keys = (table: string) => listKeyTable(tmux, table);
const keys = (table: string) => run(`${tmux} list-keys -T ${table}`);
let client: pty.IPty | null = null;
/** The session the attach client is looking at right now. */
@@ -318,8 +275,7 @@ describe.skipIf(!hasTmux)('restrictTmuxPrefixTable against a real tmux (private
run(`${tmux} set-option -g prefix 'C-\\'`);
try {
expect(restrictTmuxPrefixTable(tmux, run)).toBe(true);
// `list-keys -T` escapes the key (`C-\\`); the full listing some builds fall back to does not.
expect(keys('prefix')).toMatch(/-T prefix C-\\(?:\\)?\s+send-prefix/);
expect(keys('prefix')).toMatch(/-T prefix C-\\\\\s+send-prefix/);
expect(restrictTmuxPrefixTable(tmux, run)).toBe(false);
} finally {
run(`${tmux} set-option -g prefix C-b`);
@@ -389,7 +345,7 @@ describe.skipIf(!hasTmux)('nested Docker/remote tmux prefix table (private socke
it('after the nested reset, Ctrl+Q ), s and w leave the client, and Ctrl+Q Ctrl+Q reaches the pane', async () => {
for (const command of nestedPrefixTableResetCommands()) run(`${tmux} ${command}`);
const prefix = listKeyTable(tmux, 'prefix')
const prefix = run(`${tmux} list-keys -T prefix`)
.split('\n')
.filter((line) => line.trim());
expect(prefix).toEqual([expect.stringMatching(/-T prefix C-q\s+send-prefix$/)]);
@@ -425,7 +381,7 @@ describe.skipIf(!hasTmux)('nested Docker/remote tmux prefix table (private socke
].join(' \\; ');
try {
run(`${base} -f ${config} ${chain}`);
const prefix = listKeyTable(base, 'prefix')
const prefix = run(`${base} list-keys -T prefix`)
.split('\n')
.filter((line) => line.trim());
expect(prefix).toEqual([expect.stringMatching(/-T prefix C-q\s+send-prefix$/)]);
-57
View File
@@ -13,7 +13,6 @@ import { describe, it, expect } from 'vitest';
import {
applyLiveMetrics,
applyMuxNames,
attachTargetError,
beginAttachHandoff,
buildAttachBanner,
buildListLines,
@@ -31,7 +30,6 @@ import {
planResume,
previewIntervalMs,
previewNoteFor,
resolveAttachTarget,
resyncDelayMs,
sameFrame,
samePreview,
@@ -917,58 +915,3 @@ describe('planResume', () => {
});
});
});
describe('resolveAttachTarget (codeman tui <session>)', () => {
function named(name: string, group: TuiRow['group'], sessionId: string): TuiRow {
return {
session: { sessionId, sources: ['live'], name },
state: group === 'recent' ? 'recent' : 'idle',
group,
since: 0,
};
}
const rows: TuiRow[] = [
named('api', 'working', 'aaaaaaaa01'),
named('docs', 'idle', 'bbbbbbbb02'),
named('twin', 'idle', 'cccccccc03'),
named('twin', 'needs-you', 'dddddddd04'),
named('old', 'recent', 'eeeeeeee05'),
named('docs', 'recent', 'ffffffff06'),
];
it('keeps digits-only as a list position, as a number or as a string', () => {
expect(resolveAttachTarget(rows, 2)).toEqual({ kind: 'row', row: rows[1] });
expect(resolveAttachTarget(rows, '2')).toEqual({ kind: 'row', row: rows[1] });
expect(resolveAttachTarget(rows, '7')).toEqual({ kind: 'none' });
});
it('attaches the one live session with that exact name, ignoring a finished namesake', () => {
expect(resolveAttachTarget(rows, 'api')).toEqual({ kind: 'row', row: rows[0] });
expect(resolveAttachTarget(rows, 'docs')).toEqual({ kind: 'row', row: rows[1] });
});
it('matches case-sensitively and never by prefix', () => {
expect(resolveAttachTarget(rows, 'API')).toEqual({ kind: 'none' });
expect(resolveAttachTarget(rows, 'ap')).toEqual({ kind: 'none' });
});
it('refuses a name two live sessions share, naming their positions', () => {
expect(resolveAttachTarget(rows, 'twin')).toEqual({ kind: 'ambiguous', positions: [3, 4] });
});
it('says a name only history carries is finished, not missing', () => {
expect(resolveAttachTarget(rows, 'old')).toEqual({ kind: 'finished' });
expect(resolveAttachTarget(rows, 'nope')).toEqual({ kind: 'none' });
});
it('words each refusal for a human and points at --list', () => {
expect(attachTargetError({ kind: 'ambiguous', positions: [3, 4] }, 'twin')).toMatch(
/2 live sessions are named twin \(3, 4 in the list\)[\s\S]*codeman tui 3/
);
expect(attachTargetError({ kind: 'finished' }, 'old')).toContain('no live session named old');
expect(attachTargetError({ kind: 'none' }, 'nope')).toContain('there is no session named nope');
expect(attachTargetError({ kind: 'none' }, 9)).toContain('there is no session 9');
for (const kind of ['finished', 'none'] as const)
expect(attachTargetError({ kind }, 'x')).toContain('codeman tui --list');
});
});
-32
View File
@@ -1015,35 +1015,3 @@ describe('resumeSession', () => {
expect(recorded).toHaveLength(1);
});
});
describe('TuiClient key-table reads on a tmux that lists a one-binding table as nothing', () => {
// tmux 3.7 through 3.7c (fixed in 3.8) print nothing for `list-keys -T prefix` when
// the table holds exactly one binding, which is how Codeman leaves it. Reading that as "free"
// would let the TUI claim a key the user has bound.
const fullListing =
'bind-key -T copy-mode C-a send-keys -X start-of-line\n' +
'bind-key -T prefix C-b send-prefix\n' +
'bind-key -T root F1 detach-client\n';
function client(direct: string) {
const calls: string[][] = [];
const exec = async (_file: string, args: readonly string[]) => {
calls.push([...args]);
return { stdout: args.includes('-T') ? direct : fullListing, stderr: '' };
};
return { tui: new TuiClient({ socket: 'cod563', exec }), calls };
}
it('falls back to the full listing when the table answer is blank', async () => {
const { tui, calls } = client('');
expect(await tui.readPrefixBinding('C-b')).toBe('send-prefix');
expect(await tui.readPrefixBinding('F1', 'root')).toBe('detach-client');
expect(await tui.readPrefixBinding('x')).toBeNull();
expect(calls.some((args) => args.length === 3 && args[2] === 'list-keys')).toBe(true);
});
it('keeps the table answer when there is one, with no second call', async () => {
const { tui, calls } = client('bind-key -T prefix d detach-client\n');
expect(await tui.readDetachKey()).toBe('d');
expect(calls).toEqual([['-L', 'cod563', 'list-keys', '-T', 'prefix']]);
});
});
-41
View File
@@ -778,47 +778,6 @@ describe('codeman tui --list', () => {
}, 30_000);
});
describe('codeman tui <session name>', () => {
it('resolves an exact live name before asking for a terminal', async () => {
const result = await runPiped(['tui', 'w1-alpha']);
expect(result.code).toBe(1);
// Got past resolution: the only refusal left is the missing TTY.
expect(result.stderr).toContain('attaching needs an interactive terminal');
expect(result.stderr).not.toContain('no session');
}, 30_000);
it('says a name nothing carries is missing, and points at --list', async () => {
const result = await runPiped(['tui', 'w9-nope']);
expect(result.code).toBe(1);
expect(result.stderr).toContain('there is no session named w9-nope');
expect(result.stderr).toContain('codeman tui --list');
}, 30_000);
it('says a name only history carries is finished', async () => {
const result = await runPiped(['tui', 'w3-gamma']);
expect(result.code).toBe(1);
expect(result.stderr).toContain('no live session named w3-gamma, only a finished one');
}, 30_000);
it('refuses a name two live sessions share and names their numbers', async () => {
sessions.push({ ...sessions[1], sessionId: 'eeee5555-0000-0000-0000-000000000000' });
try {
const result = await runPiped(['tui', 'w1-alpha']);
expect(result.code).toBe(1);
expect(result.stderr).toMatch(/2 live sessions are named w1-alpha \(\d+, \d+ in the list\)/);
expect(result.stderr).toContain('Attach by number instead');
} finally {
resetSessions();
}
}, 30_000);
it('still reads digits as a list number', async () => {
const result = await runPiped(['tui', '42']);
expect(result.code).toBe(1);
expect(result.stderr).toContain('there is no session 42');
}, 30_000);
});
describe('codeman tui without a terminal', () => {
it('refuses to open the dashboard and points at the fast paths', async () => {
const result = await runPiped(['tui']);
-695
View File
@@ -1,695 +0,0 @@
/**
* @fileoverview Pins bounded fs.watch failure handling and polling fallback after a production chokidar retry loop flooded logs and synchronous close caused unhandled rejections.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import fs from 'node:fs';
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { TeamWatcher } from '../src/team-watcher.js';
import { WorkflowRunWatcher } from '../src/workflow-run-watcher.js';
import { TEAM_POLL_INTERVAL_MS } from '../src/config/team-config.js';
import { WORKFLOW_RUN_POLL_INTERVAL_MS } from '../src/config/workflow-config.js';
import type { TeamConfig } from '../src/types.js';
import type { WorkflowRunInfo } from '../src/types/workflow-run.js';
const FAILURES = [
{ code: 'EMFILE', errno: -24, text: 'too many open files' },
{ code: 'ENOSPC', errno: -28, text: 'no space left on device' },
] as const;
type WatchFailure = { code: string; errno: number; text: string };
// On macOS chokidar 3 never calls fs.watch for these watchers: it uses fsevents,
// or polling when fsevents is missing, so the retry loop these tests pin cannot
// happen there and the stubbed fs.watch never fires.
const describeLinuxWatch = describe.skipIf(process.platform === 'darwin');
const delay = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
async function waitUntil(predicate: () => boolean, message: string): Promise<void> {
const deadline = Date.now() + 1500;
while (!predicate()) {
if (Date.now() >= deadline) throw new Error(message);
await delay(10);
}
}
function watchError(failure: WatchFailure, path: string): NodeJS.ErrnoException {
return Object.assign(new Error(`${failure.code}: ${failure.text}, watch '${path}'`), {
code: failure.code,
errno: failure.errno,
syscall: 'watch',
path,
});
}
function failEveryWatch(failure: WatchFailure) {
return vi.spyOn(fs, 'watch').mockImplementation((path) => {
throw watchError(failure, String(path));
});
}
let tempDir: string;
let watcher: TeamWatcher | WorkflowRunWatcher | undefined;
let warn: ReturnType<typeof vi.spyOn<typeof console, 'warn'>>;
let error: ReturnType<typeof vi.spyOn<typeof console, 'error'>>;
let unhandled: unknown[];
let onUnhandled: (reason: unknown) => void;
beforeEach(async () => {
watcher = undefined;
tempDir = await mkdtemp(join(tmpdir(), 'codeman-watch-failure-'));
warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
error = vi.spyOn(console, 'error').mockImplementation(() => {});
unhandled = [];
onUnhandled = (reason) => unhandled.push(reason);
process.on('unhandledRejection', onUnhandled);
});
afterEach(async () => {
try {
watcher?.stop();
// Keep mocks and the rejection listener installed while asynchronous close settles.
await delay(100);
await rm(tempDir, { recursive: true, force: true });
} finally {
process.off('unhandledRejection', onUnhandled);
vi.useRealTimers();
vi.restoreAllMocks();
}
});
function createTeamConfig(): TeamConfig {
return {
name: 'test-team',
createdAt: 1_700_000_000_000,
leadAgentId: 'team-lead@test-team',
leadSessionId: 'session-123',
members: [
{
agentId: 'team-lead@test-team',
name: 'team-lead',
agentType: 'team-lead',
joinedAt: 1_700_000_000_000,
},
],
};
}
async function writeTeam(teamsDir: string, config: TeamConfig): Promise<void> {
const dir = join(teamsDir, config.name);
await mkdir(dir);
await writeFile(join(dir, 'config.json'), JSON.stringify(config));
}
describeLinuxWatch('TeamWatcher fs.watch failure', () => {
let teamsDir: string;
let tasksDir: string;
let teamWatcher: TeamWatcher;
beforeEach(async () => {
teamsDir = join(tempDir, 'teams');
tasksDir = join(tempDir, 'tasks');
await mkdir(teamsDir);
await mkdir(tasksDir);
watcher = teamWatcher = new TeamWatcher(teamsDir, tasksDir);
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
});
function expectWarnings(messages: string[]): void {
// Check counts before arguments so a retry storm cannot flood failure output.
expect(warn).toHaveBeenCalledTimes(messages.length);
expect(error).toHaveBeenCalledTimes(0);
expect(unhandled.length).toBe(0);
expect(warn.mock.calls.map((call) => [...call]).sort()).toEqual(messages.map((message) => [message]).sort());
}
it.each(FAILURES)('$code stops both watchers with two warnings and keeps polling', async (failure) => {
const watch = failEveryWatch(failure);
try {
teamWatcher.start();
await waitUntil(() => warn.mock.calls.length >= 2, 'timed out waiting for both watcher warnings');
const attempts = watch.mock.calls.length;
await delay(500);
// Check counts before arguments so the unfixed log storm cannot flood failure output.
expect(warn).toHaveBeenCalledTimes(2);
expect(error).toHaveBeenCalledTimes(0);
for (const call of warn.mock.calls) expect(call.length).toBe(1);
expect(warn.mock.calls.map(([message]) => message).sort()).toEqual(
[
`[TeamWatcher] teams watcher stopped, relying on polling: ${watchError(failure, teamsDir).message}`,
`[TeamWatcher] tasks watcher stopped, relying on polling: ${watchError(failure, tasksDir).message}`,
].sort()
);
expect(watch.mock.calls.length).toBe(attempts);
expect(attempts).toBeGreaterThanOrEqual(2);
// Allow a handful of in-flight attempts, but never an ancestor retry loop.
expect(attempts).toBeLessThanOrEqual(6);
expect(unhandled.length).toBe(0);
const expectedWarnings = [
`[TeamWatcher] teams watcher stopped, relying on polling: ${watchError(failure, teamsDir).message}`,
`[TeamWatcher] tasks watcher stopped, relying on polling: ${watchError(failure, tasksDir).message}`,
];
for (const pollCount of [2, 3, 4]) {
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(500);
// The same empty roots must cost the same bounded number of attempts on every tick.
expect(watch).toHaveBeenCalledTimes(attempts * pollCount);
expectWarnings(expectedWarnings);
expect(teamWatcher.getTeams()).toEqual([]);
await delay(200);
expect(watch).toHaveBeenCalledTimes(attempts * pollCount);
}
const config = createTeamConfig();
await writeTeam(teamsDir, config);
expect(teamWatcher.getTeams()).toEqual([]);
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await waitUntil(() => teamWatcher.getTeams().length > 0, 'polling did not discover the new team');
expect(teamWatcher.getTeams()).toEqual([config]);
await delay(500);
const finalAttempts = watch.mock.calls.length;
expect(finalAttempts - attempts * 4).toBeGreaterThanOrEqual(2);
expect(finalAttempts - attempts * 4).toBeLessThanOrEqual(6);
expectWarnings(expectedWarnings);
expect(() => teamWatcher.stop()).not.toThrow();
expect(() => teamWatcher.stop()).not.toThrow();
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS * 3);
await delay(500);
expect(watch).toHaveBeenCalledTimes(finalAttempts);
expectWarnings(expectedWarnings);
} finally {
teamWatcher.stop();
}
});
it('warns again about a watcher that still fails after stop() and start() on the same instance', async () => {
const failure = FAILURES[0];
const watch = failEveryWatch(failure);
const expectedWarnings = [
`[TeamWatcher] teams watcher stopped, relying on polling: ${watchError(failure, teamsDir).message}`,
`[TeamWatcher] tasks watcher stopped, relying on polling: ${watchError(failure, tasksDir).message}`,
];
try {
teamWatcher.start();
await waitUntil(() => warn.mock.calls.length >= 2, 'timed out waiting for both watcher warnings');
await delay(200);
expectWarnings(expectedWarnings);
teamWatcher.stop();
teamWatcher.start();
await waitUntil(() => warn.mock.calls.length >= 4, 'a restarted watcher stayed silent about the same outage');
await delay(200);
expectWarnings([...expectedWarnings, ...expectedWarnings]);
} finally {
teamWatcher.stop();
watch.mockRestore();
}
});
it('keeps a healthy watcher active and discovers a new team before the poll interval', async () => {
const watch = vi.spyOn(fs, 'watch');
try {
teamWatcher.start();
await waitUntil(() => watch.mock.calls.length >= 2, 'healthy watchers did not start');
await delay(200);
const attempts = watch.mock.calls.length;
for (let tick = 0; tick < 3; tick++) {
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(200);
expect(watch).toHaveBeenCalledTimes(attempts);
expect(teamWatcher.getTeams()).toEqual([]);
expectWarnings([]);
}
const config = createTeamConfig();
await writeTeam(teamsDir, config);
// No interval is advanced: discovery must come from the real filesystem watcher.
await waitUntil(() => teamWatcher.getTeams().length > 0, 'healthy watcher did not discover the new team');
expect(teamWatcher.getTeams()).toEqual([config]);
teamWatcher.stop();
await delay(100);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
expect(unhandled.length).toBe(0);
} finally {
teamWatcher.stop();
}
});
it.each(FAILURES)('$code resumes live discovery when both watchers recover on the next poll', async (failure) => {
const watch = failEveryWatch(failure);
const created = vi.fn();
const expectedWarnings = [
`[TeamWatcher] teams watcher stopped, relying on polling: ${watchError(failure, teamsDir).message}`,
`[TeamWatcher] tasks watcher stopped, relying on polling: ${watchError(failure, tasksDir).message}`,
];
try {
teamWatcher.on('teamCreated', created);
teamWatcher.start();
await waitUntil(() => warn.mock.calls.length >= 2, 'timed out waiting for both watcher warnings');
await delay(200);
expectWarnings(expectedWarnings);
watch.mockRestore();
const recoveredWatch = vi.spyOn(fs, 'watch');
await delay(200);
expect(recoveredWatch).toHaveBeenCalledTimes(0);
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(500);
expect(recoveredWatch).toHaveBeenCalledTimes(2);
expect(recoveredWatch.mock.calls.map(([path]) => String(path)).sort()).toEqual([teamsDir, tasksDir].sort());
expect(teamWatcher.getTeams()).toEqual([]);
const config = createTeamConfig();
await writeTeam(teamsDir, config);
// No further interval tick: the recovered teams watcher must discover this team.
await waitUntil(() => created.mock.calls.length > 0, 'recovered watcher did not discover the new team');
expect(created).toHaveBeenCalledTimes(1);
expect(created.mock.calls).toEqual([[config]]);
expect(teamWatcher.getTeams()).toEqual([config]);
expectWarnings(expectedWarnings);
} finally {
teamWatcher.stop();
teamWatcher.off('teamCreated', created);
}
});
it('re-arms after one new file throws ENOENT and resumes live discovery without another poll', async () => {
const realWatch = fs.watch;
const vanishedPath = join(teamsDir, 'vanished.json');
const failure = watchError({ code: 'ENOENT', errno: -2, text: 'no such file or directory' }, vanishedPath);
let failedCalls = 0;
const watch = vi.spyOn(fs, 'watch').mockImplementation((...args) => {
if (String(args[0]) === vanishedPath && failedCalls === 0) {
failedCalls++;
throw failure;
}
return realWatch(...args);
});
const created = vi.fn();
let closeErrorMessage = '';
try {
(undefined as unknown as fs.FSWatcher).close();
} catch (error) {
closeErrorMessage = (error as TypeError).message;
}
const expectedWarnings = [`[TeamWatcher] teams watcher stopped, relying on polling: ${closeErrorMessage}`];
try {
teamWatcher.on('teamCreated', created);
teamWatcher.start();
await waitUntil(() => watch.mock.calls.length >= 2, 'healthy watchers did not start');
await delay(200);
await writeFile(vanishedPath, '{}');
await waitUntil(() => warn.mock.calls.length > 0, 'the transient failure did not stop the teams watcher');
await delay(200);
expect(failedCalls).toBe(1);
expectWarnings(expectedWarnings);
await rm(vanishedPath);
const stoppedAttempts = watch.mock.calls.length;
await delay(200);
expect(watch).toHaveBeenCalledTimes(stoppedAttempts);
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(500);
expect(watch).toHaveBeenCalledTimes(stoppedAttempts + 1);
expect(watch.mock.calls.slice(stoppedAttempts).map(([path]) => String(path))).toEqual([teamsDir]);
expect(teamWatcher.getTeams()).toEqual([]);
const config = createTeamConfig();
await writeTeam(teamsDir, config);
await waitUntil(() => created.mock.calls.length > 0, 're-armed watcher did not discover the new team');
expect(created).toHaveBeenCalledTimes(1);
expect(created.mock.calls).toEqual([[config]]);
expect(teamWatcher.getTeams()).toEqual([config]);
expect(failedCalls).toBe(1);
expectWarnings(expectedWarnings);
} finally {
teamWatcher.stop();
teamWatcher.off('teamCreated', created);
}
});
it.each(FAILURES.flatMap((failure) => ['teams', 'tasks'].map((kind) => ({ ...failure, kind }))))(
'$code re-arms only the $kind watcher and warns again only after a healthy poll',
async ({ kind, ...failure }) => {
const root = kind === 'teams' ? teamsDir : tasksDir;
const healthyRoot = kind === 'teams' ? tasksDir : teamsDir;
const realWatch = fs.watch;
let failingPath: string | undefined = root;
const watch = vi.spyOn(fs, 'watch').mockImplementation((...args) => {
if (String(args[0]) === failingPath) throw watchError(failure, failingPath);
return realWatch(...args);
});
const expectedWarnings = [
`[TeamWatcher] ${kind} watcher stopped, relying on polling: ${watchError(failure, root).message}`,
];
const attemptsAt = (path: string) =>
watch.mock.calls.filter(([watchedPath]) => String(watchedPath) === path).length;
try {
teamWatcher.start();
await waitUntil(() => warn.mock.calls.length > 0, 'timed out waiting for the failed watcher warning');
await delay(200);
expectWarnings(expectedWarnings);
expect(attemptsAt(root)).toBe(1);
expect(attemptsAt(healthyRoot)).toBe(1);
for (const expectedAttempts of [2, 3]) {
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(500);
expect(watch).toHaveBeenCalledTimes(expectedAttempts + 1);
expect(attemptsAt(root)).toBe(expectedAttempts);
expect(attemptsAt(healthyRoot)).toBe(1);
expectWarnings(expectedWarnings);
await delay(200);
expect(watch).toHaveBeenCalledTimes(expectedAttempts + 1);
}
failingPath = undefined;
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(500);
expect(watch).toHaveBeenCalledTimes(5);
expect(attemptsAt(root)).toBe(4);
expect(attemptsAt(healthyRoot)).toBe(1);
expectWarnings(expectedWarnings);
// A successful re-arm alone does not end the outage before the following poll.
failingPath = join(root, 'before-healthy-poll.json');
await writeFile(failingPath, '{}');
await waitUntil(() => attemptsAt(failingPath!) > 0, 'recreated watcher did not watch the first new file');
await delay(200);
expect(watch).toHaveBeenCalledTimes(6);
expectWarnings(expectedWarnings);
await rm(failingPath);
failingPath = undefined;
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(500);
expect(watch).toHaveBeenCalledTimes(7);
expect(attemptsAt(root)).toBe(5);
expect(attemptsAt(healthyRoot)).toBe(1);
expectWarnings(expectedWarnings);
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS);
await delay(200);
expect(watch).toHaveBeenCalledTimes(7);
expectWarnings(expectedWarnings);
failingPath = join(root, 'after-healthy-poll.json');
await writeFile(failingPath, '{}');
await waitUntil(() => attemptsAt(failingPath!) > 0, 'healthy watcher did not watch the second new file');
await delay(200);
expect(watch).toHaveBeenCalledTimes(8);
expectWarnings([
...expectedWarnings,
`[TeamWatcher] ${kind} watcher stopped, relying on polling: ${watchError(failure, failingPath).message}`,
]);
expect(teamWatcher.getTeams()).toEqual([]);
} finally {
teamWatcher.stop();
}
}
);
it.each([{ code: 'healthy', failure: undefined }, ...FAILURES.map((failure) => ({ code: failure.code, failure }))])(
'$code stop closes both watchers and the interval and is idempotent',
async ({ failure }) => {
const watch = failure ? failEveryWatch(failure) : vi.spyOn(fs, 'watch');
const expectedWarnings = failure
? [
`[TeamWatcher] teams watcher stopped, relying on polling: ${watchError(failure, teamsDir).message}`,
`[TeamWatcher] tasks watcher stopped, relying on polling: ${watchError(failure, tasksDir).message}`,
]
: [];
try {
teamWatcher.start();
await waitUntil(() => watch.mock.calls.length >= 2, 'watchers did not attempt to start');
await delay(200);
expectWarnings(expectedWarnings);
const attempts = watch.mock.calls.length;
const closed: string[] = [];
if (!failure) {
expect(watch).toHaveBeenCalledTimes(2);
watch.mock.results.forEach((result, index) => {
expect(result.type).toBe('return');
(result.value as fs.FSWatcher).on('close', () => closed.push(String(watch.mock.calls[index][0])));
});
}
expect(() => teamWatcher.stop()).not.toThrow();
expect(() => teamWatcher.stop()).not.toThrow();
await delay(200);
if (!failure) expect(closed.sort()).toEqual([teamsDir, tasksDir].sort());
expect(vi.getTimerCount()).toBe(0);
await writeTeam(teamsDir, createTeamConfig());
await writeFile(join(tasksDir, 'after-stop.json'), '{}');
vi.advanceTimersByTime(TEAM_POLL_INTERVAL_MS * 3);
await delay(500);
expect(watch).toHaveBeenCalledTimes(attempts);
expect(teamWatcher.getTeams()).toEqual([]);
expectWarnings(expectedWarnings);
} finally {
teamWatcher.stop();
}
}
);
});
describeLinuxWatch('TeamWatcher in-flight fs.watch failure', () => {
it('stays stopped when file replacement and deletion race with ENOSPC', async () => {
const teamsDir = join(tempDir, 'teams');
const tasksDir = join(tempDir, 'tasks');
const teamDir = join(teamsDir, 't');
await mkdir(teamDir, { recursive: true });
await mkdir(tasksDir);
await writeFile(join(teamDir, 'a.json'), '{}');
await writeFile(join(teamDir, 'b.json'), '{}');
const teamWatcher = new TeamWatcher(teamsDir, tasksDir);
watcher = teamWatcher;
const realWatch = fs.watch;
const listeners = new Map<string, fs.WatchListener<string | Buffer>>();
const watch = vi.spyOn(fs, 'watch').mockImplementation((...args) => {
const handle = realWatch(...args);
if (args[2]) listeners.set(String(args[0]), args[2]);
return handle;
});
let firstFailure: NodeJS.ErrnoException | undefined;
let failingCalls = 0;
try {
teamWatcher.start();
await waitUntil(
() => listeners.has(join(teamDir, 'a.json')) && listeners.has(join(teamDir, 'b.json')),
'timed out waiting for both file watches'
);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
watch.mockImplementation((...args) => {
// Bound the unfixed retry loop so it can recover and the test can finish.
if (failingCalls >= 2000) return realWatch(...args);
failingCalls++;
const failure = watchError(FAILURES[1], String(args[0]));
firstFailure ??= failure;
throw failure;
});
fs.writeFileSync(join(teamDir, 'b.json.tmp'), '{"replaced":true}');
fs.renameSync(join(teamDir, 'b.json.tmp'), join(teamDir, 'b.json'));
await waitUntil(() => warn.mock.calls.length > 0, 'timed out waiting for the teams watcher warning');
// Deliver the queued deletion callback only after the replacement failure stops the watcher.
fs.unlinkSync(join(teamDir, 'a.json'));
listeners.get(join(teamDir, 'a.json'))!('rename', 'a.json');
await delay(1000);
const attempts = watch.mock.calls.length;
const failures = failingCalls;
await delay(500);
const settledAttempts = watch.mock.calls.length;
const settledFailures = failingCalls;
const warnings = warn.mock.calls.length;
teamWatcher.stop();
await delay(500);
// Check counts before arguments so a retry storm cannot flood failure output.
expect(warn).toHaveBeenCalledTimes(1);
expect(warnings).toBe(1);
expect(error).toHaveBeenCalledTimes(0);
expect(unhandled.length).toBe(0);
expect(watch.mock.calls.length).toBe(settledAttempts);
expect(failingCalls).toBe(settledFailures);
expect(settledAttempts).toBe(attempts);
expect(settledFailures).toBe(failures);
expect(failures).toBeGreaterThanOrEqual(1);
expect(failures).toBeLessThanOrEqual(6);
expect(firstFailure?.code).toBe('ENOSPC');
expect(firstFailure?.path?.startsWith(`${teamDir}/`)).toBe(true);
expect(warn.mock.calls).toEqual([
[`[TeamWatcher] teams watcher stopped, relying on polling: ${firstFailure?.message}`],
]);
} finally {
teamWatcher.stop();
}
});
});
const PROJECT_HASH = '-home-arkon-default-claudeman';
const SESSION_UUID = '388113c8-cd01-4e80-93a8-3be66ab1519b';
const RUN_ID = 'wf_test1234-abc';
const RUN_START = 1_700_000_000_000;
function sampleRunJson() {
return {
runId: RUN_ID,
timestamp: new Date(RUN_START).toISOString(),
workflowName: 'watch-failure-test',
summary: 'Discover a run despite exhausted filesystem watches',
status: 'completed',
startTime: RUN_START,
agentCount: 0,
durationMs: 1234,
totalTokens: 0,
totalToolCalls: 0,
phases: [],
workflowProgress: [],
};
}
const { workflowProgress: _progress, ...runFields } = sampleRunJson();
const EXPECTED_RUN: WorkflowRunInfo = {
...runFields,
agents: [],
projectHash: PROJECT_HASH,
sessionUuid: SESSION_UUID,
lastActivityAt: RUN_START,
};
describeLinuxWatch('WorkflowRunWatcher fs.watch failure', () => {
let runWatcher: WorkflowRunWatcher;
let workflowsDir: string;
beforeEach(async () => {
const projectsDir = join(tempDir, 'projects');
workflowsDir = join(projectsDir, PROJECT_HASH, SESSION_UUID, 'workflows');
await mkdir(workflowsDir, { recursive: true });
await writeFile(join(workflowsDir, `${RUN_ID}.json`), JSON.stringify(sampleRunJson()));
watcher = runWatcher = new WorkflowRunWatcher(projectsDir);
// Later interval polls run only when a test explicitly advances the clock.
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
});
function firstRun(): Promise<WorkflowRunInfo> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
runWatcher.off('run_discovered', onRun);
reject(new Error('timed out waiting for run_discovered'));
}, 1500);
function onRun(info: WorkflowRunInfo) {
clearTimeout(timer);
resolve(info);
}
runWatcher.once('run_discovered', onRun);
runWatcher.start();
});
}
it.each(FAILURES)('$code discovers the run without retries, logging, or unhandled rejections', async (failure) => {
const watch = failEveryWatch(failure);
try {
const discovered = await firstRun();
await delay(500);
const attempts = watch.mock.calls.length;
await delay(500);
expect(unhandled.length).toBe(0);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
expect(watch.mock.calls.length).toBe(attempts);
expect(attempts).toBeGreaterThanOrEqual(1);
expect(attempts).toBeLessThanOrEqual(3);
expect(discovered).toEqual(EXPECTED_RUN);
expect(runWatcher.getRun(RUN_ID)).toEqual(EXPECTED_RUN);
expect(runWatcher.getAllRuns()).toEqual([EXPECTED_RUN]);
expect(runWatcher.isRunning()).toBe(true);
runWatcher.stop();
expect(runWatcher.isRunning()).toBe(false);
await delay(100);
expect(unhandled.length).toBe(0);
expect(watch.mock.calls.length).toBe(attempts);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
} finally {
runWatcher.stop();
}
});
it('retries a failed directory once per poll and resumes live discovery when fs.watch recovers', async () => {
const watch = failEveryWatch(FAILURES[0]);
const discovered = vi.fn();
try {
expect(await firstRun()).toEqual(EXPECTED_RUN);
await delay(500);
const attemptsPerPoll = watch.mock.calls.length;
expect(attemptsPerPoll).toBeGreaterThanOrEqual(1);
expect(attemptsPerPoll).toBeLessThanOrEqual(3);
await delay(500);
expect(watch).toHaveBeenCalledTimes(attemptsPerPoll);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
expect(unhandled.length).toBe(0);
for (const pollCount of [2, 3]) {
vi.advanceTimersByTime(WORKFLOW_RUN_POLL_INTERVAL_MS);
await waitUntil(
() => watch.mock.calls.length > attemptsPerPoll * (pollCount - 1),
'later poll did not retry the failed workflows directory'
);
await delay(500);
expect(watch).toHaveBeenCalledTimes(attemptsPerPoll * pollCount);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
expect(unhandled.length).toBe(0);
}
watch.mockRestore();
const recoveredWatch = vi.spyOn(fs, 'watch');
vi.advanceTimersByTime(WORKFLOW_RUN_POLL_INTERVAL_MS);
await waitUntil(() => recoveredWatch.mock.calls.length > 0, 'recovery poll did not install a watcher');
// Let watcher setup and the recovery poll settle before creating the new completion file.
await delay(500);
expect(runWatcher.getAllRuns()).toEqual([EXPECTED_RUN]);
const otherId = 'wf_recovered5678-def';
runWatcher.on('run_discovered', discovered);
await writeFile(join(workflowsDir, `${otherId}.json`), JSON.stringify({ ...sampleRunJson(), runId: otherId }));
// Do not advance the interval again: only the recovered watcher can discover this file.
await waitUntil(() => discovered.mock.calls.length > 0, 'recovered watcher did not discover the new run');
expect(discovered).toHaveBeenCalledTimes(1);
const expectedRun = { ...EXPECTED_RUN, runId: otherId };
expect(discovered).toHaveBeenCalledWith(expectedRun);
expect(runWatcher.getRun(otherId)).toEqual(expectedRun);
runWatcher.stop();
await delay(100);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
expect(unhandled.length).toBe(0);
} finally {
runWatcher.stop();
runWatcher.off('run_discovered', discovered);
}
});
it('discovers a run with a healthy watcher without logging or unhandled rejections', async () => {
try {
const discovered = await firstRun();
await delay(1000);
expect(discovered).toEqual(EXPECTED_RUN);
expect(runWatcher.getRun(RUN_ID)).toEqual(EXPECTED_RUN);
expect(runWatcher.getAllRuns()).toEqual([EXPECTED_RUN]);
runWatcher.stop();
await delay(100);
expect(warn).toHaveBeenCalledTimes(0);
expect(error).toHaveBeenCalledTimes(0);
expect(unhandled.length).toBe(0);
} finally {
runWatcher.stop();
}
});
});
-177
View File
@@ -13,7 +13,6 @@ import {
buildUpstreamRequestHeaders,
capabilityFromProxyPath,
capabilityFromReferer,
escapedWebviewAssetPath,
extractFrameAncestors,
filterCookieHeader,
isFramableCrossOrigin,
@@ -239,56 +238,6 @@ describe('buildUpstreamRequestHeaders', () => {
expect(headers.authorization).toBeUndefined();
});
// `dsh web` mints its session cookie for the loopback authority the proxy
// dials, which the browser has never visited and cannot store anything for.
// The supervisor holds it instead. The managed tab is trusted, so the browser's
// other dsh cookies are still present and must be kept alongside it.
it('puts the server-held credential ahead of the filtered browser cookies', () => {
const headers = buildUpstreamRequestHeaders({ cookie: 'codeman_session=SECRET; dash=1' }, upstream, {
forwardCookies: true,
sessionCookieName: 'codeman_session',
injectedCookie: 'dsh-auth-p=v1.payload.sig',
});
expect(headers.cookie).toBe('dsh-auth-p=v1.payload.sig; dash=1');
});
it('keeps every non-Codeman browser cookie when injecting the server credential', () => {
const headers = buildUpstreamRequestHeaders(
{ cookie: 'dsh-ui=dark; codeman_session=SECRET; dsh-settings=z' },
upstream,
{
forwardCookies: true,
sessionCookieName: 'codeman_session',
injectedCookie: 'dsh-auth-p=v1.payload.sig',
}
);
expect(headers.cookie).toBe('dsh-auth-p=v1.payload.sig; dsh-ui=dark; dsh-settings=z');
});
// A `Cookie` header may name the same cookie twice, and the first value is the
// one parsers keep. The browser can still hold a dsh cookie from an earlier
// proxied response, so the server's fresh copy has to lead or the stale one wins
// and the tab goes back to the 401 this whole path exists to prevent.
it('keeps the server credential in front of a stale browser copy of the same name', () => {
const headers = buildUpstreamRequestHeaders({ cookie: 'dsh-auth-p=STALE; dsh-ui=dark' }, upstream, {
forwardCookies: true,
sessionCookieName: 'codeman_session',
injectedCookie: 'dsh-auth-p=FRESH',
});
// The stale copy is still forwarded behind it (dropping it would need its own
// name parsing), but the parser sees FRESH first, which is what authenticates.
expect(headers.cookie).toBe('dsh-auth-p=FRESH; dsh-auth-p=STALE; dsh-ui=dark');
});
it('sends the server-held credential even when browser cookies are not forwarded', () => {
const headers = buildUpstreamRequestHeaders({}, upstream, {
forwardCookies: false,
sessionCookieName: 'codeman_session',
injectedCookie: 'dsh-auth-p=v1.payload.sig',
});
expect(headers.cookie).toBe('dsh-auth-p=v1.payload.sig');
});
it('presents Origin/Referer as if the browser talked to the dashboard directly', () => {
const headers = buildUpstreamRequestHeaders({ origin: 'https://codeman.local' }, upstream, {
forwardCookies: false,
@@ -396,38 +345,6 @@ describe('rewriteHtml', () => {
expect(out.match(/<base/g)).toHaveLength(1);
});
// A Vite build ships `<base href="./">`, and the runtime shim rewrites the
// document URL to strip the prefix — so "./" would resolve to Codeman's root
// and every module script would 404 behind an otherwise-painted page.
it('resolves a page-relative <base> against the prefix before the shim masks the URL', () => {
const out = rewriteHtml('<html><head><base href="./"></head></html>', CAP);
expect(out).toContain(`<base href="${PREFIX}">`);
expect(out.match(/<base/g)).toHaveLength(1);
});
it('keeps a sub-path in a relative <base> inside the proxy prefix', () => {
const out = rewriteHtml('<html><head><base target="_blank" href="./sub/"></head></html>', CAP);
expect(out).toContain(`<base target="_blank" href="${PREFIX}sub/">`);
});
// A document served from a subdirectory resolves its relative base against
// ITS directory, not the proxy root: `/webview/<cap>/app/page.html` with
// `<base href="./">` must point at `/webview/<cap>/app/`.
it("resolves a relative <base> against the document's own directory", () => {
const out = rewriteHtml('<html><head><base href="./"></head></html>', CAP, '', 'app/page.html');
expect(out).toContain(`<base href="${PREFIX}app/">`);
});
it('resolves a ../ base from the document directory', () => {
const out = rewriteHtml('<html><head><base href="../assets/"></head></html>', CAP, '', 'app/sub/page.html');
expect(out).toContain(`<base href="${PREFIX}app/assets/">`);
});
it('leaves a cross-origin <base> exactly as the author wrote it', () => {
const out = rewriteHtml('<html><head><base href="https://cdn.example/x/"></head></html>', CAP);
expect(out).toContain('<base href="https://cdn.example/x/">');
});
it('still injects the runtime shim when the page ships its own <base>', () => {
// The shim is the only layer that catches runtime-built URLs, so an early
// return on an existing <base> would silently break those pages.
@@ -441,48 +358,6 @@ describe('rewriteHtml', () => {
expect(rewriteHtml('just text', CAP)).toContain('<script>');
});
// SvelteKit's inline bootstrap does `import("/_app/…")`. A dynamic import is
// neither an attribute nor a fetch(), so `<base>` and the runtime shim both
// miss it and the module loads from Codeman's root — the app then sits on its
// own spinner forever.
it('rewrites root-absolute dynamic import() specifiers', () => {
const dq = rewriteHtml('<head><script>import("/_app/entry.js")</script></head>', CAP);
expect(dq).toContain(`import("${PREFIX}_app/entry.js")`);
const sq = rewriteHtml("<head><script>import( '/x.js' )</script></head>", CAP);
expect(sq).toContain(`import('${PREFIX}x.js' )`);
});
it('leaves relative and cross-origin import() specifiers alone', () => {
const out = rewriteHtml(
`<head><script>import("./a.js");import("//cdn.example/b.js");import("https://cdn.example/c.js")</script></head>`,
CAP
);
expect(out).toContain('import("./a.js")');
expect(out).toContain('import("//cdn.example/b.js")');
expect(out).toContain('import("https://cdn.example/c.js")');
});
// The rewrite is for specifiers a loader will execute, not for the word
// appearing in the page a reader sees.
it('leaves import() in visible text alone', () => {
const out = rewriteHtml(
`<html><body><pre>import("/example.js")</pre><code>import('/other.js')</code></body></html>`,
CAP
);
expect(out).toContain('<pre>import("/example.js")</pre>');
expect(out).toContain("<code>import('/other.js')</code>");
expect(out).not.toContain(`${PREFIX}example.js`);
});
it('rewrites imports in every script body, including one with attributes', () => {
const out = rewriteHtml(
`<head><script type="module">import("/_app/a.js")</script><script defer>import('/b.js')</script></head>`,
CAP
);
expect(out).toContain(`import("${PREFIX}_app/a.js")`);
expect(out).toContain(`import('${PREFIX}b.js')`);
});
it('rebases root-absolute src/href/action, which <base> cannot fix', () => {
const out = rewriteHtml(
`<head></head><body><script src="/static/app.js"></script><link href='/s.css'><form action="/login"></form></body>`,
@@ -983,55 +858,3 @@ describe('lost-frame recovery', () => {
expect(has({ authorization: 'Basic YWRtaW46eA==' })).toBe(true);
});
});
describe('escapedWebviewAssetPath: naming a 404 a web tab caused', () => {
const req = (over: Record<string, unknown> = {}) => ({
method: 'GET',
url: '/_app/immutable/entry/start.js',
...over,
headers: {
host: 'codeman.example:3001',
referer: 'http://codeman.example:3001/',
'sec-fetch-dest': 'script',
...((over.headers as Record<string, string | string[] | undefined> | undefined) ?? {}),
},
});
it('recognises a root-absolute module a masked frame asked for', () => {
expect(escapedWebviewAssetPath(req())).toBe('/_app/immutable/entry/start.js');
});
it('drops the query string, which carries no diagnostic value', () => {
expect(escapedWebviewAssetPath(req({ url: '/_app/x.js?v=17' }))).toBe('/_app/x.js');
});
it('ignores every shape that is not a dashboard asset', () => {
// A navigation is the lost-frame recovery's job, not this one's.
expect(
escapedWebviewAssetPath(req({ headers: { host: 'h', referer: 'http://h/', 'sec-fetch-dest': 'document' } }))
).toBeNull();
// Codeman's own missing files say nothing about a web tab.
expect(
escapedWebviewAssetPath(
req({ url: '/favicon.ico', headers: { host: 'h', referer: 'http://h/', 'sec-fetch-dest': 'image' } })
)
).toBeNull();
// A real Codeman page's assets resolve; only a masked landing (`/`) is this shape.
expect(
escapedWebviewAssetPath(req({ headers: { host: 'h', referer: 'http://h/settings', 'sec-fetch-dest': 'script' } }))
).toBeNull();
// Cross-origin referer, API paths, writes, and no referer at all.
expect(
escapedWebviewAssetPath(req({ headers: { host: 'h', referer: 'http://other/', 'sec-fetch-dest': 'script' } }))
).toBeNull();
expect(escapedWebviewAssetPath(req({ url: '/api/thing' }))).toBeNull();
expect(escapedWebviewAssetPath(req({ method: 'POST' }))).toBeNull();
expect(escapedWebviewAssetPath(req({ headers: { host: 'h' } }))).toBeNull();
});
it('accepts the array headers a proxy front end can produce', () => {
expect(
escapedWebviewAssetPath(req({ headers: { host: ['h'], referer: ['http://h/'], 'sec-fetch-dest': ['image'] } }))
).toBe('/_app/immutable/entry/start.js');
});
});