mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-21 13:39:32 +01:00
Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4cedeec529 | ||
|
|
e99b42c387 | ||
|
|
574eae72f3 | ||
|
|
75ea908f29 | ||
|
|
d44b049c51 | ||
|
|
259cabd738 | ||
|
|
f1b2a2ab75 | ||
|
|
03cb6a68b4 | ||
|
|
6fb8b27768 | ||
|
|
f604deba3e | ||
|
|
60f1900081 | ||
|
|
fa4815b465 | ||
|
|
a26be7c98f | ||
|
|
4423949923 | ||
|
|
5396e33b48 |
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"aicodeman": patch
|
||||
---
|
||||
|
||||
**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.
|
||||
@@ -76,6 +76,8 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
| Regenerate the CLI catalogue | `npm run generate:cli-catalog` (`--check` to fail on drift). Rewrites `config/clis.stock.json` **and** the marked block in `install.sh` from `stock.ts`. ⚠ **Commit both.** They are what `install.sh` and the Docker agent image read, since neither can import TypeScript; `test/cli-catalog-sync.test.ts` and a CI `--check` step fail if either goes stale. See `docs/cli-registry.md` |
|
||||
| Build the docker agent image | `node scripts/build-agent-image.mjs --no-cache` (builds `codeman/agent:base` from `docker/agent.Dockerfile`; prerequisite for Docker cases; `--engine`/`--image`). ⚠ **Always `--no-cache`** — a plain rebuild re-uses the cached `npm install -g` layer and silently keeps the CLIs frozen at their original versions, which once shipped a BROKEN codex while reporting success. See `docs/docker-cases.md` |
|
||||
| Browser-test exclusion check | `npm run check:browser-excludes` (`scripts/check-browser-test-excludes.mjs`; runs in CI, <1s). Fails if a test importing playwright/puppeteer is still collected by `config/vitest.ci.config.ts`; add it to `BROWSER_TEST_GLOBS` in `config/test-suites.ts` |
|
||||
| Dead-code report | `npm run knip` (`config/knip.json`; fetched with `npx`, so it needs the network and is not a CI step). It reports nothing on a clean tree: an export, file or dependency it lists is new dead code, or a manual script that needs an `entry`. Tests count as users, and `src/web/public/` is outside it (plain scripts with no imports). A deliberate keep carries `@knipignore` in its JSDoc |
|
||||
| Frontend dead-code check | `npm run check:frontend-dead` (`scripts/check-frontend-dead-code.mjs`, a few seconds, not a CI step). `src/web/public/` is plain scripts that knip cannot follow, so this is its counterpart there: it fails on a function, method or top-level binding that nothing references (identifiers, strings, `index.html`, the gesture overlay's source, tests) and on a CSS class or id that no markup or script can produce. `--production` also lists what only tests reference. A deliberate keep goes in the script's `ALLOW` map with its reason |
|
||||
| Pre-push hook | Installed by `npm install` (`scripts/git-hooks.mjs`, via postinstall): runs the static CI checks (~10-40s) before `git push`. Skip once: `CODEMAN_SKIP_PREPUSH=1 git push`. Skips itself with a notice when HEAD is not the pushed commit or the tree has uncommitted changes the checks would read. Marker-owned, so a hand-written `pre-push` is never overwritten; installs ONLY into the repo's own `<git-common-dir>/hooks` (worktree-safe; a `core.hooksPath` elsewhere, e.g. a global one, is left alone) |
|
||||
| Production logs | `journalctl --user -u codeman-web -f` |
|
||||
| Detached server | `codeman web -d` (`--status`, `--stop`; pidfile+log at `dataPath('web.pid'/'web.log')`). ⚠ Refuses to start a 2nd server on one data dir — see Instance isolation |
|
||||
@@ -92,7 +94,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
- **ESM only** — Never `require()`, use `await import()`. `tsx` masks CJS/ESM issues in dev but production breaks
|
||||
- **Package ≠ product name** — npm: `aicodeman`, product: **Codeman**. Release renames tags accordingly. Both `aicodeman` and `codeman` bin aliases are installed (`package.json` `bin`)
|
||||
- **Global regex `lastIndex`** — Shared `g`-flag patterns in loops must reset `lastIndex = 0` first, or use the `execPattern()` helper in `utils/regex-patterns.ts` (resets automatically)
|
||||
- **`envOverrides` flow `CLAUDE_CODE_*` / `OPENCODE_*` / `CODEX_*` / `GEMINI_*` / `GOOGLE_*` / `ANTIGRAVITY_*` / `PI_*` / `GROK_*` / `XAI_*` / `DSH_*` / `DEEPSEEK_*` / `COPILOT_*` env vars, plus exact-key `CLAUDE_CONFIG_DIR`** — Set via `POST /api/sessions { envOverrides }`, stored on `Session._envOverrides`, exported by `tmux-manager.buildEnvExports()` at spawn time, persisted in `SessionState.envOverrides`. **Do NOT** write these to `<case>/.claude/settings.local.json` — that's the old path and creates UI/disk drift. (`GOOGLE_*` is the deliberately-broad Vertex-AI namespace for Gemini — see Multi-CLI prefix discipline.) `CLAUDE_CONFIG_DIR` (#255, exact match via `ALLOWED_ENV_KEYS` in `schemas.ts`) points a session at a separate Claude account/config dir for per-client subscriptions; it persists to state.json (a path, not a secret; losing it on restart would silently switch accounts). ⚠️ A relocated config dir writes transcripts outside `~/.claude/projects`, so the response viewer, subagent windows, ultracode panel and Read My Mind capture go blind for that session unless the user symlinks `projects` back into the shared tree (`ln -s ~/.claude/projects <configDir>/projects`). ⚠️ It is also one of claude's `privilegedEnvKeys` (Custom Model Endpoint Profiles, since it can redirect a session's traffic same as any other injected var), so in multi-user mode setting it via `envOverrides` is admin-only, and a non-granted owner's already-persisted `CLAUDE_CONFIG_DIR` is stripped on reboot-restore — silently returning that session to the default Claude account rather than the one it was pointed at (see `session-env-clamp.ts`). → [architecture-invariants#per-session-env-overrides-exact-key-allowlist-and-claude_config_dir](docs/architecture-invariants.md#per-session-env-overrides-exact-key-allowlist-and-claude_config_dir)
|
||||
- **`envOverrides` flow `CLAUDE_CODE_*` / `OPENCODE_*` / `CODEX_*` / `GEMINI_*` / `GOOGLE_*` / `ANTIGRAVITY_*` / `PI_*` / `GROK_*` / `XAI_*` / `DSH_*` / `DEEPSEEK_*` / `COPILOT_*` env vars, plus exact-key `CLAUDE_CONFIG_DIR`** — Set via `POST /api/sessions { envOverrides }`, stored on `Session._envOverrides`, exported by `tmux-manager.buildEnvExports()` at spawn time, persisted in `SessionState.envOverrides`. **Do NOT** write these to `<case>/.claude/settings.local.json` — that's the old path and creates UI/disk drift. (`GOOGLE_*` is the deliberately-broad Vertex-AI namespace for Gemini — see Multi-CLI prefix discipline.) `CLAUDE_CONFIG_DIR` (#255, exact match via `ALLOWED_ENV_KEYS` in `schemas.ts`) points a session at a separate Claude account/config dir for per-client subscriptions; it persists to state.json (a path, not a secret; losing it on restart would silently switch accounts). ⚠️ A relocated config dir writes transcripts outside `~/.claude/projects`, so subagent windows, the ultracode panel and Read My Mind capture go blind for that session unless the user symlinks `projects` back into the shared tree (`ln -s ~/.claude/projects <configDir>/projects`). The response viewer and the rename's `/resume` title read a LOCAL session's own folder, then the server's `CLAUDE_CONFIG_DIR`, then `~/.claude` (`claudeConversationDirs()` in session-routes.ts over `claudeProjectsDir()`, as the Edit history panel and the relaunch pin do, #701): a relocated folder is probed bounded first, and a missing one reads as no transcript, never as a reason to look under `~/.claude`. ⚠️ It is also one of claude's `privilegedEnvKeys` (Custom Model Endpoint Profiles, since it can redirect a session's traffic same as any other injected var), so in multi-user mode setting it via `envOverrides` is admin-only, and a non-granted owner's already-persisted `CLAUDE_CONFIG_DIR` is stripped on reboot-restore — silently returning that session to the default Claude account rather than the one it was pointed at (see `session-env-clamp.ts`). → [architecture-invariants#per-session-env-overrides-exact-key-allowlist-and-claude_config_dir](docs/architecture-invariants.md#per-session-env-overrides-exact-key-allowlist-and-claude_config_dir)
|
||||
- **Effort is NOT an env var** — never carry effort as `CLAUDE_CODE_EFFORT_LEVEL`: the env var hard-locks effort and blocks in-session `/effort` switching (incl. ultracode). It flows as the dedicated `effort` payload field → `Session._effort` → `claude --effort <level>` for regular levels incl. `max` (the settings `effortLevel` key is `enum(["low","medium","high","xhigh"]).catch(undefined)` — `max` gets SILENTLY dropped there), or `claude --settings '{"ultracode":true}'` for ultracode (rejected by `--effort`). Both are soft defaults the user can override anytime. Legacy env-var entries are auto-migrated by the Session constructor and unset from tmux sessions in `applyEnvOverrides()`. See `buildEffortCliArgs()` in `session-cli-builder.ts`, tests in `test/effort-injection.test.ts`
|
||||
- **The advisor rides `--settings`, NEVER the `--advisor` flag**: Claude Code's advisor tool (a stronger model consulted at decision points, code.claude.com/docs/en/advisor) flows as the `advisorModel` payload field → `Session._advisorModel` (persisted, so respawn and reboot restore keep it) → the `advisorModel` key in the launch's ONE `--settings` JSON, merged with ultracode and the statusLine exporter by `buildAdvisorSettings()` (`session-cli-builder.ts`). ⚠️ The flag EXITS at launch on any pairing the CLI refuses (`claude --advisor haiku` exits 1, so does Fable before its usage-credit consent), which would leave a dead pane on every respawn; the settings key degrades to "no advisor" instead. ⚠️ `isAdvisorModel()` (fable/opus/sonnet aliases or full ids, no haiku) is also the injection guard for the single-quoted argument. Soft default: `/advisor` still switches it in-session. App Settings key `claudeAdvisorModel` (SYNCED, `''` = leave it to the CLI). Remote/docker quick-start refuses it, like `effort`, and so does a remote attach on `POST /api/sessions`. Tests: `test/advisor-model.test.ts`
|
||||
- **Model choice: a persistent default in `settings.local.json`, a per-session `--model`, never env** — the App Settings **Claude Model** picker (`claudeModel` in `settings.json`) is read by `session-ui.js` at session create (wins over the legacy 1M-Opus toggles `opusContext1m`/`opusContext1mEnabled`), sent as the `modelOverride` payload field, and `updateCaseModel()` (`hooks-config.ts`) writes/deletes the `model` key in `<case>/.claude/settings.local.json`. This is the intended exception to the envOverrides rule above: model legitimately lives in `settings.local.json` (a soft default — in-session `/model` still works); env vars do not. A caller that wants one session on a model without touching the case sends `model` on `POST /api/sessions` instead: it goes out as `claude --model <id>`, writes nothing, wins over the app-wide default, and is persisted as `SessionState.model` so both recovery paths relaunch on it (`test/routes/session-routes-claude-model.test.ts`, `test/session-model-recovery.test.ts`). ⚠️ Claude only, via the `model.source` capability (`cliTakesSessionModel()`), never a mode check: refused for other CLIs and on a remote attach, and published by `toState()` for claude alone (cron hands its Claude default to every CLI with a model).
|
||||
@@ -194,7 +196,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
|
||||
⚠️ **llama-swap endpoints** (one model at a time): the apply routes check `GET /running` and return `requiresConfirmation` before evicting a model another live session uses; `confirmedSwap` and `confirmedContext` are SEPARATE flags and must stay so. Claude alone gets a context floor (`CLAUDE_MIN_SAFE_CONTEXT_TOKENS`); context is parsed from `/running`'s `cmd`, never trusted from `/props`. The floor also divides that context by the model's parallel slot count (`modelSlotCounts`: `--parallel`/`-np` from `cmd`, else `/props` `total_slots`; `perSlotContext()`), and `/props` only ever RAISES that warning: it supplies the context only when `cmd` states none and the count only when `cmd` has no `--parallel`, never a larger pool. `/props` is probed once per launch command (it refreshes llama-swap's last-use time, so a `ttl` would never expire), and a `/props` context beside an explicit `--parallel N` is already per slot, so it is not divided again. Backend log lines come from llama-swap's `/api/events` `upstream` source, never `/logs`. → [architecture-invariants#custom-model-endpoint-profiles](docs/architecture-invariants.md#custom-model-endpoint-profiles)
|
||||
|
||||
**Local model recommendation** (`GET /api/local-model`, `src/local-model/`, `src/config/local-model-catalog.ts`, `src/types/local-model.ts`; EXPERIMENTAL): the server looks at the Mac it runs on and says which local coding model fits it and with which agent CLI. ⚠️ The READ side stays read-only: the probe, the catalogue and `recommend()` download nothing, install nothing and write nothing; everything that changes the machine is the install below, behind an explicit request. Apple silicon macOS only: anywhere else the answer is a `200` with verdict `none` (reasons `not-macos`, `intel`, `memory`, `disk`, `macos`, `no-harness`), and a failed probe is an answer, never a 500. The probe (`hardware.ts`) is ONE bounded async spawn of `/usr/sbin/sysctl` WITHOUT `-n`, parsed as `key: value` lines by the pure `parseSysctl()`, plus `statfs` of the data dir (probed bounded first, #516) and `node:os` fallbacks, cached 60 s; ⚠️ never `system_profiler`, never a second spawn, and `iogpu.wired_limit_mb` of 0 means not set. The catalogue is a compiled constant validated by a Zod schema: ⚠️ no override file and no runtime data, and a model id is `name:tag` in lowercase with no slash (`LOCAL_MODEL_ID_PATTERN`, so an id can never name another registry host). ⚠️ A harness is a catalogue ROW (`{ cli, minContext, rank, gated?, slowFirstTurn? }`) plus a `HarnessFact` built from the CLI registry at call time (`harness-facts.ts`); no code compares a CLI id (both id-branching guards scan these files). `recommend()` (`recommend.ts`) is pure. ⚠️ A model's need is its PEAK (`bytes + heldBytesPerToken * context + overheadBytes + peakExtraBytes`, measured on a Mac for one row and marked `estimated` on the others), and every row names its `runner` (`mlx` or `llamacpp`, the build a Mac really pulls) and carries figures of its OWN: computed from its model's config.json by that runner's rule (catalogue header, MEMORY), never borrowed from another row; `test/local-model-catalog.test.ts` recomputes them, and the `llamacpp` rows assume the runtime's `OLLAMA_KV_CACHE_TYPE=q8_0`, `LLAMA_ARG_CACHE_RAM=1024` and `LLAMA_ARG_CTX_CHECKPOINTS=8` (`runtimeEnv()`) and count what llama-server keeps beside the cache (8 context checkpoints of the recurrent or sliding-window state, and for a GGUF with a prediction layer one rollback copy of the recurrent state per drafted token and that layer's cache in f16), so change the two together. The need is judged against a budget that is `estimated` until the runtime ran and `measured` from then on (`RecommendOptions.measuredTotalBytes`). ⚠️ Ranking, lexicographic: tested on a Mac like this first, then speed `ok` before `unknown` before `slow`, then model rank, harness rank, larger context; the fit grade decides whether a row is listed and what it says, it does NOT sort, so a model is offered at the largest context it fits at. ⚠️ The answer lists EVERY model that fits, and the install accepts only a listed row: `MAX_ALTERNATIVES` is a bound above the catalogue's size (`test/local-model-catalog.test.ts` fails for a catalogue that outgrows it), never a way to shorten the list. ⚠️ `limited` is a statement about the MAC (no model with 12 billion parameters or more fits), judged before the disk filter and whatever the pick is; a small pick under `ok` carries `noteSmallPick`, and a model left out for disk space is named in `noteDiskDropped`, never dropped in silence. ⚠️ The word "Recommended" exists only in `headlineTested`, and the tag "Tested on a Mac like this" only on a row whose model has a `tested` entry for exactly this chip, memory size and harness. ⚠️ Speed is `ok`/`slow`/`unknown`, graded on the unrounded figure, and a chip in no chips row is `unknown`: never guess a bandwidth. ⚠️ ONE unit for every computed size a person reads: decimal GB text from `formatGb()` (`format.ts`), sent beside the bytes, and the browser never divides bytes; the one exception is the installed memory, shown as `memClassGb` (the size the Mac is sold as, 48 and not 51.5). ⚠️ Every sentence the server chooses is a `LOCAL_MODEL_LABELS`, `LOCAL_MODEL_TAG_LABELS` or `LOCAL_MODEL_INSTALL_LABELS` text with `{placeholder}` slots filled from `vars` (no apostrophe in a text: the zh-CN key is single-quoted), and each needs a zh-CN entry. Admin only in multi-user mode (403 before anything is probed). Tests: `test/local-model-*.test.ts`, `test/routes/local-model-routes.test.ts`. Window rules: `src/web/CLAUDE.md` (Run a model on this Mac). → `docs/api-reference.md` (Local model), `docs/versioning-policy.md`
|
||||
**Local model recommendation** (`GET /api/local-model`, `src/local-model/`, `src/config/local-model-catalog.ts`, `src/types/local-model.ts`; EXPERIMENTAL): the server looks at the Mac it runs on and says which local coding model fits it and with which agent CLI. ⚠️ The READ side stays read-only: the probe, the catalogue and `recommend()` download nothing, install nothing and write nothing; everything that changes the machine is the install below, behind an explicit request. Apple silicon macOS only: anywhere else the answer is a `200` with verdict `none` (reasons `not-macos`, `intel`, `memory`, `disk`, `macos`, `no-harness`), and a failed probe is an answer, never a 500. The probe (`hardware.ts`) is ONE bounded async spawn of `/usr/sbin/sysctl` WITHOUT `-n`, parsed as `key: value` lines by the pure `parseSysctl()`, plus `statfs` of the data dir (probed bounded first, #516) and `node:os` fallbacks, cached 60 s; ⚠️ never `system_profiler`, never a second spawn, and `iogpu.wired_limit_mb` of 0 means not set. The catalogue is a compiled constant validated by a Zod schema: ⚠️ no override file and no runtime data, and a model id is `name:tag` in lowercase with no slash (`LOCAL_MODEL_ID_PATTERN`, so an id can never name another registry host). ⚠️ A harness is a catalogue ROW (`{ cli, minContext, rank, gated?, slowFirstTurn? }`) plus a `HarnessFact` built from the CLI registry at call time (`harness-facts.ts`); no code compares a CLI id (both id-branching guards scan these files). `recommend()` (`recommend.ts`) is pure. ⚠️ A model's need is its PEAK (`bytes + heldBytesPerToken * context + overheadBytes + peakExtraBytes`, measured on a Mac for two rows, the MLX builds of Qwen3.6 35B-A3B and Muse Glimmer 30B, and marked `estimated` on the others), and every row names its `runner` (`mlx` or `llamacpp`, the build a Mac really pulls) and carries figures of its OWN: computed from its model's config.json by that runner's rule (catalogue header, MEMORY), never borrowed from another row; `test/local-model-catalog.test.ts` recomputes them, and the `llamacpp` rows assume the runtime's `OLLAMA_KV_CACHE_TYPE=q8_0`, `LLAMA_ARG_CACHE_RAM=1024` and `LLAMA_ARG_CTX_CHECKPOINTS=8` (`runtimeEnv()`) and count what llama-server keeps beside the cache (8 context checkpoints of the recurrent or sliding-window state, and for a GGUF with a prediction layer one rollback copy of the recurrent state per drafted token and that layer's cache in f16), so change the two together. The need is judged against a budget that is `estimated` until the runtime ran and `measured` from then on (`RecommendOptions.measuredTotalBytes`). ⚠️ Ranking, lexicographic: tested on a Mac like this first, then speed `ok` before `unknown` before `slow`, then model rank, harness rank, larger context; the fit grade decides whether a row is listed and what it says, it does NOT sort, so a model is offered at the largest context it fits at. ⚠️ The answer lists EVERY model that fits, and the install accepts only a listed row: `MAX_ALTERNATIVES` is a bound above the catalogue's size (`test/local-model-catalog.test.ts` fails for a catalogue that outgrows it), never a way to shorten the list. ⚠️ `limited` is a statement about the MAC (no model with 12 billion parameters or more fits), judged before the disk filter and whatever the pick is; a small pick under `ok` carries `noteSmallPick`, and a model left out for disk space is named in `noteDiskDropped`, never dropped in silence. ⚠️ The word "Recommended" exists only in `headlineTested`, and the tag "Tested on a Mac like this" only on a row whose model has a `tested` entry for exactly this chip, memory size and harness. ⚠️ Speed is `ok`/`slow`/`unknown`, graded on the unrounded figure, and a chip in no chips row is `unknown`: never guess a bandwidth. ⚠️ ONE unit for every computed size a person reads: decimal GB text from `formatGb()` (`format.ts`), sent beside the bytes, and the browser never divides bytes; the one exception is the installed memory, shown as `memClassGb` (the size the Mac is sold as, 48 and not 51.5). ⚠️ Every sentence the server chooses is a `LOCAL_MODEL_LABELS`, `LOCAL_MODEL_TAG_LABELS` or `LOCAL_MODEL_INSTALL_LABELS` text with `{placeholder}` slots filled from `vars` (no apostrophe in a text: the zh-CN key is single-quoted), and each needs a zh-CN entry. Admin only in multi-user mode (403 before anything is probed). Tests: `test/local-model-*.test.ts`, `test/routes/local-model-routes.test.ts`. Window rules: `src/web/CLAUDE.md` (Run a model on this Mac). → `docs/api-reference.md` (Local model), `docs/versioning-policy.md`
|
||||
|
||||
**Local model install** (`POST /api/local-model/install|use|cancel|resume|runtime|agent`, `DELETE /api/local-model`, `DELETE /api/local-model/models`; `src/local-model/{install-job,runtime,ollama-client,connect,state-store,paths,developer-tools}.ts`; EXPERIMENTAL, admin only in multi-user mode on EVERY verb; guide `docs/local-models.md`): installs the chosen model on the Mac the server runs on and ends on a session of the coding agent running on it. ONE job of five idempotent steps (`runtime`, `model`, `verify`, `agent`, `connect`; `agent` only when the coding agent is missing), a pure reducer (`reduceInstallJob()`) over three tables in `install-job.ts` driven by one service per process (`getLocalModelService()`); the window polls the GET once a second, no SSE event. ⚠️ A LIBRARY with ONE model in use: the store may hold several models and `LocalModelStateFile.library` lists the ones that passed the check (written by the service when `verify` passes, carried by the reducer, dropped by `remove`; an `installed` file without it counts its one model, `libraryOf()`), but the endpoint record lists ONE model, the runtime holds one and only the state's model is ever launched: never widen the record to every checked model. `install` from `installed` adds a model (the earlier one stays: `replacedModelFor()` never names a library model), `use` switches to a checked one (a job of `USE_JOB_STEPS`, `verify` then `connect`; the stored digest is compared before anything is loaded, else `model-changed`), and both answer 409 `sessions-open` while a live session uses the endpoint; until such a job ends `installed`, no session starts (`launchRefusal()` answers `job-unfinished`). `DELETE /api/local-model/models` deletes ONE model by its NAME (`LOCAL_MODEL_ID_PATTERN`, never a path), only a name of the server's own listing, only through the runtime's own delete, never the model of the installation or of the current job (409 `model-active`), and it is no reducer event: its row is the `delete-model` action of `INSTALL_STATE_TABLE`. ⚠️ The view's `library` (state entries joined with the runtime's `/api/tags`: `ready`, `changed`, `missing`, `unverified`) and `store` (the blob folder's size, `measureModelStore()`) are cached (5 s, 30 s), refreshed in the background and thrown away by every verb and step that changes them (`forgetStore()`): never ask the runtime or the disk on the one-second poll, and a runtime that does not answer keeps the last list. ⚠️ Layout only through `localModelPaths()` (all `dataPath()`): `local-model/runtime/ollama-<version>/`, `local-model/models/`, `local-model/home/` (the runtime's PRIVATE HOME, so the user's `~/.ollama` is never touched) and the state file `local-model.json` (0600, ONE serialized writer, total reader, holds NO path); nothing is written or deleted outside `local-model/` except that file and the two writes of the connect step. ⚠️ The runtime pin (`OLLAMA_RUNTIME_PIN`: version, URL, size, sha256) is a COMPILED constant no file, setting or request may supply; the hash is compared BEFORE anything is unpacked. ⚠️ The runtime is a NON-detached child whose environment comes from the `runtimeEnv()` ALLOWLIST, never `process.env` (no `CODEMAN_*`, none of the user's `OLLAMA_*`); the port is chosen ONCE by binding (from 11435, never 11434) and stored; a listener on it is adopted or replaced only when its stored pid runs a binary under OUR runtime folder, anything else is `port-in-use`; started at boot when installed and enabled, max 3 restarts, SIGTERM at shutdown beside `stopDeepSeekWeb()`; under vitest nothing spawns or fetches. ⚠️ Consent is bound to the size: `acknowledgedBytes` must equal the server's own total (`Candidate.installBytes`) or the answer is 409 `size-changed`; the model, context and CLI must be a row the current recommendation offers (400). ⚠️ ONE job at a time (409 `job-running`); a job a restart interrupted comes back `paused` and NEVER continues without a click (so `shutdown()` writes nothing), and an interrupted step is never recorded as failed. ⚠️ An event the transition table does not list is refused (same object back, 409 `wrong-state`): add a row to the table, never a special case. ⚠️ The budget is MEASURED from the runtime's "inference compute" log line and the model judged against it BEFORE it is downloaded. ⚠️ The pull stream is parsed incrementally (about 1.4 million lines for 23 GB): never buffer it, never write state per line. ⚠️ A failure is a code with ONE next step (`LOCAL_MODEL_ERROR_NEXT`), never a bare "failed"; a probe that ended on its token limit is `probe-unfinished`, not `no-tool-call`. ⚠️ The coding agent is installed through the shared runner `src/cli-install-runner.ts` (extracted from `cli-registry-routes.ts`, ONE install slot per CLI for both callers) with `stockInstallCommand()`, the COMPILED stock command, never the `clis.json`-merged one (this path has no `cliManagementEnabled` gate); only for a catalLine truncated
|
||||
|
||||
|
||||
+16
-13
@@ -1,16 +1,19 @@
|
||||
{
|
||||
"$schema": "https://unpkg.com/knip@5/schema.json",
|
||||
"entry": [
|
||||
"scripts/*.mjs",
|
||||
"scripts/*.js",
|
||||
"scripts/watch-subagents.ts",
|
||||
"scripts/remotion/Root.tsx",
|
||||
"scripts/remotion/index.ts",
|
||||
"test/**/*.test.ts",
|
||||
"test/mobile/vitest.config.ts",
|
||||
"test/**/*.mjs"
|
||||
],
|
||||
"project": ["src/**/*.{ts,tsx}", "scripts/**/*.{ts,tsx,mjs,js}", "test/**/*.{ts,mjs}"],
|
||||
"$schema": "https://unpkg.com/knip@6/schema.json",
|
||||
"workspaces": {
|
||||
".": {
|
||||
"entry": [
|
||||
"scripts/*.{mjs,js,mts,ts}",
|
||||
"scripts/dev/*.mjs",
|
||||
"scripts/remotion/Root.tsx",
|
||||
"scripts/remotion/index.ts",
|
||||
"test/**/*.test.ts"
|
||||
],
|
||||
"project": ["src/**/*.{ts,tsx}", "scripts/**/*.{ts,tsx,mjs,js,mts}", "!scripts/remotion/**", "test/**/*.{ts,mjs}"]
|
||||
}
|
||||
},
|
||||
"ignoreExportsUsedInFile": true,
|
||||
"ignoreDependencies": ["@remotion/cli", "@remotion/transitions", "esbuild", "agent-browser"]
|
||||
"ignoreDependencies": ["@remotion/cli", "@remotion/transitions"],
|
||||
"ignoreBinaries": ["ffprobe", "ffmpeg", "wslpath", "vm_stat", "jq", "codex", "script", "mkfifo"],
|
||||
"tags": ["-knipignore"]
|
||||
}
|
||||
@@ -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',
|
||||
|
||||
@@ -41,7 +41,7 @@ Pure helpers unit-tested in `test/base-path.test.ts` + `test/webview-proxy.test.
|
||||
|
||||
### External CLI modes (OpenCode, Codex, Gemini, Antigravity, Pi, Grok, DeepSeek, OMP)
|
||||
|
||||
**External CLI modes (OpenCode, Codex, Gemini, Antigravity, Pi, Grok, DeepSeek, OMP, Copilot, jcode)**: `isExternalCliMode()` in `session.ts` (`mode === 'opencode' || 'codex' || 'gemini' || 'antigravity' || 'pi' || 'grok' || 'deepseek'`) gates Claude-specific behavior — Ralph tracker, BashToolParser, token/CLI-info parsing, and ❯-prompt readiness detection are all skipped (these CLIs render their own TUIs; readiness = output stabilization instead). ⚠️ **Work detection left this gate in #385** and is now per-CLI `capabilities.workDetect` data (`promptGlyph` + `workingLine`), because gating it on the mode left every Codex session reporting `idle` for its entire life; a CLI declaring neither falls back to Claude's pair, which is logic-identical to the pre-registry behaviour. All seven modes **require tmux — no direct PTY fallback** — because secrets are injected via `tmux setenv` (socket-scoped `${this.tmux()} setenv`, never on the spawn command line): OpenCode gets `OPENCODE_CONFIG_CONTENT` etc., Codex gets `OPENAI_API_KEY`/`CODEX_API_KEY`/`CODEX_HOME` (`setCodexEnvVars`), Gemini gets `GEMINI_API_KEY`/`GOOGLE_API_KEY`/`GOOGLE_CLOUD_PROJECT`/`GOOGLE_APPLICATION_CREDENTIALS`/`GOOGLE_GENAI_USE_VERTEXAI` etc. (`setGeminiEnvVars`, all in `tmux-manager.ts`). Codex specifics: command built by `buildCodexCommand()` (`--no-daemon` behind the `noDaemonFlag` gate at 0.162.0, measured against codex's own version, local launches only; `--model`, `--config model_reasoning_effort=<level>` from `reasoningEffort`, `--config sandbox_workspace_write.network_access=true` from `networkAccess` (the **Allow network access** app setting `codexNetworkAccess`, a launch default and a privileged param; ⚠️ with it on, a command in codex's sandbox can call Codeman's API and start a session outside that sandbox, password or not), `--config tui.animations=<bool>` from `animations`, `resume <id>`, `--dangerously-bypass-approvals-and-sandbox` from the `codexConfig` payload / `codexDangerouslyBypassApprovals` app setting; `renderMode` is schema-coerced to `'hybrid'`, the only supported mode). Gemini specifics: command built by `buildGeminiCommand()` (`--skip-trust` always, `--approval-mode <default|auto_edit|yolo|plan>` defaulting to `yolo` for parity with Claude's `--dangerously-skip-permissions`, `--model`, `--resume` from the `geminiConfig` payload); availability via `GET /api/gemini/status` — session/quick-start routes fail with `OPERATION_FAILED` + install hint (`npm install -g @google/gemini-cli`) when missing. Codex, Gemini, Antigravity, Pi, Grok, DeepSeek and OMP export `COLORTERM=truecolor` and unset `NO_COLOR`; `opencode` unsets `COLORTERM`. **Terminal colour env** under Session launch modes covers Claude and says which panes those declarations actually reach. Gemini joins `isAltScreenStripMode()` (Codex/Claude/Gemini are Ink TUIs that repaint inline → strip alt-screen/`3J` so scrollback survives). Codex availability via `GET /api/codex/status`. Antigravity specifics: command built by `buildAntigravityCommand()` (`--model`, `--conversation <id>` resume, `--dangerously-skip-permissions` from the `antigravityConfig` payload); availability via `GET /api/antigravity/status` — routes fail with `OPERATION_FAILED` + install hint (`curl -fsSL https://antigravity.google/cli/install.sh | bash`) when missing. Unlike the other three it is NOT an npm package (standalone binary, `~/.local/bin/agy`), which is why `docker/agent.Dockerfile` installs it with its own `--dir /usr/local/bin` step rather than in the `npm install -g` line, and why it does NOT join `isAltScreenStripMode()`. Frontend: run-mode dropdown → `runCodex()`/`runGemini()` in `session-ui.js` ("Run CX"/"Run GM" labels), App Settings → Agents & CLIs → Codex; Respawn/Ralph options are Claude-only, so session options open on the Session tab for external CLI sessions. ⚠️ `run*()` MUST unwrap the `{success,data}` envelope (`(await res.json()).data.available` / `data.data.sessionId`) — reading the raw shape silently breaks the run. Tests: `test/run-mode-ui.test.ts` + `test/gemini-mode.test.ts` (vm-sandbox harness, no real DOM). Grok specifics: command built by `buildGrokCommand()` (`--always-approve` from `grokConfig.alwaysApprove` — grok's `bypassPermissions` permission mode, deny rules still apply; `--model`; `--resume <id>` / `--continue`, id-regexed so grok's resume-by-TITLE feature can never put an arbitrary string on the spawn line); availability via `GET /api/grok/status`, which carries `version` because the resolver version-probes candidates (`grok` has npm squatters, e.g. @vibe-kit/grok-cli — `GROK_VERSION_REGEX` is shared with the dependency registry so doctor and run mode agree). Like antigravity it is a standalone binary (xAI installer → `~/.grok/bin`, symlinked into `~/.local/bin`), so `docker/agent.Dockerfile` installs it in its own step (copy to `/usr/local/bin`, drop root's `~/.grok` in the same layer) and it stays OUT of `isAltScreenLine truncated
|
||||
**External CLI modes (OpenCode, Codex, Gemini, Antigravity, Pi, Grok, DeepSeek, OMP, Copilot, jcode)**: `isExternalCliMode()` in `session.ts` (`mode === 'opencode' || 'codex' || 'gemini' || 'antigravity' || 'pi' || 'grok' || 'deepseek'`) gates Claude-specific behavior — Ralph tracker, BashToolParser, token/CLI-info parsing, and ❯-prompt readiness detection are all skipped (these CLIs render their own TUIs; readiness = output stabilization instead). ⚠️ **Work detection left this gate in #385** and is now per-CLI `capabilities.workDetect` data (`promptGlyph` + `workingLine`), because gating it on the mode left every Codex session reporting `idle` for its entire life; a CLI declaring neither falls back to Claude's pair, which is logic-identical to the pre-registry behaviour. All seven modes **require tmux — no direct PTY fallback** — because secrets are injected via `tmux setenv` (socket-scoped `${this.tmux()} setenv`, never on the spawn command line): OpenCode gets `OPENCODE_CONFIG_CONTENT` etc., Codex gets `OPENAI_API_KEY`/`CODEX_API_KEY`/`CODEX_HOME` (`setCodexEnvVars`), Gemini gets `GEMINI_API_KEY`/`GOOGLE_API_KEY`/`GOOGLE_CLOUD_PROJECT`/`GOOGLE_APPLICATION_CREDENTIALS`/`GOOGLE_GENAI_USE_VERTEXAI` etc. (`setGeminiEnvVars`, all in `tmux-manager.ts`). Codex specifics: command built by `buildCodexCommand()` (`--no-daemon` behind the `noDaemonFlag` gate at 0.162.0, measured against codex's own version, local launches only; `--model`, `--config model_reasoning_effort=<level>` from `reasoningEffort`, `--config sandbox_workspace_write.network_access=true` from `networkAccess` (the **Allow network access** app setting `codexNetworkAccess`, a launch default and a privileged param; ⚠️ with it on, a command in codex's sandbox can call Codeman's API and start a session outside that sandbox, password or not), `--config tui.animations=<bool>` from `animations`, `resume <id>`, `--dangerously-bypass-approvals-and-sandbox` from the `codexConfig` payload / `codexDangerouslyBypassApprovals` app setting; `renderMode` is schema-coerced to `'hybrid'`, the only supported mode). Gemini specifics: command built by `buildGeminiCommand()` (`--skip-trust` always, `--approval-mode <default|auto_edit|yolo|plan>` defaulting to `yolo` for parity with Claude's `--dangerously-skip-permissions`, `--model`, `--resume` from the `geminiConfig` payload); availability via `GET /api/gemini/status` — session/quick-start routes fail with `OPERATION_FAILED` + install hint (`npm install -g @google/gemini-cli`) when missing. Codex, Gemini, Antigravity, Pi, Grok, DeepSeek and OMP export `COLORTERM=truecolor` and unset `NO_COLOR`; `opencode` unsets `COLORTERM`. **Terminal colour env** under Session launch modes covers Claude and says which panes those declarations actually reach. Gemini joins `isAltScreenStripMode()` (Codex/Claude/Gemini are Ink TUIs that repaint inline → strip alt-screen/`3J` so scrollback survives). Codex availability via `GET /api/codex/status`. Antigravity specifics: command built by `buildAntigravityCommand()` (`--model`, `--conversation <id>` resume, `--dangerously-skip-permissions` from the `antigravityConfig` payload); availability via `GET /api/antigravity/status` — routes fail with `OPERATION_FAILED` + install hint (`curl -fsSL https://antigravity.google/cli/install.sh | bash`) when missing. Unlike the other three it is NOT an npm package (standalone binary, `~/.local/bin/agy`), which is why `docker/agent.Dockerfile` installs it with its own `--dir /usr/local/bin` step rather than in the `npm install -g` line, and why it does NOT join `isAltScreenStripMode()`. Frontend: run-mode dropdown → `run()` → the shared `_runCliMode(mode)` in `session-ui.js` ("Run CX"/"Run GM" labels), App Settings → Agents & CLIs → Codex; Respawn/Ralph options are Claude-only, so session options open on the Session tab for external CLI sessions. ⚠️ `run*()` MUST unwrap the `{success,data}` envelope (`(await res.json()).data.available` / `data.data.sessionId`) — reading the raw shape silently breaks the run. Tests: `test/run-mode-ui.test.ts` + `test/gemini-mode.test.ts` (vm-sandbox harness, no real DOM). Grok specifics: command built by `buildGrokCommand()` (`--always-approve` from `grokConfig.alwaysApprove` — grok's `bypassPermissions` permission mode, deny rules still apply; `--model`; `--resume <id>` / `--continue`, id-regexed so grok's resume-by-TITLE feature can never put an arbitrary string on the spawn line); availability via `GET /api/grok/status`, which carries `version` because the resolver version-probes candidates (`grok` has npm squatters, e.g. @vibe-kit/grok-cli — `GROK_VERSION_REGEX` is shared with the dependency registry so doctor and run mode agree). Like antigravity it is a standalone binary (xAI installer → `~/.grok/bin`, symlinked into `~/.local/bin`), so `docker/agent.Dockerfile` installs it in its own step (copy to `/usr/local/bin`, drop root's `~/.grok` in the same layer) and it stays OUTLine truncated
|
||||
|
||||
**DeepSeek Harness (`dsh`) specifics** — the mode that breaks three of the assumptions the six above share, so read this before changing anything about it.
|
||||
|
||||
@@ -149,7 +149,7 @@ Spawn commands are pinned as literal strings in `test/cli-registry-spawn-golden.
|
||||
|
||||
### Per-session env overrides: exact-key allowlist and CLAUDE_CONFIG_DIR
|
||||
|
||||
**The env allowlist has two tiers, and exceptions go in the exact-key tier, never a widened prefix** (#255): `ALLOWED_ENV_PREFIXES` in `src/web/schemas.ts` carries the CLI-namespace prefixes, and `ALLOWED_ENV_KEYS` carries exact keys (currently only `CLAUDE_CONFIG_DIR`). `CLAUDE_CONFIG_DIR` relocates the Claude CLI's user config (credentials, settings, stats), which is how one machine runs sessions on separate Claude subscriptions: point a case's sessions at e.g. `~/.claude-clients/acme` via `envOverrides` and run `/login` there once against the client's account. The exact match matters: `CLAUDE_` as a prefix would open every future Claude CLI variable unreviewed, and near-misses (`CLAUDE_CONFIG_DIR_EXTRA`) stay rejected (`test/env-overrides-schema.test.ts`). No new security boundary is crossed: sessions already run as the server's OS account, and `applyEnvOverrides()` shellescapes values into socket-scoped `tmux setenv`. Two carry rules: **(1)** the key must survive `getEnvOverridesForPersist()` in `session.ts` (it is a path, not a secret; dropping it from state.json would silently move a rebuilt-after-reboot session back to the default account); **(2)** ⚠️ a relocated config dir writes transcripts outside `homedir()/.claude/projects`, which `subagent-watcher.ts`, `workflow-run-watcher.ts`, the response-viewer routes and Read My Mind capture all hardcode — those surfaces go blind for such a session. Documented workaround: symlink the transcripts back into the shared tree (`ln -s ~/.claude/projects <configDir>/projects`), keeping credentials separate while the watchers keep working.
|
||||
**The env allowlist has two tiers, and exceptions go in the exact-key tier, never a widened prefix** (#255): `ALLOWED_ENV_PREFIXES` in `src/web/schemas.ts` carries the CLI-namespace prefixes, and `ALLOWED_ENV_KEYS` carries exact keys (currently only `CLAUDE_CONFIG_DIR`). `CLAUDE_CONFIG_DIR` relocates the Claude CLI's user config (credentials, settings, stats), which is how one machine runs sessions on separate Claude subscriptions: point a case's sessions at e.g. `~/.claude-clients/acme` via `envOverrides` and run `/login` there once against the client's account. The exact match matters: `CLAUDE_` as a prefix would open every future Claude CLI variable unreviewed, and near-misses (`CLAUDE_CONFIG_DIR_EXTRA`) stay rejected (`test/env-overrides-schema.test.ts`). No new security boundary is crossed: sessions already run as the server's OS account, and `applyEnvOverrides()` shellescapes values into socket-scoped `tmux setenv`. Two carry rules: **(1)** the key must survive `getEnvOverridesForPersist()` in `session.ts` (it is a path, not a secret; dropping it from state.json would silently move a rebuilt-after-reboot session back to the default account); **(2)** ⚠️ a relocated config dir writes transcripts outside `homedir()/.claude/projects`, which `subagent-watcher.ts`, `workflow-run-watcher.ts` and Read My Mind capture all hardcode: those surfaces go blind for such a session. Documented workaround: symlink the transcripts back into the shared tree (`ln -s ~/.claude/projects <configDir>/projects`), keeping credentials separate while the watchers keep working. The response viewer is no longer one of them (#701): `claudeConversationDirs()` in `session-routes.ts` gives `lastResponseFor` (the viewer, `codeman agent read`, the Discord bridge's last message) and the rename's `/resume` title the folder the session's claude really writes to, `<config dir>/projects` and `<config dir>/history.jsonl`, resolved by `claudeProjectsDir()` like the relaunch pin and the Edit history panel: the session's own override, then the server's `CLAUDE_CONFIG_DIR` (a pane inherits it through tmux), then `~/.claude`. ⚠️ Only a LOCAL session reads its override: in a Docker case or on a remote host the value names a folder over there. ⚠️ A relocated folder is a user-chosen path, so it is probed bounded first (#516), and anything but a directory reads as "no transcript": never fall back to `~/.claude`, where a file of the same name is another account's conversation. The default folder is not probed, so that path is unchanged. Tests: `test/routes/session-routes-claude-last-response.test.ts` (relocated folder block), `test/routes/session-name-routes.test.ts`.
|
||||
|
||||
⚠️ **As of the custom-model endpoint feature, `CLAUDE_CONFIG_DIR` is ALSO admin-only in multi-user mode**, which is a change to the above rather than a restatement of it. It joined claude's `privilegedEnvKeys` (`stock.ts`) alongside `CLAUDE_CODE_MAX_CONTEXT_TOKENS`, because the rule that every traffic-redirecting var that feature can inject must be listed there is worth keeping literally true. `privilegedEnvKeys` has exactly one consumer, `ownerClampedEnvKeys()` in `src/session-env-clamp.ts`, which feeds the generic `envOverrides` clamp on `POST /api/sessions`, `POST /api/quick-start` and reboot-restore. So for a non-granted owner two things now follow: the key cannot be set through `envOverrides` at all, and an ALREADY-PERSISTED one is stripped on reboot-restore, which silently moves that session back to the default Claude account. That second consequence is the one to watch, since it turns a working per-client setup into a wrong-account one across a host reboot with no error anywhere. `session-env-clamp.ts`'s own fileoverview used to state the opposite invariant (that claude's privileged keys are the five `ANTHROPIC_*` names, so a persisted record cannot carry a clamped key) and was corrected when this landed; a claude clamp test now pins the behaviour next to the deepseek and omp ones.
|
||||
|
||||
@@ -1123,7 +1123,7 @@ Tests: `test/tab-rail-search.test.ts` (gate) and `test/tab-rail-search.browser.t
|
||||
|
||||
**Adding a skin means touching four places, and each one fails silently on its own**: (1) the `html[data-skin="…"]` token block in `styles.css`; (2) the xterm ANSI palette in `CODEMAN_XTERM_THEMES` (terminal-ui.js) — a missing entry falls back to `daylight-blue`, so the terminal simply stays the wrong color; (3) the pre-paint allowlist array in `index.html` — a skin missing there is coerced to `daylight-blue` on every reload, which reads as "my theme keeps resetting"; (4) the `<select>` in App Settings → Appearance → Theme. `test/skin-themes.test.ts` is the static four-way guard.
|
||||
|
||||
**Light skins carry three extra obligations.** `color-scheme: light` on the `html[data-skin]` block, or the UA renders native `<select>` popups, date pickers and scrollbars as dark widgets on a light page. xterm `minimumContrastRatio: 4.5` (set at construction in terminal-ui.js **and** panels-ui.js for teammate terminals, and re-applied in `applyTerminalSkin()`), because CLIs emit colors chosen for dark backgrounds; dark skins keep `1` to avoid the per-cell contrast work. And `applyTerminalSkin()` must call `this._localEchoOverlay?.refreshFont()` — the zero-lag overlay **caches** the terminal fg/bg at construction, so without the refresh typed-but-not-yet-flushed text keeps the previous theme's dark backing after a live skin switch.
|
||||
**Light skins carry three extra obligations.** `color-scheme: light` on the `html[data-skin]` block, or the UA renders native `<select>` popups, date pickers and scrollbars as dark widgets on a light page. xterm `minimumContrastRatio: 4.5` (set at construction in terminal-ui.js **and** terminal-tile.js, and re-applied in `applyTerminalSkin()`), because CLIs emit colors chosen for dark backgrounds; dark skins keep `1` to avoid the per-cell contrast work. And `applyTerminalSkin()` must call `this._localEchoOverlay?.refreshFont()` — the zero-lag overlay **caches** the terminal fg/bg at construction, so without the refresh typed-but-not-yet-flushed text keeps the previous theme's dark backing after a live skin switch.
|
||||
|
||||
**Shared surface tokens, not literals.** Elevated/floating surfaces resolve through `--floating-bg`, `--control-bg{,-hover}`, `--control-border{,-hover}`, `--banner-bg-a/b`, `--modal-backdrop` and `--elevated-shadow`, so modals, the command palette, dropdowns, subagent/ultracode windows, file previews and the mobile sheets follow the skin instead of hardcoded near-black rgba. ⚠️ Every skin that wants its own elevated look must override these — a skin that omits `--floating-bg` silently inherits the `:root` value, which is how the OG skin's near-black modals drifted slate. `styles.css` also defines **compatibility aliases** (`--bg-primary/secondary/tertiary`, `--text-primary/secondary`, `--border-color`, `--accent-color`, `--success`, `--error`, `--danger`, `--font-mono`, `--shadow-lg`) that forward to the canonical tokens; panels written against those names previously resolved to *nothing* (invalid at computed-value time), so the aliases are load-bearing, not cosmetic.
|
||||
|
||||
@@ -1255,7 +1255,7 @@ The age stamps are refreshed **in place** by a 20s clock (`_tickHomeSessionsTime
|
||||
|
||||
⚠️ **The `@font-face` descriptor, not the file, is what the browser synthesizes from**: `fonts/jetbrains-mono-variable.woff2` carries a `wght` axis of 100-800, and while `styles.css` declared it `400 700` every weight below 400 rendered identically to 400 and 800 identically to 700 — measured — so the setting was a no-op for anyone without Fira Code or Cascadia Code installed, which is most installs. It is declared `100 800`; re-narrowing it silently guts the feature (`test/terminal-font-weight.test.ts` pins the range).
|
||||
|
||||
⚠️ A live save must reach **both echo overlays** (`refreshFont()` — they cache `terminal.options.fontWeight` and paint it into their spans, so typed characters otherwise keep the old weight, most visible on a phone) **and open Agent Teams panes** (they read their options at construction, exactly like `applyTerminalSkin()` propagates).
|
||||
⚠️ A live save must reach **both echo overlays** (`refreshFont()` — they cache `terminal.options.fontWeight` and paint it into their spans, so typed characters otherwise keep the old weight, most visible on a phone) **and every open tile and split pane** (`_forEachTile`: they read their options at construction, exactly like `applyTerminalSkin()` propagates).
|
||||
|
||||
⚠️ `_awaitTerminalFont()` is deliberately untouched: `CharSizeService` measures through the CSS `font` shorthand, which RESETS the weight, so the measured face is always the 400 one and a weighted descriptor would ask for nothing new.
|
||||
|
||||
@@ -1321,7 +1321,7 @@ Tests: `test/mobile-prompt-composer.test.ts` (in the CI gate, deliberately not u
|
||||
|
||||
### PTY and browser terminal geometry
|
||||
|
||||
**The PTY and the browser terminal must never disagree about size** (issue #464, `syncTerminalGeometry()` in terminal-ui.js): Claude Code's TUI wraps its frame at the width the PTY reported and erases the previous frame by walking the cursor up the number of rows it BELIEVES that frame occupied. A browser terminal of a different width makes each logical line take more physical rows than Ink counted, so `eraseLines(n)` clears too few and the new frame paints over rows nothing erased — the doubled lines and half-overwritten prose in #464, **measured** against this repo's xterm (a 120-column PTY against a 62-column terminal renders every wrapped line twice; `test/terminal-pty-geometry.test.ts` pins it, and pins the clean render at matching widths so the assertion cannot pass against code that fixes nothing). ⚠️ **`fitAddon.fit()` is NOT the way to resize this terminal.** It resizes xterm to `proposeDimensions()` RAW while every server-facing path reports those floored at 40x10, so whenever the floor bit the two diverged silently — **measured in Chrome at 430px**: font size 44 proposed 13 columns, the server was told 40, and xterm stayed at 13. `syncTerminalGeometry()` fits, floors and applies as one step and is the ONE function that may change the size; `test/terminal-pty-geometry.test.ts` sweeps the seven modules that touch the main terminal (terminal-ui, mobile-handlers, app, ralph-panel, settings-ui, tab-rail-resize, notification-manager) for a bare fit; the split pane and teammate terminals own their own sizing and are out of scope. ⚠️ **Withhold the fit wherever you withhold the SIGWINCH.** `throttledResize` (virtual keyboard up) and `sendResize` (session detached into its own window) used to reflow locally and skip only the server write, which is the one combination that cannot be right. ⚠️ **A font change is a geometry change**: `setFontSize`/`setFontFamily`/`setFontWeight` move the cell size and told the server nothing, so raising the font on a phone left the CLI wrapping at the old column count (`_refitAfterCellSizeChange`). ⚠️ **Resize is no longer write-only.** `Session.resize` DECLINES a small-viewport request while a desktop connection holds an active sizing claim and says nothing, so both transports now answer with `Session.ptyGeometry` (`{"t":"zc"}` on the socket, the body of the resize POST) and `_onPtyGeometryReport` adopts it — a terminal that keeps a WIDTH the PTY refused renders GARBLED, not merely wrong-sized. ⚠️ While that refusal stands (`_paneWidthRefused`), a resize ASKS for the container's width without applying it (`_geometryForResizeRequest`: rows follow the container, columns stay at the PTY's): fitting first re-wrapped the whole buffer to the container and back on every 30s mobile retry, and ran the scrollback clear for a resize that brings no redraw. `selectSession` clears the flag, since it belongs to the previous pane. ⚠️ **`ptyGeometry` is null without a live pane**, never the field values: they are seeded at spawn (`_notePtySpawnGeometry`, so a reattached pane reports its tmux window's real size) and moved by `resize()`, but a dead-pane session still holds the constructor defaults of 120x40 or a gone pane's size — reporting those made a client adopt a size no process was ever told and claim another device owned the pane when none existed. ⚠️ **COLUMNS ONLY** (one documented exception, the keyboard row hold in the next paragraph). Adopting the PTY's ROWS was a regression: a phone taking a desktop's 43 rows into a viewport with room for 18 painted an `.xterm-screen` far taller than its container, xterm's own viewport then had nothing to scroll, and the CLI's input line sat below the container with no gesture able to reach it — output visible, typing invisible, for as long as the claim stayed hot. Width is the axis the wrap arithmetic depends on; rows only decide how much is on screen, and keeping the local count keeps the composer at the bottom of a viewport that scrolls. ⚠️ **`.term-overflows-x` keys on what does not FIT, not on a PTY mismatch**, because the 40-column floor widens the terminal past a narrow container with the PTY agreeing throughout (measured at 360px: font 18 paints 433px, font 24 paints 578px — 38% unreachable, and `increaseFontSize` reaches 24 in two taps). `_syncTerminalOverflowAffordance()` MEASURES `.xterm-screen` against the container on the next frame rather than deriving it from cell arithmetic. ⚠️ That rule sets **both** overflow axes — mobile.css loads later with `.terminal-container { overflow: visible }`, and a bare `overflow-x` would leave overflow-y computing to `auto`, handing the browser a vertical scroll container the terminal's touch handler does not know about — and sets **no `touch-action`**: the terminal's own touchmove handler pans it (`canPanHorizontally`), because `touchstart` preventDefault()s every 'content' tap and that cancels a native `pan-x` before it starts (measured: a 140px Line truncated
|
||||
**The PTY and the browser terminal must never disagree about size** (issue #464, `syncTerminalGeometry()` in terminal-ui.js): Claude Code's TUI wraps its frame at the width the PTY reported and erases the previous frame by walking the cursor up the number of rows it BELIEVES that frame occupied. A browser terminal of a different width makes each logical line take more physical rows than Ink counted, so `eraseLines(n)` clears too few and the new frame paints over rows nothing erased — the doubled lines and half-overwritten prose in #464, **measured** against this repo's xterm (a 120-column PTY against a 62-column terminal renders every wrapped line twice; `test/terminal-pty-geometry.test.ts` pins it, and pins the clean render at matching widths so the assertion cannot pass against code that fixes nothing). ⚠️ **`fitAddon.fit()` is NOT the way to resize this terminal.** It resizes xterm to `proposeDimensions()` RAW while every server-facing path reports those floored at 40x10, so whenever the floor bit the two diverged silently — **measured in Chrome at 430px**: font size 44 proposed 13 columns, the server was told 40, and xterm stayed at 13. `syncTerminalGeometry()` fits, floors and applies as one step and is the ONE function that may change the size; `test/terminal-pty-geometry.test.ts` sweeps the seven modules that touch the main terminal (terminal-ui, mobile-handlers, app, ralph-panel, settings-ui, tab-rail-resize, notification-manager) for a bare fit; the split pane and the tiles own their own sizing and are out of scope. ⚠️ **Withhold the fit wherever you withhold the SIGWINCH.** `throttledResize` (virtual keyboard up) and `sendResize` (session detached into its own window) used to reflow locally and skip only the server write, which is the one combination that cannot be right. ⚠️ **A font change is a geometry change**: `setFontSize`/`setFontFamily`/`setFontWeight` move the cell size and told the server nothing, so raising the font on a phone left the CLI wrapping at the old column count (`_refitAfterCellSizeChange`). ⚠️ **Resize is no longer write-only.** `Session.resize` DECLINES a small-viewport request while a desktop connection holds an active sizing claim and says nothing, so both transports now answer with `Session.ptyGeometry` (`{"t":"zc"}` on the socket, the body of the resize POST) and `_onPtyGeometryReport` adopts it — a terminal that keeps a WIDTH the PTY refused renders GARBLED, not merely wrong-sized. ⚠️ While that refusal stands (`_paneWidthRefused`), a resize ASKS for the container's width without applying it (`_geometryForResizeRequest`: rows follow the container, columns stay at the PTY's): fitting first re-wrapped the whole buffer to the container and back on every 30s mobile retry, and ran the scrollback clear for a resize that brings no redraw. `selectSession` clears the flag, since it belongs to the previous pane. ⚠️ **`ptyGeometry` is null without a live pane**, never the field values: they are seeded at spawn (`_notePtySpawnGeometry`, so a reattached pane reports its tmux window's real size) and moved by `resize()`, but a dead-pane session still holds the constructor defaults of 120x40 or a gone pane's size — reporting those made a client adopt a size no process was ever told and claim another device owned the pane when none existed. ⚠️ **COLUMNS ONLY** (one documented exception, the keyboard row hold in the next paragraph). Adopting the PTY's ROWS was a regression: a phone taking a desktop's 43 rows into a viewport with room for 18 painted an `.xterm-screen` far taller than its container, xterm's own viewport then had nothing to scroll, and the CLI's input line sat below the container with no gesture able to reach it — output visible, typing invisible, for as long as the claim stayed hot. Width is the axis the wrap arithmetic depends on; rows only decide how much is on screen, and keeping the local count keeps the composer at the bottom of a viewport that scrolls. ⚠️ **`.term-overflows-x` keys on what does not FIT, not on a PTY mismatch**, because the 40-column floor widens the terminal past a narrow container with the PTY agreeing throughout (measured at 360px: font 18 paints 433px, font 24 paints 578px — 38% unreachable, and `increaseFontSize` reaches 24 in two taps). `_syncTerminalOverflowAffordance()` MEASURES `.xterm-screen` against the container on the next frame rather than deriving it from cell arithmetic. ⚠️ That rule sets **both** overflow axes — mobile.css loads later with `.terminal-container { overflow: visible }`, and a bare `overflow-x` would leave overflow-y computing to `auto`, handing the browser a vertical scroll container the terminal's touch handler does not know about — and sets **no `touch-action`**: the terminal's own touchmove handler pans it (`canPanHorizontally`), because `touchstart` preventDefault()s every 'content' tap and that cancels a native `pan-x` before it starts (measured: a 140px swipe reaLine truncated
|
||||
|
||||
**The one exception to COLUMNS ONLY: rows held under the on-screen keyboard** (#672, `keyboardHoldsRows`, per-device, default ON): every PTY height change makes Claude Code's inline renderer clear the screen and reprint only the transcript tail that fits the new height, so the rows above that tail are gone from tmux and older ones stay in history as stale copies, and the phone keyboard opening and closing was such a change each time. **Measured** on Claude Code 2.1.306 with tmux 3.2a, a fresh session already at the phone's size printing 100 numbered lines: five keyboard cycles (PTY 62x38 to 62x15 and back, one SIGWINCH per transition) left 75 of the 100 in `tmux capture-pane` history; with the rows held the PTY stayed 62x38, no SIGWINCH reached the pane and all 100 remained. So `KeyboardHandler` captures `terminal.rows` on the show transition (`app._keyboardHeldRows`) and `getTerminalDimensions()` never reports fewer rows while the keyboard is visible; columns still follow the container, so the #464 width rule is untouched. ⚠️ **Why this is not the regression the COLUMNS ONLY note describes.** There the extra rows came from ANOTHER device's sizing claim, adopted from `ptyGeometry`, and nothing kept the composer in view: an `.xterm-screen` taller than its container with the input line below it and no gesture able to reach it. Here the rows are this device's own keyboard-free rows, held on purpose only while the keyboard is up, and the screen is translated up by `--kb-clip` (`_applyKeyboardClip()`, pure math in `keyboardClipPx()` in constants.js) so the last content row sits at the bottom of the visible box: following live output, the cursor counts only within `KEYBOARD_CLIP_CURSOR_REACH` (2) rows below the last content (a TUI that parks its cursor far below what it drew must not scroll its content away); reading history, the offset follows the scroll position so the top of the scrollback stays reachable. The local-echo overlay is bounded to the visible rows through `setRowLimit()`, which narrows the overlay renderer's existing `totalRows` bound rather than adding a second one, so a long draft grows upward from the last row the user can see. `reconcilePtyGeometry` still adopts columns only: nothing here takes rows from the PTY's report. `test/keyboard-held-rows.test.ts` pins the composer row inside the visible box with the rows held, against a real headless xterm and the shipped `_applyKeyboardClip()`. ⚠️ Holding goes through `getTerminalDimensions()`, never one caller, so the fit, the PTY resize and the capture-geometry comparisons agree; `syncTerminalGeometry()` skips `fitAddon.fit()` while held, so xterm never visits the short size. ⚠️ A shape change (rotation, fold) releases the hold AND arms the viewport settle (`_scheduleViewportSettle()`), which refits and tells the PTY: with the keyboard still up `throttledResize` stands aside and a rotation alone arms nothing, so without it xterm kept the held rows with no clip and the composer sat under the keyboard until it closed. A rotation with no hold arms nothing, as before. ⚠️ ONLY inline renderers qualify (`_keyboardHoldEligible()`): the registry's `capabilities.keyboardHold: 'inline'` (Claude alone; read through `window.__codemanKeyboardHoldModes`, never an id literal), never while `cliMouseTracking` reports Claude's fullscreen mode (it lays out the full height and has not been measured losing lines, so it resizes as before), never remote or docker (their local pane hosts a nested client). A full-height layout (codex: banner at the top, composer pinned to the bottom) cannot fit both ends above the keyboard, which is what the first, unscoped version got wrong. ⚠️ The hold lives on the shared terminal, so `_reconcileKeyboardHold()` releases it whenever the active session stops qualifying (tab switch, a `session:updated`, a reconnect, the setting turned off), and keyboard close releases it too; it never re-holds with the keyboard already up, so a session that becomes eligible mid-keyboard keeps the short rows until the keyboard closes.
|
||||
|
||||
@@ -1339,7 +1339,7 @@ Tests: `test/mobile-prompt-composer.test.ts` (in the CI gate, deliberately not u
|
||||
|
||||
### Z-index layers
|
||||
|
||||
**Z-index layers**: subagent windows (1000), split picker menu (1000, `.split-picker-menu`), Tiles count menu (1000, `.tile-count-menu`), the closing grid's still copy (`.tile-grid-ghosts`, z-index 3 inside `.main`, over the single view coming back; hidden under `.main.webview-active`), plan agents (1100), mobile/tablet fixed header (1200, `mobile.css`), modals on ≤768px (1300 — must beat the fixed header or the modal close button is buried), log viewers (2000), connection-loss overlay (2500, above the fixed header and modals), image popups (3000), response viewer (5000, backdrop 4999), folder grid (5090, `#folderGridOverlay` — above the response viewer a folder link opens it from, below the file preview its tiles open, so a tile's preview and its ←/→ paging sit on top of the grid), file-preview overlay (5100 — must outrank the response viewer, which can launch it; at its old 2000 a path clicked in the chat opened BEHIND the chat), toasts/path picker (10000+, deliberately above the preview), the custom-model center-status banner (10001, `.center-status-banner` — `[hidden]` must re-assert `display: none` over its own `display: flex`, same trap as `.home-sessions[hidden]`, or `dismiss()` leaves an invisible click-blocker dead centre on screen), the swap-confirm and context-warning modals (10010, `#customModelSwapConfirmModal`/`#customModelContextWarningModal` — must clear both the plain `.modal` z-index of 1000 and the center-status banner it can appear over), terminal touch-selection bar (900 — above terminal content and the local-echo overlay, deliberately BELOW floating agent windows so it can never cover their controls), local echo overlay (7), iOS IME composition preview (EFFECTIVE layer depends on its home: with local echo on it is part of the local echo overlay at 7, drawn by `setComposition()` as an underlined tail after the pending text; with local echo off it is a span at z-index 6 inside `.xterm-helpers`, but `.xterm-helpers` is its own z-index 5 stacking context, so the span's effective layer is 5. That is below the overlay's 7, which is why the span cannot be used while the overlay holds text: typed text never reaches the PTY before Enter, the PTY cursor that places the span stays at the prompt start, and the overlay's opaque line div covers it).
|
||||
**Z-index layers**: subagent windows (1000), split picker menu (1000, `.split-picker-menu`), Tiles count menu (1000, `.tile-count-menu`), the closing grid's still copy (`.tile-grid-ghosts`, z-index 3 inside `.main`, over the single view coming back; hidden under `.main.webview-active`), mobile/tablet fixed header (1200, `mobile.css`), modals on ≤768px (1300 — must beat the fixed header or the modal close button is buried), log viewers (2000), connection-loss overlay (2500, above the fixed header and modals), image popups (3000), response viewer (5000, backdrop 4999), folder grid (5090, `#folderGridOverlay` — above the response viewer a folder link opens it from, below the file preview its tiles open, so a tile's preview and its ←/→ paging sit on top of the grid), file-preview overlay (5100 — must outrank the response viewer, which can launch it; at its old 2000 a path clicked in the chat opened BEHIND the chat), toasts/path picker (10000+, deliberately above the preview), the custom-model center-status banner (10001, `.center-status-banner` — `[hidden]` must re-assert `display: none` over its own `display: flex`, same trap as `.home-sessions[hidden]`, or `dismiss()` leaves an invisible click-blocker dead centre on screen), the swap-confirm and context-warning modals (10010, `#customModelSwapConfirmModal`/`#customModelContextWarningModal` — must clear both the plain `.modal` z-index of 1000 and the center-status banner it can appear over), terminal touch-selection bar (900 — above terminal content and the local-echo overlay, deliberately BELOW floating agent windows so it can never cover their controls), local echo overlay (7), iOS IME composition preview (EFFECTIVE layer depends on its home: with local echo on it is part of the local echo overlay at 7, drawn by `setComposition()` as an underlined tail after the pending text; with local echo off it is a span at z-index 6 inside `.xterm-helpers`, but `.xterm-helpers` is its own z-index 5 stacking context, so the span's effective layer is 5. That is below the overlay's 7, which is why the span cannot be used while the overlay holds text: typed text never reaches the PTY before Enter, the PTY cursor that places the span stays at the prompt start, and the overlay's opaque line div covers it).
|
||||
|
||||
## Security layers
|
||||
|
||||
|
||||
@@ -8,8 +8,8 @@ This guide documents the browser testing infrastructure, framework comparison re
|
||||
# Run standalone benchmark (recommended - avoids vitest hook issues)
|
||||
npx tsx scripts/browser-comparison.mjs
|
||||
|
||||
# Run existing browser E2E tests
|
||||
npm test -- test/browser-e2e.test.ts
|
||||
# Run the browser suite (Playwright; the files are listed in config/test-suites.ts)
|
||||
npm run test:browser
|
||||
```
|
||||
|
||||
## Framework Comparison Results
|
||||
@@ -67,7 +67,7 @@ We tested three browser automation frameworks against the Codeman web UI:
|
||||
});
|
||||
```
|
||||
|
||||
3. **Use the existing browser-e2e.test.ts pattern** which uses agent-browser CLI commands via `execSync` (avoids async hook issues)
|
||||
3. **Drive agent-browser through its CLI** with `execSync`, as `scripts/browser-comparison.mjs` does (avoids async hook issues)
|
||||
|
||||
## Test File Structure
|
||||
|
||||
@@ -93,10 +93,8 @@ fixed ports 3180-3182.
|
||||
|
||||
| File | Framework | Status |
|
||||
|------|-----------|--------|
|
||||
| `test/browser-e2e.test.ts` | agent-browser | ✅ Working |
|
||||
| `test/browser-playwright.test.ts` | Playwright | ⚠️ Vitest hook issues |
|
||||
| `test/browser-puppeteer.test.ts` | Puppeteer | ⚠️ Vitest hook issues |
|
||||
| `test/browser-agent.test.ts` | agent-browser | ⚠️ Vitest hook issues |
|
||||
| `test/*.browser.test.ts` and the other files in `BROWSER_TEST_GLOBS` (`config/test-suites.ts`) | Playwright | ✅ `npm run test:browser` |
|
||||
| `test/mobile/**` | Playwright | ✅ `npm run test:mobile` |
|
||||
| `scripts/browser-comparison.mjs` | All three | ✅ Working (standalone) |
|
||||
|
||||
## Framework-Specific Patterns
|
||||
|
||||
+21
-11
@@ -20,8 +20,8 @@ in [architecture-invariants.md](architecture-invariants.md#local-model-install).
|
||||
|
||||
The window offers the best model of the catalogue (`src/config/local-model-catalog.ts`) that
|
||||
fits this Mac's memory at a context a coding agent can work with, and under it every other
|
||||
model of the catalogue that fits (ten models today: a 16 GB Mac sees one of them, a 512 GB
|
||||
Mac all ten). What the catalogue answers today, before the runtime measured anything (the
|
||||
model of the catalogue that fits (eleven models today: a 16 GB Mac sees one of them, a 512 GB
|
||||
Mac all eleven). What the catalogue answers today, before the runtime measured anything (the
|
||||
budget is then an estimate: 2/3 of the memory below 36 GB, 3/4 from 36 GB, less 1 GiB, and
|
||||
never more than the memory less 6, 8 or 12 GiB for macOS, Codeman, a browser and the agent):
|
||||
|
||||
@@ -31,9 +31,9 @@ never more than the memory less 6, 8 or 12 GiB for macOS, Codeman, a browser and
|
||||
| 16 GB | 10.4 GB | A small model (`limited`): Ornith 1.0 9B at 65,536 tokens, 9.3 GB, tight (90%). Its build has no vision projector, which makes it 0.9 GB smaller than the other two 9B builds: MiMo V2.6 9B needs 10.2 GB there, 98.7% of the budget, just past the 98% a tight fit may reach. Once the runtime measures what a 16 GB Mac mini measured (10.7 GB), all three fit and MiMo is the pick. No 9B was run on such a Mac by us: only a run settles it |
|
||||
| 18 GB | 11.8 GB | A small model (`limited`): MiMo V2.6 9B at 131,072 tokens, 11.4 GB, tight. Ornith 1.0 9B (10.5 GB) and Qwen3.5 9B are the alternatives |
|
||||
| 24 GB | 16.1 GB | The same, with room. On a base M2 or M3 (100 GB/s) it computes to 9.3 tokens per second: slow |
|
||||
| 32 GB | 21.8 GB | No longer a small-model Mac: Muse Glimmer 30B fits at 65,536 tokens (21.2 GB, 97%, tight). It is a dense model. On an M1 Max or M2 Max it computes to 11.8 tokens per second and is the pick; on a base or Pro chip it computes to under 6 and is listed as slow, and the pick stays MiMo V2.6 9B at 131,072 tokens with the note that it is a small model. North Mini Code 1.0 needs 23.2 GB at 65,536 tokens; once the runtime measures about 3/4 of the memory, as it did on a 16 and a 48 GB Mac, the Mac gets it at 131,072 tokens, or Qwen3.8 27B at 65,536 tokens on a Max chip |
|
||||
| 32 GB | 21.8 GB | No longer a small-model Mac: Muse Glimmer 30B fits at 65,536 tokens (21.2 GB, 97%, tight). It is a dense model. On an M1 Max or M2 Max it computes to 11.8 tokens per second and is the pick; on a base or Pro chip it computes to under 6 and is listed as slow, and the pick stays MiMo V2.6 9B at 131,072 tokens with the note that it is a small model. North Mini Code 1.0 needs 23.2 GB at 65,536 tokens; once the runtime measures about 3/4 of the memory, as it did on a 16 and a 48 GB Mac, the Mac gets it at 131,072 tokens, or Qwen3.8 27B at 65,536 tokens on a Max chip. Run once on a Mac (an M5 Pro with 48 GB, 2026-11-12): this GGUF build wrote 15 tokens per second, and an OpenCode worker given a one-line task showed no answer after 7 minutes. Its MLX build, which finished an OpenCode turn on a one-line prompt in 45 seconds, needs 36.1 GB and is offered from 48 GB |
|
||||
| 36 GB | 27.9 GB | Qwen3.8 27B at 131,072 tokens on an M4 or M5 Max (27.0 GB, 97%); on a slower chip, where the dense 27B computes to under 10 tokens per second, Qwen3.6 35B-A3B as a GGUF build (27.1 GB, 97%). Both tight. Muse Glimmer 30B at 131,072 tokens (21.6 GB, 78%) is the alternative with room to spare |
|
||||
| 48 GB | 37.6 GB | Qwen3.6 35B-A3B (MLX) at 131,072 tokens: the pair we tested, "Recommended" on an Apple M5 Pro with 48 GB. On a Max chip Qwen3.8 27B at 262,144 tokens (32.1 GB, tight). The test was a short task: in a long session MLX may keep up to 8 GiB more, which brings this pair to the edge of the budget, and past it while a long prompt is processed |
|
||||
| 48 GB | 37.6 GB | Qwen3.6 35B-A3B (MLX) at 131,072 tokens: the pair we tested, "Recommended" on an Apple M5 Pro with 48 GB. On a Max chip Qwen3.8 27B at 262,144 tokens (32.1 GB, tight). A session of many prompts on that Mac (a 95,000-token prompt, then twelve separate ones of 15,000 tokens, measured on 2026-11-12) ended at 33.4 GB of the 40.2 GB its runtime measures, still growing by 0.5 GiB a prompt: MLX may keep up to 8 GiB of earlier prompts, which brings this pair to the edge of the budget. Muse Glimmer 30B as its MLX build is offered here too, at 65,536 tokens (36.1 GB, tight) |
|
||||
| 64 GB | 50.5 GB | Qwen3.8 27B at 262,144 tokens on a Max chip; Qwen3.6 35B-A3B (MLX) on a Pro chip |
|
||||
| 96 GB | 76.2 GB | Qwen3.8 27B at 262,144 tokens; on an M3 Max, Qwen3.6 35B-A3B (MLX) |
|
||||
| 128 GB | 102 GB | Ornith 1.5 122B-A10B (MLX) at 131,072 tokens, 97.4 GB, tight |
|
||||
@@ -73,7 +73,10 @@ names its runner (`runner`) and its figures follow that runner's rule:
|
||||
- **MLX** grows its cache with the tokens actually used, keeps snapshots of the recurrent
|
||||
state, and may keep up to 8 GiB of snapshots of earlier prompts, which no setting bounds. A
|
||||
Mac always takes the MLX build of a tag that has one. Below 48 GB that 8 GiB does not fit
|
||||
beside a useful model, so the catalogue lists GGUF builds there.
|
||||
beside a useful model, so the catalogue lists GGUF builds there. For Muse Glimmer the MLX
|
||||
runner was measured holding 38,000 to 45,000 bytes per token, against the 7,072 its GGUF
|
||||
build computes to: close to every layer's cache at full length, so it evidently does not
|
||||
trim the sliding-window layers the way llama.cpp does.
|
||||
|
||||
Where every figure comes from:
|
||||
|
||||
@@ -84,6 +87,7 @@ Where every figure comes from:
|
||||
| `mimo-v2.6:9b-q4_k_m` | llama.cpp | the same (a fine-tune of Qwen3.5-9B) | 9.3: the same architecture and size |
|
||||
| `north-mini-code-1.0:q4_k_m` | llama.cpp | computed from its config | 13.6: the 35B-A3B's, the same 3 billion active parameters |
|
||||
| `muse-glimmer:30b-q4_k_m` | llama.cpp | computed from its config: 13 full-attention and 39 sliding-window layers | 2.95: the dense 27B's, whose weights are the same size |
|
||||
| `muse-glimmer:30b-mlx` | MLX | **measured** on an Apple M5 Pro with 48 GB, the 8 GiB of prefix snapshots counted | 5.4: measured beside the 35B-A3B on MLX, 0.32 of its 16.9 |
|
||||
| `qwen3.6:35b-a3b-mtp-q4_k_m` | llama.cpp | computed from the Qwen3.6-35B-A3B config, prediction layer included | 13.6: a published run on an M1 Max |
|
||||
| `qwen3.6:35b-a3b` | MLX | **measured** on an Apple M5 Pro with 48 GB | 16.9: a published run; 67.7 measured on the tested Mac |
|
||||
| `qwen3.8:27b-q8_0` | llama.cpp | computed from the Qwen3.8-27B config, prediction layer included | 1.7: the row below scaled by file size |
|
||||
@@ -91,12 +95,18 @@ Where every figure comes from:
|
||||
| `ornith-1.5:122b` | MLX | computed from the Qwen3.5-122B-A10B config, scaled by the measured MLX row, + 8 GiB | 5.0: the 35B-A3B's, x 3/10 active parameters |
|
||||
|
||||
Sizes are what the registry serves a Mac for each tag (every layer plus the config), read on
|
||||
2026-11-08 (the Ornith 1.0 and Muse Glimmer rows on 2026-11-10). Only one row was ever run on
|
||||
a Mac, so every other answer in the table above is a calculation. For a llama.cpp build the check after the download catches a load that was
|
||||
2026-11-08 (the Ornith 1.0 and Muse Glimmer rows on 2026-11-10, Muse Glimmer's MLX build on
|
||||
2026-11-12). Two rows carry memory figures measured on a Mac, both on an Apple M5 Pro with
|
||||
48 GB; every other answer in the table above is a calculation. Three more rows were installed
|
||||
and loaded on that Mac on 2026-11-12 (Qwen3.5 9B, Ornith 1.0 9B and Muse Glimmer as a GGUF
|
||||
build): that checked their download size and that they load on the GPU, not their memory
|
||||
figures. For a llama.cpp build the check after the download catches a load that was
|
||||
judged too kindly, but not what grows after it in host memory (the checkpoints and the prompt
|
||||
cache, which are counted, not checked); for an MLX build it catches neither (see "The check"
|
||||
below). The measured row's figures come from single long prompts, not a session of many
|
||||
requests, in which MLX may keep up to 8 GiB more. The catalogue header lists the models left
|
||||
below). The 35B-A3B's figures come from single long prompts, not a session of many
|
||||
requests, in which MLX may keep up to 8 GiB more: such a session was measured on it later
|
||||
(the 48 GB row above) and its figures were left as they are. Muse Glimmer's MLX row counts
|
||||
the 8 GiB. The catalogue header lists the models left
|
||||
out on purpose (no evidence of working tool calls, a restrictive licence, a known bug, a
|
||||
build that needs a newer runtime than the pinned one) and why. The strongest of those today
|
||||
is Ripple 65B Preview, published on 2026-11-09: every build of it requires Ollama 0.40.16,
|
||||
@@ -484,8 +494,8 @@ or `python3`.
|
||||
a session uses the model: close those sessions first.
|
||||
- **The runtime does not enforce the context length.** A prompt longer than the context was
|
||||
accepted in testing. Do not rely on the runtime to stop one.
|
||||
- **Most memory figures are calculated, not measured.** One model was run on one Mac; the
|
||||
others are computed from their architecture, and the runtime settings they assume (an 8-bit
|
||||
- **Most memory figures are calculated, not measured.** Two models were measured on one Mac;
|
||||
the others are computed from their architecture, and the runtime settings they assume (an 8-bit
|
||||
K/V cache, flash attention, a 1 GiB prompt cache) were read in its source, not yet observed
|
||||
on a Mac. "Recommended" appears only for the pair we ran, on the Mac we ran it on.
|
||||
- **A tool call that quotes a tool call can be cut off.** The pinned runtime reads the tool
|
||||
|
||||
@@ -363,5 +363,5 @@ The Orchestrator can optionally USE the Ralph Loop internally for phase executio
|
||||
| `src/types/orchestrator.ts` | Type definitions |
|
||||
| `src/prompts/orchestrator.ts` | Prompt templates |
|
||||
| `src/web/routes/orchestrator-routes.ts` | API endpoints |
|
||||
| `src/web/public/orchestrator-ui.js` | Frontend panel |
|
||||
| `src/web/public/orchestrator-panel.js` | Frontend panel |
|
||||
| `src/web/ports/orchestrator-port.ts` | Port interface |
|
||||
@@ -837,8 +837,6 @@ POST /api/sessions/:id/auto-clear
|
||||
- `src/ralph-tracker.ts` - Core detection engine
|
||||
- `src/ralph-loop.ts` - Task orchestration
|
||||
- `src/respawn-controller.ts` - Session cycling
|
||||
- `src/spawn-orchestrator.ts` - Autonomous agent lifecycle (uses RalphTracker for completion)
|
||||
- `src/spawn-detector.ts` - Detects `<spawn1337>` tags in terminal output
|
||||
- `src/types.ts` - Type definitions
|
||||
|
||||
---
|
||||
|
||||
@@ -79,5 +79,5 @@ Uses temp file for prompt to avoid E2BIG errors with large terminal buffers.
|
||||
|
||||
- `test/respawn-scenarios.md` - Comprehensive test scenarios for edge cases
|
||||
- `test/respawn-test-plan.md` - Test environment architecture and strategies
|
||||
- `test/respawn-test-utils.ts` - Mock utilities (MockSession, MockAiIdleChecker, MockAiPlanChecker)
|
||||
- `test/mocks/mock-session.ts` - `MockSession`, the session double the respawn tests drive
|
||||
- `test/respawn-analysis.md` - Code coverage analysis and identified issues
|
||||
@@ -110,9 +110,10 @@ The defaults you will care about, all under **App Settings**:
|
||||
**Separate Claude accounts per session.** Set `CLAUDE_CONFIG_DIR` in a session's environment
|
||||
overrides to point it at a different Claude config directory, which is how you run one
|
||||
session on a client's subscription and another on your own. One caveat: a relocated config
|
||||
directory writes transcripts outside `~/.claude/projects`, which blinds the response viewer,
|
||||
subagent windows, ultracode panel, and Read My Mind for that session. Symlink `projects`
|
||||
back into the shared tree to keep them working:
|
||||
directory writes transcripts outside `~/.claude/projects`, which blinds subagent windows,
|
||||
the ultracode panel and Read My Mind for that session (the response viewer and the Edit
|
||||
history panel read the relocated directory). Symlink `projects` back into the shared tree
|
||||
to keep them working:
|
||||
|
||||
```bash
|
||||
ln -s ~/.claude/projects <configDir>/projects
|
||||
|
||||
@@ -108,9 +108,9 @@ are not reading.
|
||||
|
||||
- **A session pointed at a relocated Claude config directory goes blind here.** Transcripts
|
||||
written outside `~/.claude/projects` are invisible to the watchers, so subagent windows,
|
||||
the ultracode panel, the response viewer, and Read My Mind all stop working for that
|
||||
session. Symlink `projects` back into the shared tree to fix it. See
|
||||
[Agent CLIs](Agent-CLIs).
|
||||
the ultracode panel and Read My Mind stop working for that session. Symlink `projects`
|
||||
back into the shared tree to fix it. The response viewer reads the session's own
|
||||
directory and keeps working. See [Agent CLIs](Agent-CLIs).
|
||||
- **Closing a window does not cancel the agent.** Nothing on this page controls agents; it
|
||||
observes them.
|
||||
- **Windows are opt-in for ultracode, automatic for subagents.**
|
||||
|
||||
Generated
-8
@@ -52,7 +52,6 @@
|
||||
"@types/pngjs": "^6.0.5",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/uuid": "^10.0.0",
|
||||
"@types/web-push": "^3.6.4",
|
||||
"@types/ws": "^8.18.1",
|
||||
"@vitest/coverage-v8": "^4.1.8",
|
||||
@@ -3966,13 +3965,6 @@
|
||||
"csstype": "^3.2.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/uuid": {
|
||||
"version": "10.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz",
|
||||
"integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/web-push": {
|
||||
"version": "3.6.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/web-push/-/web-push-3.6.4.tgz",
|
||||
|
||||
+1
-1
@@ -29,6 +29,7 @@
|
||||
"pretest:mobile": "node scripts/prepare-test-vendor.mjs",
|
||||
"test:mobile": "vitest run --config test/mobile/vitest.config.ts",
|
||||
"check:frontend-syntax": "node scripts/check-frontend-syntax.mjs",
|
||||
"check:frontend-dead": "node scripts/check-frontend-dead-code.mjs",
|
||||
"check:browser-excludes": "node scripts/check-browser-test-excludes.mjs",
|
||||
"check:local-model-catalog": "tsx scripts/check-local-model-catalog.mjs",
|
||||
"fix:node-pty": "node scripts/fix-node-pty.mjs",
|
||||
@@ -123,7 +124,6 @@
|
||||
"@types/pngjs": "^6.0.5",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/uuid": "^10.0.0",
|
||||
"@types/web-push": "^3.6.4",
|
||||
"@types/ws": "^8.18.1",
|
||||
"@vitest/coverage-v8": "^4.1.8",
|
||||
|
||||
@@ -35,8 +35,8 @@ security-framework = "3"
|
||||
# Ignoring signals in the logo blinker (src/logo.rs). Already in the tree
|
||||
# through wry and tao, so no new crate is added.
|
||||
libc = "0.2"
|
||||
# JavaScript dialogs, HTTP Basic challenges, clearing cookies and the window's
|
||||
# content size (src/macos.rs). The versions wry already pulls in, so no new
|
||||
# JavaScript dialogs, HTTP Basic challenges, clearing one server's cookies and
|
||||
# the window's content size (src/macos.rs). The versions wry already pulls in, so no new
|
||||
# crate is added.
|
||||
objc2 = { version = "0.6.5", default-features = false, features = ["std"] }
|
||||
block2 = { version = "0.6.2", default-features = false, features = ["std"] }
|
||||
@@ -44,10 +44,12 @@ objc2-foundation = { version = "0.3.2", default-features = false, features = [
|
||||
"std",
|
||||
"objc2-core-foundation",
|
||||
"block2",
|
||||
"NSArray",
|
||||
"NSBundle",
|
||||
"NSDate",
|
||||
"NSDictionary",
|
||||
"NSGeometry",
|
||||
"NSHTTPCookie",
|
||||
"NSObject",
|
||||
"NSOperation",
|
||||
"NSProcessInfo",
|
||||
@@ -61,6 +63,7 @@ objc2-foundation = { version = "0.3.2", default-features = false, features = [
|
||||
"NSURLRequest",
|
||||
"NSURLResponse",
|
||||
"NSURLSession",
|
||||
"NSUUID",
|
||||
"NSValue",
|
||||
] }
|
||||
objc2-app-kit = { version = "0.3.2", default-features = false, features = [
|
||||
@@ -80,6 +83,7 @@ objc2-web-kit = { version = "0.3.2", default-features = false, features = [
|
||||
"block2",
|
||||
"objc2-app-kit",
|
||||
"WKFrameInfo",
|
||||
"WKHTTPCookieStore",
|
||||
"WKNavigationDelegate",
|
||||
"WKSecurityOrigin",
|
||||
"WKUIDelegate",
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
A small native app that opens Codeman in its own window. Double-click it, and
|
||||
it runs Codeman on this Mac (installing it first if it is not there) or
|
||||
connects to Codeman on another machine (installing it there over SSH if
|
||||
needed), and Codeman fills the window. `⌃⌘F` puts it in full screen.
|
||||
needed), and Codeman fills the window. Several servers open side by side as
|
||||
tabs in the title bar, one click apart. `⌃⌘F` puts it in full screen.
|
||||
|
||||
macOS first: the app runs on 11.3 or later, and Codeman's own page needs the
|
||||
WebKit of Safari 16.4 (see Known limits). The same code is meant to build for
|
||||
@@ -28,20 +29,21 @@ cannot do.
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| **Server tabs** | One tab per Codeman server, in a strip that takes the place of the title bar (the traffic lights sit at its left end, so the strip costs about 10 points over a plain title bar and stays in full screen). A click switches tabs, and every tab stays loaded, so a switch is instant: no reload, no new login. Each tab shows what its server's agents do: a red count for sessions that need a permission or an answer, an amber dot when one finished and waits for you, a blue ring while agents work, a dashed circle when the server does not answer. The app reads that itself from each server every two seconds (`api/sessions` and `api/approvals`, the reader the Apple logo uses), because WebKit stalls a hidden page. Each tab has a colour of its own, as a stripe on the tab in front, so you do not type into the wrong machine. `+` (or `⌘T`) opens the connect screen in a new tab; a server that is already open in a tab is not opened twice, its tab comes to the front instead. A double-click on a name, or **Rename Tab…** in the right-click menu, renames it; the right-click menu also picks the colour, reloads, connects the tab to another server and closes tabs. Drag a tab to reorder. Closing a tab only closes the window onto that server: its sessions keep running there, and `⇧⌘T` opens it again. The tabs of a server come back at the next launch, and connect by themselves when *Connect automatically when the app opens* is on. **All Servers** (`⌘0`, or the grid button left of the tabs) shows every server at once, the ones that need you first, with their sessions most urgent first; a click on a session opens its tab and selects it. |
|
||||
| **This Mac** | The connect screen's first tab looks for Codeman on this Mac and offers what fits: *Open Codeman* when it runs, *Start Codeman* when it is installed but stopped, *Install Codeman on this Mac* when it is not there. The address comes from Codeman's LaunchAgent (port, sub-path, HTTPS). The tab also finds every Codeman server of yours that already runs on this Mac (with `ps` and `lsof`: a `codeman web --port 4000` in a terminal, a beta instance beside the installed one) and recommends connecting to it. Each one's address is worked out from its listening socket and its command line (`127.0.0.1` for a bind to loopback or to every interface, its own address for a bind to one, `https` with `--https`, the path of `--base-url`), and each is asked once whether Codeman answers there. When nothing answers at the usual address (the LaunchAgent's, or `http://127.0.0.1:3000` without one), *Open Codeman* is for the first found server that does; when none of them can be opened, the tab says *Codeman is already running on this Mac* and lists them. Next to a Codeman that answers, the others are listed under *Also running on this Mac*. A row shows the address, the version, and a *Connect* button, or the reason the app cannot open that one (HTTPS with Codeman's own certificate, no answer). *Connect* is the connect of the Another machine tab with that address filled in: the same check, the login saved for it, the same entry under recent servers. Finding a server connects to nothing by itself. The tab never offers to start a second server, which would take over the first one's sessions, and Start refuses while one runs. A server that runs but listens nowhere yet (the first seconds after login, a restart) shows as *starting*: the tab looks again every second and, when a connect to this Mac had just been refused, opens Codeman once it is up. Start asks launchd to run the LaunchAgent (`kickstart`, or `bootstrap` when it is not loaded), so the server keeps its own settings and supervision; without a LaunchAgent it runs `codeman web -d`. The login comes from where Codeman keeps it: the LaunchAgent's `CODEMAN_USERNAME`/`CODEMAN_PASSWORD`, else `~/.codeman/.env` (what Codeman's command-line clients read), `admin` by default. It goes only to `127.0.0.1` on that Codeman's port, only while one of your own Codeman processes holds that port, is never saved to the Keychain, and never reaches the page. Whether Codeman is installed is looked up in its files and processes, then the login shell; the interactive profile (nvm in `.zshrc`, say) only on *Check again*. Install sets Codeman up from the app itself, with no Terminal and no password (see Decisions). It fetches the installer, asks it what is on this Mac, then asks two things: which coding agent to install, only when this Mac has none (the list comes from the installer, and *Skip for now* is there), and who can reach Codeman (this Mac only, or the local network with a password). A checklist follows the install, the installer's output is one click away, and Cancel stops it; installing again picks up where it stopped. Codeman runs as a LaunchAgent, so it keeps running when the app quits and starts at login. Port 3000 is used unless something else answers there, then the next free one. Closing the app does not stop an install: it runs on its own, and the app picks it up when it opens again. When it is done the app looks every 3 seconds and opens Codeman as soon as it answers; it stops looking after the first answer, after 30 minutes, or 90 seconds after a finished install whose server never answered (then it offers Start). *Install in Terminal instead* runs the installer in a Terminal window, for what the app cannot do (see Known limits): it may ask for the Mac password (Homebrew) and asks its own questions there. The app offers it by itself on a Mac where the graphical install cannot finish. An install still running in Terminal is recognized by its process, so the tab waits for it instead of offering Install twice. *Add a coding agent*, on this tab and in the app menu whenever Codeman is on this Mac, is the same chooser after the install: pick one agent, watch it install, open Codeman. It needs no password, leaves a running Codeman alone, and can be cancelled or left running like an install. After *Skip for now* the app says Codeman has no agent yet and offers this before it opens Codeman. |
|
||||
| **Another machine** | The second tab connects to a server by address (below). *Codeman is not installed there yet?* opens Terminal, connects with `ssh -t` and runs Codeman's installer on that machine, which asks its questions there; the app then suggests `http://<host>:3000` and the installer prints the real address at the end. The SSH login is checked to the characters of a user and host name (no option can be slipped in) and may carry a `:port`. The remote command runs under `bash -o pipefail`, so a failed download fails the install instead of reporting success. The same tab shows the one-line install command, with a Copy button, to run on a machine by hand. |
|
||||
| **Connect screen** | Server address, recent servers, a login for password-protected servers (password kept in the macOS Keychain), auto-connect at launch. An address typed without `http://` or `https://` gets `http://`, except a tailnet name with no port (`machine.tailnet.ts.net`, which is `tailscale serve`), which gets `https://`. It explains each failure: nothing listening; wrong password; too many failed logins (the password field stays open, since a single-user Codeman accepts the right password even then); unknown host name; an address this Mac cannot reach (with a pointer to the Local Network setting); an `http://` address on a port that only speaks HTTPS; an untrusted certificate; a redirect, with a button for the suggested `https://` address; not a Codeman server. A multi-user account that must change its password connects, and Codeman's own dialog asks for the new one. If the server page has not started showing within 15 seconds, or you press Cancel while it opens, the connect screen comes back with a notice. A login that would cross the network over plain `http://` to another machine says so. Return opens or starts the Codeman on this Mac (or connects to the one found here, when that is the tab's main button) and Esc cancels a connect, as in a Mac dialog (Install always takes a click). On a Mac whose WebKit is too old for Codeman it says so and Connect stays off (see Known limits). |
|
||||
| **Start Codeman** | On the This Mac tab, and when `http://127.0.0.1:<port>` or `http://localhost:<port>` answers nothing, one click runs `codeman web -d` (or `~/.codeman/app`) with your login shell's environment, so the server gets your real PATH (Homebrew, nvm) for the agents it spawns. zsh, bash and other POSIX shells run the start themselves; fish, nu, xonsh, tcsh and other shells only report their environment, and the start runs under `/bin/sh` with it. Offered for those two addresses only: `codeman web -d` listens on 127.0.0.1. |
|
||||
| **Login** | The app answers the server's HTTP Basic login requests itself, with the login you connected with, so the page keeps working after the server restarts (a restart forgets every session cookie). It answers only for Codeman's own pages under the server's base path: a web tab or a rendered HTML file that asks for a Basic login of its own is left to WebKit and never gets your Codeman password. WebKit keeps no copy of the login, so every request for it gets the current one. Each connect first clears the app's cookies, so connecting to the same server as another user really switches users (local storage, where Codeman keeps its per-device settings, stays; a dashboard in a web tab that keeps its own login in a cookie may ask for it again). A page that still gets a 401 reloads once. If the server refuses the login (the password was changed, say), the app does not keep sending it: it checks it with a single probe, and only if the server refuses that too does the connect screen come back with a notice. That does not take focus from the app you are in: if Codeman is in the background, its Dock icon bounces. |
|
||||
| **Login** | The app answers the server's HTTP Basic login requests itself, with the login you connected that tab with (each tab answers for its own server only), so the page keeps working after the server restarts (a restart forgets every session cookie). It answers only for Codeman's own pages under the server's base path: a web tab or a rendered HTML file that asks for a Basic login of its own is left to WebKit and never gets your Codeman password. WebKit keeps no copy of the login, so every request for it gets the current one. Each connect first clears that server's cookies, so connecting to the same server as another user really switches users (local storage, where Codeman keeps its per-device settings, stays; a dashboard in a web tab that keeps its own login in a cookie may ask for it again). On macOS 14 and later each server's pages keep their cookies and local storage in a data store of their own (see Decisions); before macOS 14 two servers on one machine (a Codeman on port 3000 and a beta on 5000) cannot be open in two tabs at once, since they would share one login cookie, and the app says so. A page that still gets a 401 reloads once. If the server refuses the login (the password was changed, say), the app does not keep sending it: it checks it with a single probe, and only if the server refuses that too does the connect screen come back with a notice. That does not take focus from the app you are in: if Codeman is in the background, its Dock icon bounces. |
|
||||
| **Dialogs** | Codeman's `confirm()`, `prompt()` and `alert()` (Delete case, Kill all sessions, Update Codeman, discarding unsaved edits, ...) show as native macOS dialogs. wry implements none of them, and without them WKWebView answers Cancel without showing anything. Each dialog's first line names the page it comes from, and says so when that is an embedded frame (a web tab, a rendered HTML preview), so a frame cannot pass its text off as Codeman's. |
|
||||
| **Full screen** | `⌃⌘F` or the green button. The last state is restored at launch; *Always Open in Full Screen* forces it. Leaving full screen returns to the saved window size and position. |
|
||||
| **Menus** | A real Edit menu (without one, `⌘C`/`⌘V` do nothing in a WKWebView), Reload `⌘R`, Switch Server `⇧⌘O`, Developer Tools `⌥⌘I`. The page sees every key first, so Codeman's own shortcuts keep working. If the main window ends up showing a raw file instead of Codeman, `⌘R` takes it back to Codeman. |
|
||||
| **Menus** | A real Edit menu (without one, `⌘C`/`⌘V` do nothing in a WKWebView), Reload `⌘R`, Developer Tools `⌥⌘I`, and a Server menu: New Server Tab `⌘T` (Switch Server `⇧⌘O` does the same), Close Tab `⌘W` (Close Window is `⇧⌘W`), Reopen Closed Tab `⇧⌘T`, Show All Servers `⌘0`, Show Previous and Next Tab `⇧⌘[` and `⇧⌘]`, and one item per tab, `⌘1` to `⌘8` (from nine tabs on, `⌘9` is the last one). `⌃Tab` and `⌥1` to `⌥9` stay Codeman's own (they switch sessions inside the server you are on). The page sees every key first, so Codeman's own shortcuts keep working. If the main window ends up showing a raw file instead of Codeman, `⌘R` takes it back to Codeman. |
|
||||
| **Pop-outs** | Implements Codeman's existing native-wrapper bridge, `window.CodemanHost` (`openInHostWindow` in `src/web/public/app.js`), so popping out a session or a file preview opens a real app window, and the pop-out icon is on by default. Session and rendered-HTML pop-outs come only from Codeman's own pop-out button. A `window.open` from page script opens only Codeman's file and download windows, without taking keyboard focus, at most 3 at once and then 1 per second. Only Codeman's own pop-out pages become app windows (see Decisions); when the app refuses one, Codeman shows a toast. Each pop-out opens a step down and to the right of the window in use, never exactly on top of another one. A web tab's *Open in new tab* opens the dashboard in your default browser, as it would from a browser tab. |
|
||||
| **Links** | On Codeman's own pages (the dashboard and session windows), a link to another site opens in your default browser, also on `⌘`-click or a middle click. Pages can send at most 3 links to the browser at once, then 1 per second. Inside a rendered HTML preview or a web tab, a plain link to another site does nothing, while one that asks for a new window (`target="_blank"`, `window.open`) opens in your default browser within the same budget (see Known limits). |
|
||||
| **Downloads** | Codeman's Download links, and downloads Codeman opens in a new window, save the file to `~/Downloads` whatever its type, and a toast in Codeman names the file. Files the web view cannot display are saved the same way. |
|
||||
| **A page that stops** | When the web content process of a window ends (a WebKit crash, or macOS taking the process back under memory pressure), the window loads its page again instead of staying blank. A second time within 30 seconds, the main window goes back to the connect screen and a pop-out closes, so a page that cannot stay up never becomes a reload loop. |
|
||||
| **Apple logo** | On a MacBook Pro with a PROLED XDR display, the lit Apple logo on the lid says what the agents are doing. **View > Blink Apple Logo** is the one switch, off until you turn it on. The more the logo moves, the more it needs you: it breathes (a slow fade out and back in) while agents work, blinks every two seconds for a yellow tab and flashes three times, then rests, for a red one. Each state can take another style under **View > Apple Logo Blink Styles**: Off, Breathe, Calm, Slow, Wink, Heartbeat, Fast, or Alarm. Picking a style turns the switch on, and turning the switch on with every state off brings back the recommended three (Breathe, Calm, Alarm). When several states hold, the most urgent one with a style shows: red, then yellow, then work. Styles chosen in 1.50.0 are kept, with the switch on if any of them was. The menu only exists on a Mac with that logo. No password is needed. Shell tabs do not count. The app asks the server every two seconds, and a change has to hold for three seconds before the logo follows it, so an agent between two turns does not flicker it. It keeps working while the window is hidden, and with any Codeman server. The logo moves on its own hardware fades, the ones [LogoLight](https://github.com/Ark0N/LogoLight) uses, so a blink writes no setting, and a logo you switched off yourself stays off. LogoLight (1.3 or later) steps aside while Codeman shows its agents on the logo, and takes the logo back afterwards, with whatever it showed before; while an older LogoLight runs, Codeman leaves the logo to it. While the app is closed nothing blinks. With the lid closed it just goes on while the Mac stays awake on its power adapter (**Keep This Mac Awake > With the Lid Closed**, or an external display): macOS keeps the logo dark under a closed lid, so the app tells the logo the lid is open and the keyboard that it is closed, which stays dark, as LogoLight's *Lit with Lid Closed* does. The light sensor is covered then, so the logo glows as it would in a dark room. The line under **Apple Logo Blink Styles** says what the closed lid did last (blinking, or why not). On battery, and while the display only sleeps with the lid open, the blink pauses and writes nothing. |
|
||||
| **Keep awake** | **Codeman > Keep This Mac Awake** keeps the Mac from going to sleep while Codeman's agents work on it: **While Agents Work** (an agent at work, and for 5 minutes after the last one stopped, so the gap between two turns or a reply from your phone does not let it drop off), or **Always** (while the app is open). Off until you choose. Only for a Codeman on this Mac (`127.0.0.1`, `localhost`, or one of this Mac's own addresses); for a server on another machine the menu says so. The display still sleeps. No password is needed anywhere: the app holds a power assertion of its own, which macOS shows in Activity Monitor and in `pmset -g assertions` as *Codeman keeps this Mac awake while its agents work*, and which ends with the app, a crash or a Force Quit included. On a MacBook, **Only When Plugged In** (on by default) pauses it on battery, and **With the Lid Closed** keeps a closed MacBook awake as well: while it holds, the app has macOS's sleep-on-lid-close turned off (see Decisions), and turns it back on when it lets go, quits or crashes. The lid is never kept awake on battery, whatever the settings: unplugged with the lid closed, the Mac goes to sleep. A line at the bottom of the menu says what it does right now: whether the lid is covered, that it is left to macOS while an external display is connected (a docked MacBook stays awake with its lid closed by macOS's own doing), and if the Mac slept under the lid all the same, until when. Codeman 1.50.1 kept the lid awake through a small root helper, behind the administrator password. Nothing uses that helper any more, and where it is still installed the menu has **Remove the Old Lid Helper…** (the one item that asks for the password). It lives in the app, so it ends when the app quits: Codeman keeps running as a LaunchAgent, but nothing keeps the Mac awake then. That is why, while it watches a Codeman on this Mac, closing the Codeman window hides the app instead of quitting it, as Cmd+H does, also while it is paused (on battery, say), since it carries on by itself: a click on its Dock icon brings it back, and only Cmd+Q (or Quit from the Dock) ends it. With no server open, or one on another machine, closing the window quits. |
|
||||
| **Apple logo** | On a MacBook Pro with a PROLED XDR display, the lit Apple logo on the lid says what the agents are doing. **View > Blink Apple Logo** is the one switch, off until you turn it on. The more the logo moves, the more it needs you: it breathes (a slow fade out and back in) while agents work, blinks every two seconds for a yellow tab and flashes three times, then rests, for a red one. Each state can take another style under **View > Apple Logo Blink Styles**: Off, Breathe, Calm, Slow, Wink, Heartbeat, Fast, or Alarm. Picking a style turns the switch on, and turning the switch on with every state off brings back the recommended three (Breathe, Calm, Alarm). When several states hold, the most urgent one with a style shows: red, then yellow, then work. Styles chosen in 1.50.0 are kept, with the switch on if any of them was. The menu only exists on a Mac with that logo. No password is needed. Shell tabs do not count. The app asks the server every two seconds, and a change has to hold for three seconds before the logo follows it, so an agent between two turns does not flicker it. It keeps working while the window is hidden, and with any Codeman server: with several tabs open it shows the most urgent state of all of them together, so a red tab on any server flashes it. The logo moves on its own hardware fades, the ones [LogoLight](https://github.com/Ark0N/LogoLight) uses, so a blink writes no setting, and a logo you switched off yourself stays off. LogoLight (1.3 or later) steps aside while Codeman shows its agents on the logo, and takes the logo back afterwards, with whatever it showed before; while an older LogoLight runs, Codeman leaves the logo to it. While the app is closed nothing blinks. With the lid closed it just goes on while the Mac stays awake on its power adapter (**Keep This Mac Awake > With the Lid Closed**, or an external display): macOS keeps the logo dark under a closed lid, so the app tells the logo the lid is open and the keyboard that it is closed, which stays dark, as LogoLight's *Lit with Lid Closed* does. The light sensor is covered then, so the logo glows as it would in a dark room. The line under **Apple Logo Blink Styles** says what the closed lid did last (blinking, or why not). On battery, and while the display only sleeps with the lid open, the blink pauses and writes nothing. |
|
||||
| **Keep awake** | **Codeman > Keep This Mac Awake** keeps the Mac from going to sleep while Codeman's agents work on it: **While Agents Work** (an agent at work, and for 5 minutes after the last one stopped, so the gap between two turns or a reply from your phone does not let it drop off), or **Always** (while the app is open). Off until you choose. It watches the Codeman on this Mac among the open tabs (the tab in front when that is one). Only for a Codeman on this Mac (`127.0.0.1`, `localhost`, or one of this Mac's own addresses); for a server on another machine the menu says so. The display still sleeps. No password is needed anywhere: the app holds a power assertion of its own, which macOS shows in Activity Monitor and in `pmset -g assertions` as *Codeman keeps this Mac awake while its agents work*, and which ends with the app, a crash or a Force Quit included. On a MacBook, **Only When Plugged In** (on by default) pauses it on battery, and **With the Lid Closed** keeps a closed MacBook awake as well: while it holds, the app has macOS's sleep-on-lid-close turned off (see Decisions), and turns it back on when it lets go, quits or crashes. The lid is never kept awake on battery, whatever the settings: unplugged with the lid closed, the Mac goes to sleep. A line at the bottom of the menu says what it does right now: whether the lid is covered, that it is left to macOS while an external display is connected (a docked MacBook stays awake with its lid closed by macOS's own doing), and if the Mac slept under the lid all the same, until when. Codeman 1.50.1 kept the lid awake through a small root helper, behind the administrator password. Nothing uses that helper any more, and where it is still installed the menu has **Remove the Old Lid Helper…** (the one item that asks for the password). It lives in the app, so it ends when the app quits: Codeman keeps running as a LaunchAgent, but nothing keeps the Mac awake then. That is why, while it watches a Codeman on this Mac, closing the Codeman window hides the app instead of quitting it, as Cmd+H does, also while it is paused (on battery, say), since it carries on by itself: a click on its Dock icon brings it back, and only Cmd+Q (or Quit from the Dock) ends it. With no server open, or one on another machine, closing the window quits. |
|
||||
| **Window** | Size, position and full-screen state are remembered. A saved window that hangs off the screen it opens on (it was last on a larger display that is gone, say) is pulled back on and shrunk to fit; one whose title bar is on no screen at all opens at the default size instead. Clicking the Dock icon brings back a minimized window. |
|
||||
|
||||
## Build (on a Mac)
|
||||
@@ -73,7 +75,8 @@ the macOS version in `macos/Info.plist` (`LSMinimumSystemVersion`, 11.3), and
|
||||
takes the binary from where cargo says it wrote it, so `CARGO_TARGET_DIR` and a
|
||||
cargo config's `build.target-dir` work.
|
||||
|
||||
Settings live in `~/Library/Application Support/Codeman/desktop.json`; passwords
|
||||
Settings live in `~/Library/Application Support/Codeman/desktop.json` (with the
|
||||
tabs to open again: their servers, names, colours and which was in front); passwords
|
||||
in the Keychain under *Codeman Desktop*, one item per username and server. A
|
||||
`desktop.json` the app cannot read or parse is moved aside, never overwritten:
|
||||
to `desktop.json.corrupt`, or to the first free name of `desktop.json.corrupt.1`
|
||||
@@ -99,6 +102,29 @@ the page logged in. Using the crates directly is also smaller.
|
||||
the JavaScript dialog methods and the authentication-challenge method to the
|
||||
classes of wry's own delegates, so wry stays an unmodified crates.io dependency.
|
||||
|
||||
**One window, a web view per tab.** The tab strip (`assets/tabs.html`) is a
|
||||
web view of its own across the top of the window, and each tab's pages sit
|
||||
below it, the one in front visible and the others hidden but loaded
|
||||
(`src/tabs.rs` holds the pure half: names, colours, order, the state the strip
|
||||
and the overview are sent). A tab shows the connect page until its server's
|
||||
page commits: that page loads in a second, hidden web view behind it, so the
|
||||
connect page keeps its status line and Cancel while the server loads, and the
|
||||
load can be abandoned without a blank tab. The strip and the overview listen to
|
||||
their own page only (`policy::parse_strip_ipc`, `parse_overview_ipc`) and
|
||||
navigate nowhere else, and a session id from the overview goes into Codeman's
|
||||
page only when it is made of the characters Codeman's ids are.
|
||||
|
||||
**A data store per server.** Codeman's login cookie has the same name on every
|
||||
port, and cookies are not told apart by port, so two servers on one machine in
|
||||
one store would keep logging each other out. On macOS 14 and later each
|
||||
server's pages (its tab and its pop-outs) use a WebKit data store of their own,
|
||||
named by a hash of the server's address (`tabs::store_id`), so it is the same
|
||||
store at every launch. The one exception is the server used last before tabs
|
||||
existed: it keeps WebKit's default store, and with it the local storage where
|
||||
Codeman keeps its per-device settings (every other server starts those afresh
|
||||
once). Before a connect only that server's cookies are removed from its store,
|
||||
never another tab's.
|
||||
|
||||
**What a page may ask of the app** (all in `src/policy.rs`, unit-tested):
|
||||
|
||||
- Codeman shows content it did not write on its own origin: rendered HTML files
|
||||
@@ -136,8 +162,11 @@ classes of wry's own delegates, so wry stays an unmodified crates.io dependency.
|
||||
relay 401s from content Codeman did not write. Only such a challenge can
|
||||
send the user back to the connect screen. WebKit is handed the login without
|
||||
persistence, so it keeps no copy: every challenge gets the current login,
|
||||
and one from before a Switch Server is never replayed.
|
||||
- Each connect starts by clearing the app's cookies (never local storage).
|
||||
and one from before another connect is never replayed. Each tab hands over
|
||||
a login of its own, and a challenge goes to the tab whose server holds the
|
||||
URL that got the 401 (the deepest base path, when two servers share an
|
||||
origin behind one proxy), so one tab never answers for another.
|
||||
- Each connect starts by clearing that server's cookies (never local storage).
|
||||
Codeman checks its session cookie before the `Authorization` header, so an
|
||||
earlier user's cookie would otherwise win over the new login.
|
||||
- Microphone and camera requests prompt per page. wry's default without a
|
||||
@@ -242,7 +271,7 @@ can write to the runtime folder. It asks `preflight` for the list like an instal
|
||||
does, and both pass `--no-admin`: that flag decides which agents count as
|
||||
installable, so without it on both the page could offer one the run refuses. The
|
||||
menu item is on the connect page because that is where the app may run things:
|
||||
from a Codeman page it leaves the page the way *Switch Server* does.
|
||||
from a Codeman page it opens in a new tab, as New Server Tab does.
|
||||
|
||||
**Terminal stays for what the app cannot do.** The route with Homebrew asks for
|
||||
the administrator password on a terminal, the Xcode tools arrive as a system
|
||||
|
||||
@@ -1636,13 +1636,20 @@
|
||||
els.fullscreen.checked = !!msg.startFullscreen;
|
||||
els.version.textContent = 'Codeman Desktop ' + (msg.version || '');
|
||||
renderRecent();
|
||||
if (state.servers[0]) choose(state.servers[0]);
|
||||
// A server tab opened again at launch names its server (target), and
|
||||
// connects to it by itself when connectNow says so; any other tab
|
||||
// shows the server used last.
|
||||
var target = typeof msg.target === 'string' && msg.target ? msg.target : '';
|
||||
var targeted = target ? (state.servers.filter(function (s) { return s.url === target; })[0] || { url: target }) : null;
|
||||
var shown = targeted || state.servers[0];
|
||||
if (shown) choose(shown);
|
||||
var auto = !!(msg.autoConnect && !manual && !tooOld && !msg.starting && !msg.notice && state.servers[0]);
|
||||
// The tab of the server used last; This Mac on a first run. An
|
||||
// automatic connect opens Codeman without looking at this Mac first:
|
||||
// that look runs a few processes and asks the server once more, and
|
||||
// it is only needed when the connect fails, which then asks for it.
|
||||
selectTab(state.servers[0] && !isLocalUrl(state.servers[0].url) ? 'remote' : 'local', auto);
|
||||
if (targeted) auto = !!(msg.connectNow && !tooOld && !msg.starting && !msg.notice);
|
||||
// The tab of that server; This Mac on a first run. An automatic
|
||||
// connect opens Codeman without looking at this Mac first: that look
|
||||
// runs a few processes and asks the server once more, and it is only
|
||||
// needed when the connect fails, which then asks for it.
|
||||
selectTab(shown && !isLocalUrl(shown.url) ? 'remote' : 'local', auto);
|
||||
if (msg.starting) {
|
||||
setBusy(true, false);
|
||||
setStatus('busy', 'Starting Codeman on this Mac…', msg.notice || '');
|
||||
|
||||
@@ -0,0 +1,373 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>All servers</title>
|
||||
<style>
|
||||
/* All servers (Cmd+0): one card per server tab, what needs you first. The
|
||||
native side sends the whole list, already ordered, on every change. */
|
||||
:root { color-scheme: dark; }
|
||||
* { box-sizing: border-box; }
|
||||
html { min-height: 100%; background: #0b0c0f; }
|
||||
body {
|
||||
margin: 0; min-height: 100%; overflow-x: hidden; background: #0b0c0f; color: #e8eaed;
|
||||
font: 13px/1.4 -apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, sans-serif;
|
||||
-webkit-user-select: none; user-select: none; cursor: default;
|
||||
}
|
||||
main { padding: 22px 28px 28px; }
|
||||
header { display: flex; align-items: baseline; flex-wrap: wrap; column-gap: 14px; row-gap: 4px; margin-bottom: 18px; }
|
||||
h1 { margin: 0; font-size: 20px; font-weight: 650; letter-spacing: -0.01em; }
|
||||
#summary { font-size: 13px; color: #8b9099; }
|
||||
#summary .needs { color: #fca5a5; }
|
||||
#summary .waiting { color: #fcd34d; }
|
||||
#grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(300px, 100%), 1fr)); gap: 18px; align-items: stretch; }
|
||||
|
||||
button { font: inherit; color: inherit; margin: 0; cursor: pointer; -webkit-user-select: none; user-select: none; }
|
||||
button:focus-visible { outline: 2px solid #3b82f6; outline-offset: 2px; }
|
||||
|
||||
.card {
|
||||
--c: #94a3b8;
|
||||
display: flex; flex-direction: column; min-width: 0; min-height: 236px; padding-top: 3px;
|
||||
border: 1px solid #23252b; border-radius: 12px; background: #121316;
|
||||
box-shadow: inset 0 3px 0 var(--c);
|
||||
}
|
||||
.card.urgent { border-color: rgba(248,113,113,0.45); }
|
||||
.card.offline { border-style: dashed; border-color: #30333b; background: #0f1013; box-shadow: inset 0 3px 0 #30333b; }
|
||||
.card.slim { min-height: 0; align-self: start; }
|
||||
|
||||
.head {
|
||||
display: flex; align-items: flex-start; gap: 10px; width: 100%; padding: 11px 16px 10px;
|
||||
border: 0; border-radius: 9px 9px 0 0; background: transparent; text-align: left;
|
||||
}
|
||||
.head:hover .name { text-decoration: underline; text-decoration-color: #3a3d45; text-underline-offset: 3px; }
|
||||
.head:focus-visible { outline-offset: -2px; }
|
||||
.title { flex: 1; min-width: 0; }
|
||||
.name { display: block; font-size: 15px; font-weight: 650; line-height: 1.35; color: #e8eaed; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.card.offline .name { color: #8b9099; }
|
||||
.url { display: block; margin-top: 2px; font-size: 12px; color: #8b9099; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.key { flex: none; padding-top: 2px; font-size: 12px; color: #6b7079; }
|
||||
|
||||
.body { flex: 1; min-height: 0; padding: 0 10px; }
|
||||
.row {
|
||||
display: flex; align-items: center; gap: 9px; width: 100%; padding: 7px 8px; margin: 0 0 3px;
|
||||
border: 0; border-radius: 8px; background: transparent; font-size: 12.5px; line-height: 18px; text-align: left;
|
||||
}
|
||||
.row:hover { background: #1a1c21; }
|
||||
.row.needs { background: rgba(248,113,113,0.10); }
|
||||
.row.needs:hover { background: rgba(248,113,113,0.16); }
|
||||
.row.waiting { background: rgba(251,191,36,0.07); }
|
||||
.row.waiting:hover { background: rgba(251,191,36,0.12); }
|
||||
.mark { flex: none; display: flex; align-items: center; justify-content: center; width: 18px; height: 18px; }
|
||||
.mark::before { content: ""; display: block; }
|
||||
.row.needs .mark { border-radius: 9px; background: #f87171; color: #2a0707; font-weight: 700; font-size: 11px; line-height: 18px; }
|
||||
.row.needs .mark::before { display: none; }
|
||||
.row.waiting .mark::before { width: 9px; height: 9px; border-radius: 50%; background: #fbbf24; }
|
||||
.row.working .mark::before {
|
||||
width: 11px; height: 11px; border-radius: 50%; border: 2px solid #60a5fa; border-right-color: transparent;
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
.row.idle .mark::before { width: 8px; height: 8px; border-radius: 50%; background: #3a3d45; }
|
||||
.sname { flex: 0 1 auto; min-width: 0; max-width: 55%; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.stext { flex: 1 1 0; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #8b9099; }
|
||||
.row.needs .stext { color: #fca5a5; }
|
||||
.row.waiting .stext { color: #fcd34d; }
|
||||
.row.idle .stext { color: #6b7079; }
|
||||
.more { padding: 3px 8px 0; font-size: 12px; color: #6b7079; }
|
||||
.note { display: flex; align-items: center; gap: 9px; padding: 4px 6px; font-size: 12.5px; color: #8b9099; }
|
||||
.note.warn { color: #fcd34d; }
|
||||
|
||||
.foot { display: flex; align-items: center; gap: 10px; margin-top: 10px; padding: 10px 16px 14px; border-top: 1px solid #1d1f24; }
|
||||
.meta { flex: 1; min-width: 0; font-size: 12px; color: #6b7079; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.action {
|
||||
flex: none; height: 28px; padding: 0 12px; border: 1px solid #30333b; border-radius: 7px;
|
||||
background: #16181d; color: #e8eaed; font-weight: 600; font-size: 12px;
|
||||
}
|
||||
.action:hover { background: #1d2026; border-color: #3a3d45; }
|
||||
.action.urgent { border-color: #ef4444; background: #ef4444; color: #ffffff; }
|
||||
.action.urgent:hover { border-color: #dc2626; background: #dc2626; }
|
||||
|
||||
.add {
|
||||
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px;
|
||||
min-height: 236px; padding: 0; border: 1.5px dashed #30333b; border-radius: 12px;
|
||||
background: transparent; color: #8b9099;
|
||||
}
|
||||
.add:hover { border-color: #3a3d45; color: #c9ccd2; }
|
||||
.add-ico { width: 40px; height: 40px; border-radius: 12px; border: 1.5px dashed #3a3d45; display: flex; align-items: center; justify-content: center; }
|
||||
.add-label { font-size: 13px; font-weight: 600; }
|
||||
.add-key { font-size: 12px; color: #6b7079; }
|
||||
|
||||
.spin {
|
||||
flex: none; width: 14px; height: 14px; border-radius: 50%;
|
||||
border: 2px solid #30333b; border-top-color: #60a5fa; animation: spin 0.9s linear infinite;
|
||||
}
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.row.working .mark::before, .spin { animation: none; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<header>
|
||||
<h1>All servers</h1>
|
||||
<span id="summary"></span>
|
||||
</header>
|
||||
<div id="grid"></div>
|
||||
</main>
|
||||
<script>
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var FALLBACK_COLOR = '#94a3b8';
|
||||
var COLOR_RE = /^#[0-9a-fA-F]{6}$/;
|
||||
var MAX_ROWS = 4;
|
||||
var STATES = ['needs', 'waiting', 'working', 'idle'];
|
||||
var SVG_NS = 'http://www.w3.org/2000/svg';
|
||||
|
||||
var grid = document.getElementById('grid');
|
||||
var summary = document.getElementById('summary');
|
||||
|
||||
function post(msg) { try { window.ipc.postMessage(JSON.stringify(msg)); } catch (e) { /* not in the app */ } }
|
||||
|
||||
// Names, URLs, versions and session texts come from servers: they are only
|
||||
// ever set as text, and a colour only after it passed the #rrggbb check.
|
||||
function str(v) { return typeof v === 'string' ? v : ''; }
|
||||
function color(v) { return typeof v === 'string' && COLOR_RE.test(v) ? v : FALLBACK_COLOR; }
|
||||
function count(v) {
|
||||
var n = Math.floor(Number(v));
|
||||
return isFinite(n) && n > 0 ? n : 0;
|
||||
}
|
||||
function shortcut(v) {
|
||||
var n = Number(v);
|
||||
return n >= 1 && n <= 9 && Math.floor(n) === n ? n : null;
|
||||
}
|
||||
function plural(n, one, many) { return n + ' ' + (n === 1 ? one : many); }
|
||||
|
||||
function normServer(s) {
|
||||
if (!s || typeof s !== 'object') return null;
|
||||
var tab = Number(s.tab);
|
||||
if (!isFinite(tab)) return null;
|
||||
var c = s.counts && typeof s.counts === 'object' ? s.counts : {};
|
||||
var sessions = [];
|
||||
(Array.isArray(s.sessions) ? s.sessions : []).forEach(function (x) {
|
||||
if (!x || typeof x !== 'object') return;
|
||||
sessions.push({
|
||||
id: str(x.id),
|
||||
name: str(x.name),
|
||||
state: STATES.indexOf(x.state) >= 0 ? x.state : 'idle',
|
||||
text: str(x.text)
|
||||
});
|
||||
});
|
||||
return {
|
||||
tab: tab,
|
||||
name: str(s.name),
|
||||
color: color(s.color),
|
||||
url: str(s.url),
|
||||
local: s.local === true,
|
||||
key: shortcut(s.key),
|
||||
version: str(s.version),
|
||||
kind: s.kind === 'connect' || s.kind === 'loading' ? s.kind : 'server',
|
||||
offline: s.offline === true,
|
||||
refused: s.refused === true,
|
||||
sessions: sessions,
|
||||
counts: {
|
||||
needsYou: count(c.needsYou),
|
||||
waiting: count(c.waiting),
|
||||
working: count(c.working),
|
||||
sessions: count(c.sessions)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function el(tag, cls, text) {
|
||||
var e = document.createElement(tag);
|
||||
if (cls) e.className = cls;
|
||||
if (text !== undefined) e.textContent = text;
|
||||
return e;
|
||||
}
|
||||
function button(cls, focusKey, text) {
|
||||
var b = el('button', cls, text);
|
||||
b.type = 'button';
|
||||
b.dataset.focus = focusKey;
|
||||
return b;
|
||||
}
|
||||
function plusIcon(size) {
|
||||
var s = document.createElementNS(SVG_NS, 'svg');
|
||||
s.setAttribute('width', String(size));
|
||||
s.setAttribute('height', String(size));
|
||||
s.setAttribute('viewBox', '0 0 16 16');
|
||||
s.setAttribute('fill', 'none');
|
||||
s.setAttribute('stroke', 'currentColor');
|
||||
s.setAttribute('stroke-width', '1.7');
|
||||
s.setAttribute('aria-hidden', 'true');
|
||||
var p = document.createElementNS(SVG_NS, 'path');
|
||||
p.setAttribute('d', 'M8 2.5v11M2.5 8h11');
|
||||
s.appendChild(p);
|
||||
return s;
|
||||
}
|
||||
|
||||
function renderSummary(servers) {
|
||||
var needs = 0, waiting = 0, working = 0, offline = 0;
|
||||
servers.forEach(function (s) {
|
||||
if (s.offline) { offline++; return; }
|
||||
needs += s.counts.needsYou;
|
||||
waiting += s.counts.waiting;
|
||||
working += s.counts.working;
|
||||
});
|
||||
var parts = [];
|
||||
if (needs) parts.push(el('span', 'needs', needs + (needs === 1 ? ' needs you' : ' need you')));
|
||||
if (waiting) parts.push(el('span', 'waiting', waiting + ' waiting'));
|
||||
if (working) parts.push(el('span', 'working', working + ' working'));
|
||||
if (offline) parts.push(el('span', 'offline', offline + ' offline'));
|
||||
if (!parts.length) parts.push(el('span', 'calm', 'Nothing needs you'));
|
||||
var out = [];
|
||||
parts.forEach(function (p, i) {
|
||||
if (i) out.push(document.createTextNode(' · '));
|
||||
out.push(p);
|
||||
});
|
||||
summary.replaceChildren.apply(summary, out);
|
||||
}
|
||||
|
||||
function sessionRow(s, x) {
|
||||
var row = button('row ' + x.state, 'row:' + s.tab + ':' + x.id);
|
||||
var mark = el('span', 'mark', x.state === 'needs' ? '!' : undefined);
|
||||
mark.setAttribute('aria-hidden', 'true');
|
||||
row.appendChild(mark);
|
||||
row.appendChild(el('span', 'sname', x.name || 'Untitled'));
|
||||
row.appendChild(el('span', 'stext', x.text));
|
||||
var said = { needs: 'needs you', waiting: 'waiting', working: 'working', idle: 'idle' }[x.state];
|
||||
row.setAttribute('aria-label', (x.name || 'Untitled') + ', ' + said + (x.text ? ': ' + x.text : ''));
|
||||
if (x.id) row.addEventListener('click', function () { post({ cmd: 'openSession', tab: s.tab, session: x.id }); });
|
||||
else row.disabled = true;
|
||||
return row;
|
||||
}
|
||||
|
||||
function card(s) {
|
||||
var c = el('section', 'card');
|
||||
c.style.setProperty('--c', s.color);
|
||||
var name = s.name || (s.kind === 'connect' ? 'New server tab' : 'Untitled');
|
||||
c.setAttribute('aria-label', name);
|
||||
|
||||
var head = button('head', 'head:' + s.tab);
|
||||
var title = el('span', 'title');
|
||||
title.appendChild(el('span', 'name', name));
|
||||
if (s.url) title.appendChild(el('span', 'url', s.url));
|
||||
head.appendChild(title);
|
||||
if (s.key) head.appendChild(el('span', 'key', '⌘' + s.key));
|
||||
head.addEventListener('click', function () { post({ cmd: 'open', tab: s.tab }); });
|
||||
c.appendChild(head);
|
||||
|
||||
var body = el('div', 'body');
|
||||
var meta = '';
|
||||
var action = button('action', 'act:' + s.tab, 'Open');
|
||||
var onAction = function () { post({ cmd: 'open', tab: s.tab }); };
|
||||
|
||||
if (s.kind === 'connect') {
|
||||
c.classList.add('slim');
|
||||
body.appendChild(el('div', 'note', 'Not connected yet'));
|
||||
} else if (s.kind === 'loading') {
|
||||
var note = el('div', 'note');
|
||||
note.appendChild(el('span', 'spin'));
|
||||
note.appendChild(document.createTextNode('Connecting…'));
|
||||
body.appendChild(note);
|
||||
} else if (s.offline) {
|
||||
c.classList.add('offline');
|
||||
body.appendChild(el('div', 'note', 'Not answering, the app keeps trying'));
|
||||
meta = s.version;
|
||||
action.textContent = 'Retry';
|
||||
onAction = function () { post({ cmd: 'retry', tab: s.tab }); };
|
||||
} else if (s.refused) {
|
||||
body.appendChild(el('div', 'note warn', 'The login was refused'));
|
||||
meta = s.version;
|
||||
} else {
|
||||
var shown = s.sessions.slice(0, MAX_ROWS);
|
||||
shown.forEach(function (x) { body.appendChild(sessionRow(s, x)); });
|
||||
var total = Math.max(s.counts.sessions, s.sessions.length);
|
||||
if (total > shown.length) body.appendChild(el('div', 'more', '+' + (total - shown.length) + ' more'));
|
||||
if (!total) body.appendChild(el('div', 'note', 'No sessions'));
|
||||
meta = plural(total, 'session', 'sessions') + (s.version ? ' · ' + s.version : '');
|
||||
if (s.counts.needsYou > 0) {
|
||||
c.classList.add('urgent');
|
||||
action.textContent = 'Answer';
|
||||
action.classList.add('urgent');
|
||||
// Answer goes straight to the first session that needs you, when the
|
||||
// list names it; else to the server.
|
||||
var first = s.sessions.filter(function (x) { return x.state === 'needs' && x.id; })[0];
|
||||
if (first) onAction = function () { post({ cmd: 'openSession', tab: s.tab, session: first.id }); };
|
||||
}
|
||||
}
|
||||
c.appendChild(body);
|
||||
|
||||
var foot = el('div', 'foot');
|
||||
foot.appendChild(el('span', 'meta', meta));
|
||||
action.setAttribute('aria-label', action.textContent + ' ' + name);
|
||||
action.addEventListener('click', onAction);
|
||||
foot.appendChild(action);
|
||||
c.appendChild(foot);
|
||||
return c;
|
||||
}
|
||||
|
||||
function addCard() {
|
||||
var b = button('add', 'new');
|
||||
b.setAttribute('aria-label', 'Add a server');
|
||||
var ico = el('span', 'add-ico');
|
||||
ico.appendChild(plusIcon(16));
|
||||
b.appendChild(ico);
|
||||
b.appendChild(el('span', 'add-label', 'Add a server'));
|
||||
b.appendChild(el('span', 'add-key', '⌘T'));
|
||||
b.addEventListener('click', function () { post({ cmd: 'new' }); });
|
||||
return b;
|
||||
}
|
||||
|
||||
var lastJson = null;
|
||||
|
||||
function render(servers) {
|
||||
// A state arrives every few seconds: the button that had the keyboard
|
||||
// focus gets it back in the new cards.
|
||||
var active = document.activeElement;
|
||||
var focusKey = active && active.dataset ? active.dataset.focus : '';
|
||||
renderSummary(servers);
|
||||
var cards = servers.map(card);
|
||||
cards.push(addCard());
|
||||
grid.replaceChildren.apply(grid, cards);
|
||||
if (focusKey) {
|
||||
var all = grid.querySelectorAll('[data-focus]');
|
||||
for (var i = 0; i < all.length; i++) {
|
||||
if (all[i].dataset.focus === focusKey) { all[i].focus({ preventScroll: true }); break; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function onNative(msg) {
|
||||
if (typeof msg === 'string') {
|
||||
try { msg = JSON.parse(msg); } catch (e) { return; }
|
||||
}
|
||||
if (!msg || typeof msg !== 'object' || msg.type !== 'state') return;
|
||||
var servers = [];
|
||||
var seen = new Set();
|
||||
(Array.isArray(msg.servers) ? msg.servers : []).forEach(function (raw) {
|
||||
var s = normServer(raw);
|
||||
if (!s || seen.has(s.tab)) return;
|
||||
seen.add(s.tab);
|
||||
servers.push(s);
|
||||
});
|
||||
var json = JSON.stringify(servers);
|
||||
if (json === lastJson) return;
|
||||
lastJson = json;
|
||||
render(servers);
|
||||
}
|
||||
|
||||
Object.defineProperty(window, '__codemanOverview', {
|
||||
value: Object.freeze({ onNative: onNative }),
|
||||
writable: false,
|
||||
configurable: false,
|
||||
enumerable: false
|
||||
});
|
||||
|
||||
render([]);
|
||||
post({ cmd: 'ready' });
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,604 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Codeman tabs</title>
|
||||
<style>
|
||||
/* The tab strip: a 38px web view across the top of the window, under the
|
||||
macOS traffic lights. One tab per Codeman server; the native side owns
|
||||
the tabs and sends the whole list on every change. */
|
||||
:root { color-scheme: dark; }
|
||||
* { box-sizing: border-box; }
|
||||
html, body { margin: 0; height: 100%; overflow: hidden; background: #141519; }
|
||||
body {
|
||||
font: 500 13px/1 -apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, sans-serif;
|
||||
color: #a3a8b1; cursor: default;
|
||||
-webkit-user-select: none; user-select: none;
|
||||
}
|
||||
#strip {
|
||||
position: relative; height: 38px; display: flex; align-items: flex-end; gap: 4px;
|
||||
padding: 0 8px 0 78px; overflow: hidden; background: #141519;
|
||||
}
|
||||
#strip.fullscreen { padding-left: 10px; }
|
||||
/* The bottom line is drawn under the tabs, so the active tab covers it and
|
||||
joins the page below. */
|
||||
#strip::after {
|
||||
content: ""; position: absolute; left: 0; right: 0; bottom: 0; height: 1px;
|
||||
background: #23252b; pointer-events: none; z-index: 1;
|
||||
}
|
||||
.icon-btn {
|
||||
align-self: center; flex: none; width: 28px; height: 28px; padding: 0; border: 0;
|
||||
border-radius: 7px; background: transparent; color: #8b9099;
|
||||
display: flex; align-items: center; justify-content: center; cursor: default; outline: none;
|
||||
}
|
||||
.icon-btn:hover { background: #1b1d22; color: #c9ccd2; }
|
||||
#overview { margin-right: 6px; }
|
||||
#overview.on { background: #2563eb; color: #ffffff; }
|
||||
#new { margin-left: 2px; }
|
||||
/* Empty strip moves the window, so some of it stays empty however many
|
||||
tabs there are. */
|
||||
#fill { flex: 1 0 48px; align-self: stretch; }
|
||||
|
||||
/* The tabs share the room evenly: 200px each, down to 72px; past that the
|
||||
row is clipped, never wrapped or scrolled. */
|
||||
#tabs {
|
||||
display: flex; align-items: flex-end; gap: 2px; flex: 0 1 auto; min-width: 0;
|
||||
height: 100%; overflow: hidden;
|
||||
}
|
||||
.tab {
|
||||
--c: #94a3b8;
|
||||
/* width, not only flex-basis: the row's own width is worked out from
|
||||
its tabs' widths, and flex-basis does not count there. */
|
||||
position: relative; flex: 0 1 auto; width: 200px; min-width: 72px; height: 31px;
|
||||
display: flex; align-items: center; gap: 8px; padding: 0 7px 0 10px;
|
||||
border-radius: 9px 9px 0 0; color: #a3a8b1; overflow: hidden;
|
||||
}
|
||||
.tab:hover { background: #1b1d22; }
|
||||
/* A thin line between two tabs neither in front nor under the pointer, so a
|
||||
badge at a tab's right end reads as that tab's and not the next one's. */
|
||||
.tab + .tab::before {
|
||||
content: ''; position: absolute; left: 0; top: 9px; bottom: 7px; width: 1px;
|
||||
background: #2c2f37; pointer-events: none;
|
||||
}
|
||||
.tab.active::before, .tab.active + .tab::before,
|
||||
.tab:hover::before, .tab:hover + .tab::before { display: none; }
|
||||
.tab.active {
|
||||
z-index: 2; background: #0b0c0f; color: #e8eaed;
|
||||
box-shadow: inset 0 2px 0 var(--c), inset 1px 0 0 #23252b, inset -1px 0 0 #23252b;
|
||||
}
|
||||
/* The tab button itself is a transparent layer over the whole tab, so a
|
||||
click anywhere on it is one target and the name, icon and badge stay
|
||||
plain text for the screen reader's label. */
|
||||
.hit {
|
||||
position: absolute; inset: 0; z-index: 0; margin: 0; padding: 0; border: 0;
|
||||
background: transparent; border-radius: inherit; cursor: default; outline: none;
|
||||
}
|
||||
.ico { flex: none; display: flex; color: var(--c); }
|
||||
.tab.connect .ico { color: #60a5fa; }
|
||||
.name { flex: 1 1 auto; min-width: 0; line-height: 16px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.tab.offline .name { color: #6b7079; }
|
||||
.tab.renaming .name { display: none; }
|
||||
.rename {
|
||||
position: relative; z-index: 1; flex: 1 1 auto; min-width: 0; height: 21px; margin: 0;
|
||||
padding: 0 5px; border: 1px solid #3b82f6; border-radius: 5px; background: #0b0c0f;
|
||||
color: #e8eaed; font: inherit; outline: none; -webkit-user-select: text; user-select: text;
|
||||
}
|
||||
.badge { flex: none; display: none; }
|
||||
.badge.needs {
|
||||
display: block; min-width: 18px; height: 18px; padding: 0 6px; border-radius: 9px;
|
||||
background: #f87171; color: #2a0707; font: 700 11px/18px -apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, sans-serif;
|
||||
text-align: center; font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.badge.waiting { display: block; width: 9px; height: 9px; border-radius: 50%; background: #fbbf24; }
|
||||
.badge.working {
|
||||
display: block; width: 11px; height: 11px; border-radius: 50%;
|
||||
border: 2px solid #60a5fa; border-right-color: transparent; animation: spin 1s linear infinite;
|
||||
}
|
||||
.badge.offline { display: block; width: 10px; height: 10px; border-radius: 50%; border: 1.5px dashed #6b7079; }
|
||||
.spin {
|
||||
display: block; width: 12px; height: 12px; margin: 1.5px; border-radius: 50%;
|
||||
border: 2px solid #30333b; border-top-color: var(--c); animation: spin 0.9s linear infinite;
|
||||
}
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
.close {
|
||||
position: relative; z-index: 1; flex: none; width: 16px; height: 16px; padding: 0; border: 0;
|
||||
border-radius: 4px; background: transparent; color: #8b9099; cursor: default; outline: none;
|
||||
display: none; align-items: center; justify-content: center;
|
||||
}
|
||||
.tab:hover .close, .tab.active .close { display: flex; }
|
||||
.close:hover { background: #2a2d34; color: #e8eaed; }
|
||||
/* Only while a tab is dragged do the others slide aside. */
|
||||
#tabs.dragging .tab { transition: transform 150ms ease; }
|
||||
#tabs.dragging .tab.lifted { transition: none; z-index: 3; background: #1b1d22; }
|
||||
#tabs.dragging .tab.lifted.active { background: #0b0c0f; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.badge.working, .spin { animation: none; }
|
||||
#tabs.dragging .tab { transition: none; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="strip">
|
||||
<button id="overview" class="icon-btn" type="button" tabindex="-1" aria-label="All servers" aria-pressed="false" title="All servers (⌘0)">
|
||||
<svg width="15" height="15" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><rect x="1.5" y="1.5" width="5" height="5" rx="1.2"></rect><rect x="9.5" y="1.5" width="5" height="5" rx="1.2"></rect><rect x="1.5" y="9.5" width="5" height="5" rx="1.2"></rect><rect x="9.5" y="9.5" width="5" height="5" rx="1.2"></rect></svg>
|
||||
</button>
|
||||
<div id="tabs" role="tablist" aria-label="Servers"></div>
|
||||
<button id="new" class="icon-btn" type="button" tabindex="-1" aria-label="New server tab" title="New server tab (⌘T)">
|
||||
<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true"><path d="M8 2.5v11M2.5 8h11"></path></svg>
|
||||
</button>
|
||||
<div id="fill"></div>
|
||||
</div>
|
||||
<script>
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var FALLBACK_COLOR = '#94a3b8';
|
||||
var COLOR_RE = /^#[0-9a-fA-F]{6}$/;
|
||||
var MAX_NAME = 40;
|
||||
var DRAG_START_PX = 4;
|
||||
var SVG_NS = 'http://www.w3.org/2000/svg';
|
||||
|
||||
var strip = document.getElementById('strip');
|
||||
var tabsEl = document.getElementById('tabs');
|
||||
var overviewBtn = document.getElementById('overview');
|
||||
var newBtn = document.getElementById('new');
|
||||
|
||||
function post(msg) { try { window.ipc.postMessage(JSON.stringify(msg)); } catch (e) { /* not in the app */ } }
|
||||
|
||||
// Everything below arrives from the native side, and most of it was typed
|
||||
// on a server (names, URLs): it is only ever set as text or as a checked
|
||||
// attribute value, never parsed as markup or CSS.
|
||||
function str(v) { return typeof v === 'string' ? v : ''; }
|
||||
function color(v) { return typeof v === 'string' && COLOR_RE.test(v) ? v : FALLBACK_COLOR; }
|
||||
function count(v) {
|
||||
var n = Math.floor(Number(v));
|
||||
return isFinite(n) && n > 0 ? n : 0;
|
||||
}
|
||||
function shortcut(v) {
|
||||
var n = Number(v);
|
||||
return n >= 1 && n <= 9 && Math.floor(n) === n ? n : null;
|
||||
}
|
||||
|
||||
function normTab(t) {
|
||||
if (!t || typeof t !== 'object') return null;
|
||||
var id = Number(t.id);
|
||||
if (!isFinite(id)) return null;
|
||||
var st = t.status && typeof t.status === 'object' ? t.status : {};
|
||||
return {
|
||||
id: id,
|
||||
name: str(t.name),
|
||||
color: color(t.color),
|
||||
active: t.active === true,
|
||||
kind: t.kind === 'connect' || t.kind === 'loading' ? t.kind : 'server',
|
||||
local: t.local === true,
|
||||
url: str(t.url),
|
||||
key: shortcut(t.key),
|
||||
needs: count(st.needsYou),
|
||||
waiting: count(st.waiting),
|
||||
working: count(st.working),
|
||||
offline: st.offline === true
|
||||
};
|
||||
}
|
||||
|
||||
// One badge, by precedence: needs you, waiting, working, not answering.
|
||||
function badgeOf(t) {
|
||||
if (t.kind === 'connect') return '';
|
||||
if (t.needs) return 'needs';
|
||||
if (t.waiting) return 'waiting';
|
||||
if (t.working) return 'working';
|
||||
if (t.offline) return 'offline';
|
||||
return '';
|
||||
}
|
||||
|
||||
function statusWords(t) {
|
||||
if (t.kind === 'loading') return ['Connecting'];
|
||||
if (t.kind === 'connect') return [];
|
||||
var out = [];
|
||||
if (t.needs) out.push(t.needs + (t.needs === 1 ? ' needs you' : ' need you'));
|
||||
if (t.waiting) out.push(t.waiting + ' waiting');
|
||||
if (t.working) out.push(t.working + ' working');
|
||||
if (t.offline) out.push('Not answering');
|
||||
return out;
|
||||
}
|
||||
|
||||
function displayName(t) { return t.name || 'Untitled'; }
|
||||
|
||||
// ---- icons (fixed shapes from this file; no outside text goes in) ----
|
||||
function svg(size, width, parts) {
|
||||
var s = document.createElementNS(SVG_NS, 'svg');
|
||||
s.setAttribute('width', String(size));
|
||||
s.setAttribute('height', String(size));
|
||||
s.setAttribute('viewBox', '0 0 16 16');
|
||||
s.setAttribute('fill', 'none');
|
||||
s.setAttribute('stroke', 'currentColor');
|
||||
s.setAttribute('stroke-width', String(width));
|
||||
s.setAttribute('aria-hidden', 'true');
|
||||
parts.forEach(function (p) {
|
||||
var el = document.createElementNS(SVG_NS, p[0]);
|
||||
Object.keys(p[1]).forEach(function (k) { el.setAttribute(k, p[1][k]); });
|
||||
s.appendChild(el);
|
||||
});
|
||||
return s;
|
||||
}
|
||||
var ICONS = {
|
||||
local: function () {
|
||||
return svg(15, 1.5, [['rect', { x: '2.5', y: '3', width: '11', height: '7.5', rx: '1.2' }], ['path', { d: 'M1 13h14' }]]);
|
||||
},
|
||||
server: function () {
|
||||
return svg(15, 1.5, [
|
||||
['rect', { x: '2', y: '2', width: '12', height: '5', rx: '1.2' }],
|
||||
['rect', { x: '2', y: '9', width: '12', height: '5', rx: '1.2' }],
|
||||
['path', { d: 'M4.5 4.5h1M4.5 11.5h1' }]
|
||||
]);
|
||||
},
|
||||
connect: function () { return svg(15, 1.7, [['path', { d: 'M8 2.5v11M2.5 8h11' }]]); },
|
||||
loading: function () {
|
||||
var s = document.createElement('span');
|
||||
s.className = 'spin';
|
||||
return s;
|
||||
},
|
||||
close: function () { return svg(10, 1.6, [['path', { d: 'M3 3l10 10M13 3L3 13' }]]); }
|
||||
};
|
||||
function iconKind(t) {
|
||||
if (t.kind === 'connect' || t.kind === 'loading') return t.kind;
|
||||
return t.local ? 'local' : 'server';
|
||||
}
|
||||
|
||||
// ---- state ----
|
||||
var state = { tabs: [], overviewActive: false, fullscreen: false };
|
||||
var lastJson = '';
|
||||
var views = new Map(); // tab id -> the tab's elements and what they show
|
||||
var renaming = null; // { id, input, initial }
|
||||
var drag = null; // a press on a tab that may turn into a drag
|
||||
var pendingRender = false;
|
||||
var rendering = false;
|
||||
var suppressClick = false;
|
||||
|
||||
function createView(id) {
|
||||
var root = document.createElement('div');
|
||||
root.className = 'tab';
|
||||
root.setAttribute('role', 'presentation');
|
||||
root.dataset.id = String(id);
|
||||
var hit = document.createElement('button');
|
||||
hit.type = 'button';
|
||||
hit.className = 'hit';
|
||||
hit.tabIndex = -1;
|
||||
hit.setAttribute('role', 'tab');
|
||||
var ico = document.createElement('span');
|
||||
ico.className = 'ico';
|
||||
ico.setAttribute('aria-hidden', 'true');
|
||||
var name = document.createElement('span');
|
||||
name.className = 'name';
|
||||
name.setAttribute('aria-hidden', 'true');
|
||||
var badge = document.createElement('span');
|
||||
badge.className = 'badge';
|
||||
badge.setAttribute('aria-hidden', 'true');
|
||||
var close = document.createElement('button');
|
||||
close.type = 'button';
|
||||
close.className = 'close';
|
||||
close.tabIndex = -1;
|
||||
close.setAttribute('aria-label', 'Close tab');
|
||||
close.title = 'Close tab';
|
||||
close.appendChild(ICONS.close());
|
||||
root.appendChild(hit);
|
||||
root.appendChild(ico);
|
||||
root.appendChild(name);
|
||||
root.appendChild(badge);
|
||||
root.appendChild(close);
|
||||
var v = { id: id, root: root, hit: hit, ico: ico, name: name, badge: badge, close: close, icon: '', badgeKind: null, tab: null };
|
||||
views.set(id, v);
|
||||
return v;
|
||||
}
|
||||
|
||||
function updateView(v, t) {
|
||||
v.tab = t;
|
||||
var bk = badgeOf(t);
|
||||
var cls = 'tab' + (t.active ? ' active' : '') + (bk === 'offline' ? ' offline' : '') +
|
||||
(t.kind !== 'server' ? ' ' + t.kind : '') + (renaming && renaming.id === t.id ? ' renaming' : '');
|
||||
if (v.root.className !== cls) v.root.className = cls;
|
||||
v.root.style.setProperty('--c', t.color);
|
||||
var ik = iconKind(t);
|
||||
if (v.icon !== ik) {
|
||||
v.icon = ik;
|
||||
v.ico.replaceChildren(ICONS[ik]());
|
||||
}
|
||||
var label = displayName(t);
|
||||
if (v.name.textContent !== label) v.name.textContent = label;
|
||||
var btext = bk === 'needs' ? (t.needs > 99 ? '99+' : String(t.needs)) : '';
|
||||
if (v.badgeKind !== bk + btext) {
|
||||
v.badgeKind = bk + btext;
|
||||
v.badge.className = 'badge' + (bk ? ' ' + bk : '');
|
||||
v.badge.textContent = btext;
|
||||
}
|
||||
var words = statusWords(t);
|
||||
v.hit.setAttribute('aria-selected', t.active ? 'true' : 'false');
|
||||
v.hit.setAttribute('aria-label', [label].concat(words).join(', '));
|
||||
// The strip is too short for a hover card under it, so the native
|
||||
// tooltip carries the same lines.
|
||||
var lines = [label + (t.key ? ' ⌘' + t.key : '')];
|
||||
if (t.url) lines.push(t.url);
|
||||
v.hit.title = lines.concat(words).join('\n');
|
||||
}
|
||||
|
||||
function render() {
|
||||
if (drag && drag.active) { pendingRender = true; return; }
|
||||
pendingRender = false;
|
||||
rendering = true;
|
||||
strip.classList.toggle('fullscreen', state.fullscreen);
|
||||
overviewBtn.classList.toggle('on', state.overviewActive);
|
||||
overviewBtn.setAttribute('aria-pressed', state.overviewActive ? 'true' : 'false');
|
||||
var seen = new Set();
|
||||
state.tabs.forEach(function (t, i) {
|
||||
var v = views.get(t.id) || createView(t.id);
|
||||
updateView(v, t);
|
||||
seen.add(t.id);
|
||||
var at = tabsEl.children[i];
|
||||
if (at !== v.root) tabsEl.insertBefore(v.root, at || null);
|
||||
});
|
||||
views.forEach(function (v, id) {
|
||||
if (seen.has(id)) return;
|
||||
if (renaming && renaming.id === id) endRename('gone');
|
||||
v.root.remove();
|
||||
views.delete(id);
|
||||
});
|
||||
rendering = false;
|
||||
// Moving a tab in the row takes the focus from a rename under way: give it back.
|
||||
if (renaming && document.activeElement !== renaming.input) renaming.input.focus();
|
||||
}
|
||||
|
||||
function applyState(msg) {
|
||||
var seen = new Set();
|
||||
var tabs = [];
|
||||
(Array.isArray(msg.tabs) ? msg.tabs : []).forEach(function (raw) {
|
||||
var t = normTab(raw);
|
||||
if (!t || seen.has(t.id)) return;
|
||||
seen.add(t.id);
|
||||
tabs.push(t);
|
||||
});
|
||||
var next = { tabs: tabs, overviewActive: msg.overviewActive === true, fullscreen: msg.fullscreen === true };
|
||||
var json = JSON.stringify(next);
|
||||
if (json === lastJson && !pendingRender) return;
|
||||
lastJson = json;
|
||||
state = next;
|
||||
render();
|
||||
}
|
||||
|
||||
// ---- rename ----
|
||||
function startRename(id) {
|
||||
var v = views.get(id);
|
||||
if (!v || (drag && drag.active)) return;
|
||||
if (renaming) {
|
||||
if (renaming.id === id) { renaming.input.focus(); return; }
|
||||
endRename('commit');
|
||||
}
|
||||
var input = document.createElement('input');
|
||||
input.type = 'text';
|
||||
input.className = 'rename';
|
||||
input.maxLength = MAX_NAME;
|
||||
input.spellcheck = false;
|
||||
input.autocomplete = 'off';
|
||||
input.setAttribute('aria-label', 'Tab name');
|
||||
input.value = v.tab ? v.tab.name.slice(0, MAX_NAME) : '';
|
||||
renaming = { id: id, input: input, before: v.tab ? v.tab.name : '', initial: input.value.trim() };
|
||||
v.root.classList.add('renaming');
|
||||
v.root.insertBefore(input, v.badge);
|
||||
input.addEventListener('keydown', function (ev) {
|
||||
ev.stopPropagation();
|
||||
if (ev.key === 'Enter') { ev.preventDefault(); endRename('commit'); }
|
||||
else if (ev.key === 'Escape') { ev.preventDefault(); endRename('cancel'); }
|
||||
});
|
||||
input.addEventListener('blur', function () {
|
||||
if (rendering) return;
|
||||
if (renaming && renaming.input === input) endRename('commit');
|
||||
});
|
||||
// The keyboard reaches this field only while this web view is the first
|
||||
// responder, and the native side hands it back to the page below after
|
||||
// every other click on the strip: ask for it.
|
||||
post({ cmd: 'editing' });
|
||||
input.focus();
|
||||
input.select();
|
||||
}
|
||||
|
||||
// how: 'commit' (Enter, a click elsewhere), 'cancel' (Escape) or 'gone'
|
||||
// (the tab was closed). Every rename that ends on a tab still there posts
|
||||
// one rename, a cancelled or unchanged one with the name the tab had: the
|
||||
// native side takes that as "rename finished" and hands the keyboard back
|
||||
// to the page below.
|
||||
function endRename(how) {
|
||||
var r = renaming;
|
||||
if (!r) return;
|
||||
renaming = null;
|
||||
var name = r.input.value.trim().slice(0, MAX_NAME);
|
||||
r.input.remove();
|
||||
var v = views.get(r.id);
|
||||
if (v) v.root.classList.remove('renaming');
|
||||
if (how === 'gone') return;
|
||||
if (how === 'cancel' || name === r.initial) {
|
||||
post({ cmd: 'rename', id: r.id, name: r.before });
|
||||
return;
|
||||
}
|
||||
// Shown at once; an empty name is the default the native side picks.
|
||||
if (v && name) v.name.textContent = name;
|
||||
post({ cmd: 'rename', id: r.id, name: name });
|
||||
}
|
||||
|
||||
// ---- drag to reorder ----
|
||||
function beginDrag() {
|
||||
var roots = Array.prototype.slice.call(tabsEl.children);
|
||||
drag.roots = roots;
|
||||
drag.from = roots.indexOf(drag.root);
|
||||
if (drag.from < 0) { drag = null; return; }
|
||||
drag.rects = roots.map(function (r) { return r.getBoundingClientRect(); });
|
||||
var r0 = drag.rects[drag.from];
|
||||
var gap = roots.length > 1 ? drag.rects[1].left - drag.rects[0].right : 0;
|
||||
drag.step = r0.width + gap;
|
||||
drag.to = drag.from;
|
||||
drag.active = true;
|
||||
if (renaming) endRename('commit');
|
||||
try { drag.root.setPointerCapture(drag.pointerId); } catch (e) { /* the pointer is gone */ }
|
||||
tabsEl.classList.add('dragging');
|
||||
drag.root.classList.add('lifted');
|
||||
}
|
||||
|
||||
function moveDrag(dx) {
|
||||
var rects = drag.rects;
|
||||
var r0 = rects[drag.from];
|
||||
var minDx = rects[0].left - r0.left;
|
||||
var maxDx = rects[rects.length - 1].right - r0.right;
|
||||
dx = Math.max(minDx, Math.min(maxDx, dx));
|
||||
drag.root.style.transform = 'translateX(' + dx + 'px)';
|
||||
var centre = r0.left + r0.width / 2 + dx;
|
||||
var to = 0;
|
||||
for (var i = 0; i < rects.length; i++) {
|
||||
if (i !== drag.from && centre > rects[i].left + rects[i].width / 2) to++;
|
||||
}
|
||||
drag.to = to;
|
||||
drag.roots.forEach(function (r, i) {
|
||||
if (i === drag.from) return;
|
||||
var shift = 0;
|
||||
if (drag.from < to && i > drag.from && i <= to) shift = -drag.step;
|
||||
else if (to < drag.from && i >= to && i < drag.from) shift = drag.step;
|
||||
r.style.transform = shift ? 'translateX(' + shift + 'px)' : '';
|
||||
});
|
||||
}
|
||||
|
||||
function endDrag(commit) {
|
||||
var d = drag;
|
||||
drag = null;
|
||||
if (!d || !d.active) return;
|
||||
try { d.root.releasePointerCapture(d.pointerId); } catch (e) { /* already released */ }
|
||||
// The slide stops before the tabs move, so nothing animates back.
|
||||
tabsEl.classList.remove('dragging');
|
||||
d.root.classList.remove('lifted');
|
||||
d.roots.forEach(function (r) { r.style.transform = ''; });
|
||||
// The click that ends a drag is not a select.
|
||||
suppressClick = true;
|
||||
setTimeout(function () { suppressClick = false; }, 0);
|
||||
if (commit && d.to !== d.from) {
|
||||
var at = state.tabs.findIndex(function (t) { return t.id === d.id; });
|
||||
if (at >= 0) {
|
||||
var moved = state.tabs.splice(at, 1)[0];
|
||||
state.tabs.splice(d.to, 0, moved);
|
||||
lastJson = JSON.stringify(state);
|
||||
}
|
||||
post({ cmd: 'move', id: d.id, to: d.to });
|
||||
pendingRender = true;
|
||||
}
|
||||
if (pendingRender) render();
|
||||
}
|
||||
|
||||
function tabOf(target) {
|
||||
var root = target && target.closest ? target.closest('.tab') : null;
|
||||
return root && views.has(Number(root.dataset.id)) ? Number(root.dataset.id) : null;
|
||||
}
|
||||
function inside(target, sel) { return !!(target && target.closest && target.closest(sel)); }
|
||||
|
||||
// ---- events ----
|
||||
var middleDownOn = null;
|
||||
|
||||
document.addEventListener('mousedown', function (ev) {
|
||||
var t = ev.target;
|
||||
if (renaming && t !== renaming.input) endRename('commit');
|
||||
if (inside(t, 'input')) return;
|
||||
// The strip never takes the focus or starts a selection.
|
||||
ev.preventDefault();
|
||||
if (ev.button === 1) { middleDownOn = tabOf(t); return; }
|
||||
if (ev.button !== 0 || ev.ctrlKey) return;
|
||||
if (inside(t, '.tab, button')) return;
|
||||
// The second press of a double click zooms, as a title bar does. Decided
|
||||
// here, not on dblclick: the first press's window drag may keep WebKit
|
||||
// from ever seeing a dblclick.
|
||||
if (ev.detail === 2) post({ cmd: 'zoom' });
|
||||
if (ev.detail > 1) return;
|
||||
post({ cmd: 'drag' });
|
||||
});
|
||||
|
||||
// Middle click closes, as in a browser (auxclick is not in every WebKit).
|
||||
document.addEventListener('mouseup', function (ev) {
|
||||
if (ev.button !== 1) return;
|
||||
var id = tabOf(ev.target);
|
||||
if (id !== null && id === middleDownOn) post({ cmd: 'close', id: id });
|
||||
middleDownOn = null;
|
||||
});
|
||||
|
||||
document.addEventListener('dblclick', function (ev) {
|
||||
var t = ev.target;
|
||||
var id = tabOf(t);
|
||||
if (id !== null) {
|
||||
if (!inside(t, '.close, input')) startRename(id);
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
// WebKit's own menu (Reload, Inspect Element) never shows on the strip,
|
||||
// the rename field included; only a tab has a menu, the native one, and
|
||||
// not while its name is being typed.
|
||||
document.addEventListener('contextmenu', function (ev) {
|
||||
ev.preventDefault();
|
||||
var id = inside(ev.target, 'input') ? null : tabOf(ev.target);
|
||||
if (id !== null) post({ cmd: 'menu', id: id });
|
||||
});
|
||||
|
||||
tabsEl.addEventListener('click', function (ev) {
|
||||
if (suppressClick) { suppressClick = false; return; }
|
||||
if (ev.ctrlKey) return; // a Control-click is the right click: the menu answers it
|
||||
var id = tabOf(ev.target);
|
||||
if (id === null || inside(ev.target, 'input')) return;
|
||||
if (inside(ev.target, '.close')) post({ cmd: 'close', id: id });
|
||||
else post({ cmd: 'select', id: id });
|
||||
});
|
||||
|
||||
tabsEl.addEventListener('pointerdown', function (ev) {
|
||||
if (ev.button !== 0 || ev.ctrlKey || !ev.isPrimary) return;
|
||||
var id = tabOf(ev.target);
|
||||
if (id === null || inside(ev.target, '.close, input')) return;
|
||||
drag = { id: id, root: views.get(id).root, pointerId: ev.pointerId, startX: ev.clientX, active: false };
|
||||
});
|
||||
|
||||
document.addEventListener('pointermove', function (ev) {
|
||||
if (!drag || ev.pointerId !== drag.pointerId) return;
|
||||
var dx = ev.clientX - drag.startX;
|
||||
if (!drag.active) {
|
||||
if (Math.abs(dx) < DRAG_START_PX) return;
|
||||
beginDrag();
|
||||
if (!drag) return;
|
||||
}
|
||||
moveDrag(dx);
|
||||
});
|
||||
|
||||
document.addEventListener('pointerup', function (ev) {
|
||||
if (drag && ev.pointerId === drag.pointerId) endDrag(true);
|
||||
});
|
||||
document.addEventListener('pointercancel', function (ev) {
|
||||
if (drag && ev.pointerId === drag.pointerId) endDrag(false);
|
||||
});
|
||||
window.addEventListener('blur', function () { if (drag) endDrag(false); });
|
||||
|
||||
overviewBtn.addEventListener('click', function () { post({ cmd: 'overview' }); });
|
||||
newBtn.addEventListener('click', function () { post({ cmd: 'new' }); });
|
||||
|
||||
function onNative(msg) {
|
||||
if (typeof msg === 'string') {
|
||||
try { msg = JSON.parse(msg); } catch (e) { return; }
|
||||
}
|
||||
if (!msg || typeof msg !== 'object') return;
|
||||
if (msg.type === 'state') applyState(msg);
|
||||
else if (msg.type === 'rename') {
|
||||
var id = Number(msg.id);
|
||||
if (isFinite(id)) startRename(id);
|
||||
}
|
||||
}
|
||||
|
||||
Object.defineProperty(window, '__codemanTabs', {
|
||||
value: Object.freeze({ onNative: onNative }),
|
||||
writable: false,
|
||||
configurable: false,
|
||||
enumerable: false
|
||||
});
|
||||
|
||||
post({ cmd: 'ready' });
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -57,6 +57,10 @@ pub enum Poll {
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Session {
|
||||
#[serde(default)]
|
||||
id: String,
|
||||
#[serde(default)]
|
||||
name: Option<String>,
|
||||
#[serde(default)]
|
||||
status: String,
|
||||
#[serde(default)]
|
||||
@@ -80,11 +84,20 @@ fn count_working(body: &str) -> Option<u32> {
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Approval {
|
||||
#[serde(default)]
|
||||
kind: String,
|
||||
#[serde(default, rename = "acknowledgedAt")]
|
||||
#[serde(default)]
|
||||
acknowledged_at: Option<f64>,
|
||||
#[serde(default)]
|
||||
session_id: String,
|
||||
#[serde(default)]
|
||||
tool_name: Option<String>,
|
||||
#[serde(default)]
|
||||
tool_summary: Option<String>,
|
||||
#[serde(default)]
|
||||
message: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -108,6 +121,145 @@ fn read_alerts(body: &str) -> Option<(bool, bool)> {
|
||||
Some((waiting, needs_you))
|
||||
}
|
||||
|
||||
/// What one agent session is doing, most urgent first (`SessionState::rank`).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SessionState {
|
||||
/// Stopped on a permission or a question: a red tab.
|
||||
Needs,
|
||||
/// Finished, and nobody has looked yet: a yellow tab.
|
||||
Waiting,
|
||||
/// At work.
|
||||
Working,
|
||||
Idle,
|
||||
}
|
||||
|
||||
impl SessionState {
|
||||
pub fn rank(self) -> u8 {
|
||||
match self {
|
||||
SessionState::Needs => 0,
|
||||
SessionState::Waiting => 1,
|
||||
SessionState::Working => 2,
|
||||
SessionState::Idle => 3,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One agent session of a server, for the tab badges and the overview. `name`
|
||||
/// and `text` come from the server: the pages that show them treat them as
|
||||
/// text.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SessionRow {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub state: SessionState,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// Every agent session of a server and what it is doing. Shell tabs are left
|
||||
/// out, as for the logo.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Detail {
|
||||
pub sessions: Vec<SessionRow>,
|
||||
}
|
||||
|
||||
impl Detail {
|
||||
/// The same answer `Poller::poll` gives for this server.
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
pub fn activity(&self) -> Activity {
|
||||
let any = |state: SessionState| self.sessions.iter().any(|s| s.state == state);
|
||||
Activity {
|
||||
working: any(SessionState::Working),
|
||||
waiting: any(SessionState::Waiting),
|
||||
needs_you: any(SessionState::Needs),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum DetailPoll {
|
||||
Seen(Detail),
|
||||
Failed,
|
||||
/// 401 or 403: the login is refused (or must be changed first). Asking
|
||||
/// again would count against the login rate limit.
|
||||
Refused,
|
||||
/// 429: too many failed logins from this address, maybe other clients'.
|
||||
/// Worth asking again, much later.
|
||||
RateLimited,
|
||||
}
|
||||
|
||||
/// How long a server's text may be in a row of the overview, in characters.
|
||||
const MAX_ROW_TEXT: usize = 160;
|
||||
const MAX_ROW_NAME: usize = 80;
|
||||
/// How many sessions of one server are kept, so a server cannot make the app
|
||||
/// hold a list of any length.
|
||||
const MAX_SESSIONS: usize = 200;
|
||||
|
||||
/// Server text for a row: control characters out, whitespace runs folded,
|
||||
/// cut at `max` characters.
|
||||
fn row_text(raw: &str, max: usize) -> String {
|
||||
let folded = raw
|
||||
.split(|c: char| c.is_whitespace() || c.is_control())
|
||||
.filter(|w| !w.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
match folded.char_indices().nth(max) {
|
||||
Some((cut, _)) => format!("{}\u{2026}", &folded[..cut]),
|
||||
None => folded,
|
||||
}
|
||||
}
|
||||
|
||||
/// The detail of a server from its two answers: `GET api/sessions` and, when
|
||||
/// the server has it, `GET api/approvals` (None: an older server, no alerts).
|
||||
/// None when the sessions answer is not a list of sessions.
|
||||
pub fn read_detail(sessions_body: &str, approvals_body: Option<&str>) -> Option<Detail> {
|
||||
let (Sessions::Envelope { data: sessions } | Sessions::Bare(sessions)) =
|
||||
serde_json::from_str(sessions_body).ok()?;
|
||||
let approvals: Vec<Approval> = approvals_body
|
||||
.and_then(|body| serde_json::from_str::<ApprovalsAnswer>(body).ok())
|
||||
.map(|a| a.data.approvals)
|
||||
.unwrap_or_default();
|
||||
let rows = sessions
|
||||
.into_iter()
|
||||
.filter(|s| s.mode != "shell" && !s.id.is_empty())
|
||||
.take(MAX_SESSIONS)
|
||||
.map(|s| {
|
||||
let mine = || approvals.iter().filter(|a| a.session_id == s.id);
|
||||
let urgent = mine().find(|a| a.kind == "permission" || a.kind == "question");
|
||||
let waiting = mine().any(|a| a.kind == "idle" && a.acknowledged_at.is_none());
|
||||
let (state, text) = if let Some(a) = urgent {
|
||||
let text = match (a.kind.as_str(), &a.tool_name, &a.tool_summary, &a.message) {
|
||||
("permission", Some(tool), Some(summary), _) => format!("{tool}: {summary}"),
|
||||
("permission", Some(tool), None, _) => format!("Allow {tool}?"),
|
||||
(_, _, _, Some(message)) => message.clone(),
|
||||
("question", _, _, None) => "Has a question for you".to_string(),
|
||||
_ => "Needs your permission".to_string(),
|
||||
};
|
||||
(SessionState::Needs, text)
|
||||
} else if waiting {
|
||||
(SessionState::Waiting, "Finished, waiting for you".to_string())
|
||||
} else if s.status == "busy" {
|
||||
(SessionState::Working, "Working".to_string())
|
||||
} else {
|
||||
(SessionState::Idle, "Idle".to_string())
|
||||
};
|
||||
let name = s.name.as_deref().map(|n| row_text(n, MAX_ROW_NAME)).unwrap_or_default();
|
||||
let name = if name.is_empty() {
|
||||
s.id.chars().take(8).collect()
|
||||
} else {
|
||||
name
|
||||
};
|
||||
SessionRow {
|
||||
id: s.id,
|
||||
name,
|
||||
state,
|
||||
text: row_text(&text, MAX_ROW_TEXT),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
Some(Detail { sessions: rows })
|
||||
}
|
||||
|
||||
/// `name=value` out of a `Set-Cookie` header, for Codeman's session cookie.
|
||||
fn session_cookie(header: &str) -> Option<&str> {
|
||||
let pair = header.split(';').next()?.trim();
|
||||
@@ -215,6 +367,29 @@ impl Poller {
|
||||
(activity.waiting, activity.needs_you) = self.alerts;
|
||||
Poll::Seen(activity)
|
||||
}
|
||||
|
||||
/// Every agent session and what it is doing (`read_detail`), for a server
|
||||
/// tab's badges and the overview. Needs a poller made with `alerts`.
|
||||
pub fn detail(&mut self) -> DetailPoll {
|
||||
let url = self.sessions_url.clone();
|
||||
let sessions = match self.ask(&url) {
|
||||
Some((200, Some(body))) => body,
|
||||
Some((429, _)) => return DetailPoll::RateLimited,
|
||||
Some((s, _)) if refused(s) => return DetailPoll::Refused,
|
||||
_ => return DetailPoll::Failed,
|
||||
};
|
||||
let approvals = match self.approvals_url.clone() {
|
||||
Some(url) => match self.ask(&url) {
|
||||
Some((200, body)) => body,
|
||||
Some((429, _)) => return DetailPoll::RateLimited,
|
||||
Some((s, _)) if refused(s) => return DetailPoll::Refused,
|
||||
// An older server has no list; a failed read counts as none.
|
||||
_ => None,
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
read_detail(&sessions, approvals.as_deref()).map_or(DetailPoll::Failed, DetailPoll::Seen)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -462,4 +637,66 @@ mod tests {
|
||||
let server = Url::parse(&format!("http://127.0.0.1:{port}/")).unwrap();
|
||||
assert_eq!(Poller::new(&server, None, false).unwrap().poll(), Poll::Failed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detail_reads_every_agent_session_and_its_state() {
|
||||
let sessions = r#"{"success":true,"data":[
|
||||
{"id":"s1","name":"webshop","status":"busy","mode":"claude"},
|
||||
{"id":"s2","name":"billing","status":"idle","mode":"claude"},
|
||||
{"id":"s3","name":"docs","status":"idle","mode":"codex"},
|
||||
{"id":"s4","name":"shell","status":"busy","mode":"shell"},
|
||||
{"id":"s5","status":"idle","mode":"claude"},
|
||||
{"id":"s6","name":" two\n lines\u0007 ","status":"idle","mode":"claude"}]}"#;
|
||||
let approvals = r#"{"success":true,"data":{"approvals":[
|
||||
{"sessionId":"s2","kind":"permission","toolName":"Bash","toolSummary":"npm run migrate"},
|
||||
{"sessionId":"s3","kind":"idle"},
|
||||
{"sessionId":"s5","kind":"idle","acknowledgedAt":1},
|
||||
{"sessionId":"s6","kind":"question","message":"Which locale first?"}]}}"#;
|
||||
let detail = read_detail(sessions, Some(approvals)).unwrap();
|
||||
let states: Vec<(&str, SessionState, &str)> = detail
|
||||
.sessions
|
||||
.iter()
|
||||
.map(|s| (s.id.as_str(), s.state, s.text.as_str()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
states,
|
||||
[
|
||||
("s1", SessionState::Working, "Working"),
|
||||
("s2", SessionState::Needs, "Bash: npm run migrate"),
|
||||
("s3", SessionState::Waiting, "Finished, waiting for you"),
|
||||
("s5", SessionState::Idle, "Idle"),
|
||||
("s6", SessionState::Needs, "Which locale first?"),
|
||||
]
|
||||
);
|
||||
// A session with no name shows its id's start; server text is folded.
|
||||
assert_eq!(detail.sessions[3].name, "s5");
|
||||
assert_eq!(detail.sessions[4].name, "two lines");
|
||||
assert_eq!(
|
||||
detail.activity(),
|
||||
Activity {
|
||||
working: true,
|
||||
waiting: true,
|
||||
needs_you: true
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detail_without_approvals_and_from_junk() {
|
||||
let bare = r#"[{"id":"a","name":"x","status":"busy","mode":"claude"}]"#;
|
||||
let detail = read_detail(bare, None).unwrap();
|
||||
assert_eq!(detail.sessions.len(), 1);
|
||||
assert_eq!(detail.sessions[0].state, SessionState::Working);
|
||||
assert_eq!(read_detail("not json", None), None);
|
||||
assert_eq!(read_detail(r#"{"success":true,"data":{}}"#, None), None);
|
||||
// A junk approvals answer counts as none.
|
||||
assert_eq!(read_detail(bare, Some("<html>")).unwrap().sessions.len(), 1);
|
||||
let long = format!(
|
||||
r#"[{{"id":"a","name":"{}","status":"idle","mode":"claude"}}]"#,
|
||||
"n".repeat(500)
|
||||
);
|
||||
let name = &read_detail(&long, None).unwrap().sessions[0].name;
|
||||
assert_eq!(name.chars().count(), MAX_ROW_NAME + 1);
|
||||
assert!(name.ends_with('\u{2026}'));
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,10 @@ use std::borrow::Cow;
|
||||
use wry::http::{header::CONTENT_TYPE, Request, Response, StatusCode};
|
||||
|
||||
const CONNECT_HTML: &[u8] = include_bytes!("../assets/connect.html");
|
||||
/// The tab strip across the top of the window, and the overview of every
|
||||
/// server (tabs.rs).
|
||||
const TABS_HTML: &[u8] = include_bytes!("../assets/tabs.html");
|
||||
const OVERVIEW_HTML: &[u8] = include_bytes!("../assets/overview.html");
|
||||
const ICON_PNG: &[u8] = include_bytes!("../assets/icon.png");
|
||||
|
||||
/// The connect page loads nothing from outside the app.
|
||||
@@ -14,6 +18,8 @@ const CSP: &str = "default-src 'none'; script-src 'unsafe-inline'; style-src 'un
|
||||
pub fn respond(request: Request<Vec<u8>>) -> Response<Cow<'static, [u8]>> {
|
||||
let (body, mime): (&'static [u8], &str) = match request.uri().path() {
|
||||
"/" | "/index.html" => (CONNECT_HTML, "text/html; charset=utf-8"),
|
||||
"/tabs.html" => (TABS_HTML, "text/html; charset=utf-8"),
|
||||
"/overview.html" => (OVERVIEW_HTML, "text/html; charset=utf-8"),
|
||||
"/icon.png" => (ICON_PNG, "image/png"),
|
||||
_ => {
|
||||
return Response::builder()
|
||||
@@ -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}\\"));
|
||||
|
||||
@@ -11,6 +11,8 @@ use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const MAX_SERVERS: usize = 8;
|
||||
/// How many server tabs are saved for the next launch.
|
||||
pub const MAX_TABS: usize = 24;
|
||||
/// How many recovery copies of an unreadable config can sit side by side:
|
||||
/// `desktop.json.corrupt`, then `desktop.json.corrupt.1` to `.9`.
|
||||
const ASIDE_SLOTS: usize = 10;
|
||||
@@ -59,6 +61,50 @@ pub struct Config {
|
||||
/// make the whole file unreadable, which would cost the server list.
|
||||
#[serde(deserialize_with = "lenient_window")]
|
||||
pub window: Option<WindowFrame>,
|
||||
/// The server tabs to open again at the next launch, in strip order. Only
|
||||
/// tabs that belong to a server are kept. Read leniently, like `window`.
|
||||
#[serde(deserialize_with = "lenient_tabs")]
|
||||
pub tabs: Vec<TabEntry>,
|
||||
/// The tab that was in front, an index into `tabs`.
|
||||
#[serde(deserialize_with = "lenient_index")]
|
||||
pub active_tab: usize,
|
||||
/// The one server whose pages keep WebKit's default data store, so the
|
||||
/// local storage it had before tabs existed (Codeman's per-device settings)
|
||||
/// stays with it; every other server gets a store of its own
|
||||
/// (`tabs::store_id`). None: not decided yet, which the first launch with
|
||||
/// tabs does (the most recent server, or `Some("")` for none).
|
||||
#[serde(deserialize_with = "lenient_string", skip_serializing_if = "Option::is_none")]
|
||||
pub default_store_server: Option<String>,
|
||||
}
|
||||
|
||||
/// One saved tab: the server it is for, and what the user made of it.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TabEntry {
|
||||
pub url: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub color: Option<String>,
|
||||
}
|
||||
|
||||
fn lenient_tabs<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<TabEntry>, D::Error> {
|
||||
let value = serde_json::Value::deserialize(d)?;
|
||||
let list = value.as_array().cloned().unwrap_or_default();
|
||||
Ok(list
|
||||
.into_iter()
|
||||
.filter_map(|v| serde_json::from_value::<TabEntry>(v).ok())
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn lenient_index<'de, D: serde::Deserializer<'de>>(d: D) -> Result<usize, D::Error> {
|
||||
let value = serde_json::Value::deserialize(d)?;
|
||||
Ok(value.as_u64().and_then(|n| usize::try_from(n).ok()).unwrap_or(0))
|
||||
}
|
||||
|
||||
fn lenient_string<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
||||
let value = serde_json::Value::deserialize(d)?;
|
||||
Ok(value.as_str().map(str::to_owned))
|
||||
}
|
||||
|
||||
fn lenient_window<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<WindowFrame>, D::Error> {
|
||||
@@ -83,6 +129,9 @@ impl Default for Config {
|
||||
logo_blink: BlinkStyles::default(),
|
||||
keep_awake: keep_awake::Settings::default(),
|
||||
window: None,
|
||||
tabs: Vec::new(),
|
||||
active_tab: 0,
|
||||
default_store_server: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,6 +390,35 @@ impl Config {
|
||||
self.servers.retain(|s| !s.url.is_empty() && seen.insert(s.url.clone()));
|
||||
self.servers.truncate(MAX_SERVERS);
|
||||
self.window = self.window.and_then(WindowFrame::sanitized);
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
self.tabs.retain(|t| !t.url.is_empty() && seen.insert(t.url.clone()));
|
||||
self.tabs.truncate(MAX_TABS);
|
||||
for tab in &mut self.tabs {
|
||||
tab.name = tab.name.as_deref().and_then(crate::tabs::clean_name);
|
||||
tab.color = tab.color.take().filter(|c| crate::tabs::is_color(c));
|
||||
}
|
||||
if self.active_tab >= self.tabs.len() {
|
||||
self.active_tab = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Settle `default_store_server` once: the server used last keeps the data
|
||||
/// store it always had. True when it changed (the caller saves).
|
||||
pub fn settle_default_store(&mut self) -> bool {
|
||||
if self.default_store_server.is_some() {
|
||||
return false;
|
||||
}
|
||||
self.default_store_server = Some(self.servers.first().map(|s| s.url.clone()).unwrap_or_default());
|
||||
true
|
||||
}
|
||||
|
||||
/// The data store a server's pages use: None for WebKit's default one,
|
||||
/// else the server's own (`tabs::store_id`).
|
||||
pub fn store_for(&self, url: &str) -> Option<[u8; 16]> {
|
||||
match &self.default_store_server {
|
||||
Some(server) if server == url => None,
|
||||
_ => Some(crate::tabs::store_id(url)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Move (or add) a server to the top of the recent list. Returns the
|
||||
@@ -898,4 +976,83 @@ mod tests {
|
||||
};
|
||||
assert!(full.fitted_to(&tiny, MIN).unwrap().fullscreen);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tabs_round_trip_and_bad_values_are_dropped() {
|
||||
let dir = tmp_dir("tabs");
|
||||
let path = dir.join("desktop.json");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::write(
|
||||
&path,
|
||||
r##"{"servers":[],"activeTab":7,"tabs":[
|
||||
{"url":"http://127.0.0.1:3000/","name":" Mine ","color":"#A78BFA"},
|
||||
{"url":"http://127.0.0.1:3000/","name":"again"},
|
||||
{"url":"https://studio.example.ts.net/","color":"red;x"},
|
||||
{"url":""},
|
||||
42,
|
||||
{"name":"no url"}]}"##,
|
||||
)
|
||||
.unwrap();
|
||||
let (c, can_save) = Config::load_from(&path);
|
||||
assert!(can_save);
|
||||
assert_eq!(
|
||||
c.tabs,
|
||||
[
|
||||
TabEntry {
|
||||
url: "http://127.0.0.1:3000/".into(),
|
||||
name: Some("Mine".into()),
|
||||
color: Some("#A78BFA".into()),
|
||||
},
|
||||
TabEntry {
|
||||
url: "https://studio.example.ts.net/".into(),
|
||||
name: None,
|
||||
color: None,
|
||||
},
|
||||
]
|
||||
);
|
||||
// An index past the list falls back to the first tab.
|
||||
assert_eq!(c.active_tab, 0);
|
||||
c.save_to(&path).unwrap();
|
||||
let (again, _) = Config::load_from(&path);
|
||||
assert_eq!(again.tabs, c.tabs);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_tab_value_never_costs_the_server_list() {
|
||||
let dir = tmp_dir("badtabs");
|
||||
let path = dir.join("desktop.json");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::write(
|
||||
&path,
|
||||
r#"{"servers":[{"url":"http://a/"}],"tabs":"nope","activeTab":-3,"defaultStoreServer":5}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (c, can_save) = Config::load_from(&path);
|
||||
assert!(can_save);
|
||||
assert_eq!(c.servers.len(), 1);
|
||||
assert!(c.tabs.is_empty());
|
||||
assert_eq!(c.active_tab, 0);
|
||||
assert_eq!(c.default_store_server, None);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_server_used_last_keeps_the_default_store() {
|
||||
let mut c = Config::default();
|
||||
let _ = c.remember("http://old/", None, false);
|
||||
let _ = c.remember("http://recent/", None, false);
|
||||
assert!(c.settle_default_store());
|
||||
assert_eq!(c.default_store_server.as_deref(), Some("http://recent/"));
|
||||
// Decided once: a later connect does not move it.
|
||||
let _ = c.remember("http://old/", None, false);
|
||||
assert!(!c.settle_default_store());
|
||||
assert_eq!(c.store_for("http://recent/"), None);
|
||||
assert_eq!(c.store_for("http://old/"), Some(crate::tabs::store_id("http://old/")));
|
||||
// A first run with no server keeps no server on the default store.
|
||||
let mut fresh = Config::default();
|
||||
assert!(fresh.settle_default_store());
|
||||
assert_eq!(fresh.default_store_server.as_deref(), Some(""));
|
||||
assert!(fresh.store_for("http://x/").is_some());
|
||||
}
|
||||
}
|
||||
+103
-43
@@ -1165,14 +1165,33 @@ fn watch(logo: &impl Logo, marker: &Marker, styles: BlinkStyles, signals: &mut i
|
||||
}
|
||||
}
|
||||
|
||||
/// The one line the app writes to the child.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
/// The one line the app writes to the child: every open server tab, each with
|
||||
/// its login, and the styles. The logo shows the most urgent state of all of
|
||||
/// them together.
|
||||
#[derive(Serialize, Deserialize, PartialEq)]
|
||||
struct Connection {
|
||||
server: String,
|
||||
authorization: Option<String>,
|
||||
servers: Vec<Target>,
|
||||
styles: BlinkStyles,
|
||||
}
|
||||
|
||||
/// One server the child asks.
|
||||
#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
|
||||
pub struct Target {
|
||||
pub server: String,
|
||||
pub authorization: Option<String>,
|
||||
}
|
||||
|
||||
/// What several servers' agents do together: each state holds when it holds on
|
||||
/// any of them.
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
fn merged(all: &[Activity]) -> Activity {
|
||||
all.iter().fold(Activity::default(), |acc, a| Activity {
|
||||
working: acc.working || a.working,
|
||||
waiting: acc.waiting || a.waiting,
|
||||
needs_you: acc.needs_you || a.needs_you,
|
||||
})
|
||||
}
|
||||
|
||||
/// The app's side: the pipe to the child, which is all there is to it.
|
||||
#[derive(Default)]
|
||||
pub struct Watcher {
|
||||
@@ -1185,27 +1204,23 @@ impl Watcher {
|
||||
self.current.is_some()
|
||||
}
|
||||
|
||||
/// Watch this server with this login in these styles, or nothing. A child
|
||||
/// for anything else ends first: its pipe closes with the old value. It is
|
||||
/// back to normal well before the next child looks, which takes `SETTLE`.
|
||||
pub fn sync(&mut self, want: Option<(&str, Option<&str>, BlinkStyles)>) {
|
||||
let same = match (&self.current, want) {
|
||||
(Some((now, _)), Some((server, authorization, styles))) => {
|
||||
now.server == server && now.authorization.as_deref() == authorization && now.styles == styles
|
||||
}
|
||||
/// Watch these servers with their logins in these styles, or nothing (an
|
||||
/// empty list is nothing too). A child for anything else ends first: its
|
||||
/// pipe closes with the old value. It is back to normal well before the
|
||||
/// next child looks, which takes `SETTLE`.
|
||||
pub fn sync(&mut self, want: Option<(Vec<Target>, BlinkStyles)>) {
|
||||
let want = want
|
||||
.filter(|(servers, _)| !servers.is_empty())
|
||||
.map(|(servers, styles)| Connection { servers, styles });
|
||||
let same = match (&self.current, &want) {
|
||||
(Some((now, _)), Some(want)) => now == want,
|
||||
(None, None) => true,
|
||||
_ => false,
|
||||
};
|
||||
if same {
|
||||
return;
|
||||
}
|
||||
self.current = want.and_then(|(server, authorization, styles)| {
|
||||
spawn_child(Connection {
|
||||
server: server.to_owned(),
|
||||
authorization: authorization.map(str::to_owned),
|
||||
styles,
|
||||
})
|
||||
});
|
||||
self.current = want.and_then(spawn_child);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1843,16 +1858,25 @@ mod system {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs for the life of the child. A server that does not answer counts as
|
||||
/// nothing going on, and one that refuses the login is never asked again.
|
||||
fn poll_until_refused(mut poller: Poller, shared: &Mutex<Activity>) {
|
||||
/// Runs for the life of the child, one per server. A server that does not
|
||||
/// answer counts as nothing going on, and one that refuses the login is
|
||||
/// never asked again. Each writes its own slot, and `shared` is what all of
|
||||
/// them say together (`merged`).
|
||||
fn poll_until_refused(mut poller: Poller, index: usize, slots: &Mutex<Vec<Activity>>, shared: &Mutex<Activity>) {
|
||||
loop {
|
||||
let poll = poller.poll();
|
||||
if let Ok(mut activity) = shared.lock() {
|
||||
*activity = match poll {
|
||||
Poll::Seen(seen) => seen,
|
||||
_ => Activity::default(),
|
||||
};
|
||||
let seen = match poll {
|
||||
Poll::Seen(seen) => seen,
|
||||
_ => Activity::default(),
|
||||
};
|
||||
let all = slots.lock().ok().map(|mut slots| {
|
||||
if let Some(slot) = slots.get_mut(index) {
|
||||
*slot = seen;
|
||||
}
|
||||
super::merged(&slots)
|
||||
});
|
||||
if let (Some(all), Ok(mut activity)) = (all, shared.lock()) {
|
||||
*activity = all;
|
||||
}
|
||||
if poll == Poll::Refused {
|
||||
return;
|
||||
@@ -1877,18 +1901,19 @@ mod system {
|
||||
.read_line(&mut line)
|
||||
.ok()
|
||||
.and_then(|_| serde_json::from_str::<Connection>(&line).ok());
|
||||
let Some(Connection {
|
||||
server,
|
||||
authorization,
|
||||
styles,
|
||||
}) = connection
|
||||
else {
|
||||
let Some(Connection { servers, styles }) = connection else {
|
||||
std::process::exit(0);
|
||||
};
|
||||
let poller = Url::parse(&server)
|
||||
.ok()
|
||||
.and_then(|url| Poller::new(&url, authorization, styles.wants_alerts()));
|
||||
let (Some(poller), Some(logo)) = (poller, SystemLogo::open()) else {
|
||||
let pollers: Vec<Poller> = servers
|
||||
.into_iter()
|
||||
.filter_map(|target| {
|
||||
Url::parse(&target.server)
|
||||
.ok()
|
||||
.and_then(|url| Poller::new(&url, target.authorization, styles.wants_alerts()))
|
||||
})
|
||||
.collect();
|
||||
let logo = SystemLogo::open();
|
||||
let Some(logo) = logo.filter(|_| !pollers.is_empty()) else {
|
||||
std::process::exit(0);
|
||||
};
|
||||
|
||||
@@ -1900,8 +1925,12 @@ mod system {
|
||||
let _ = closed.send(());
|
||||
});
|
||||
let activity = Arc::new(Mutex::new(Activity::default()));
|
||||
let found = activity.clone();
|
||||
std::thread::spawn(move || poll_until_refused(poller, &found));
|
||||
let slots = Arc::new(Mutex::new(vec![Activity::default(); pollers.len()]));
|
||||
for (index, poller) in pollers.into_iter().enumerate() {
|
||||
let found = activity.clone();
|
||||
let slots = slots.clone();
|
||||
std::thread::spawn(move || poll_until_refused(poller, index, &slots, &found));
|
||||
}
|
||||
|
||||
let mut signals = Live {
|
||||
pipe_closed,
|
||||
@@ -3371,15 +3400,17 @@ mod tests {
|
||||
fn the_connection_line_round_trips_with_and_without_a_login() {
|
||||
for authorization in [None, Some("Basic abc".to_string())] {
|
||||
let line = serde_json::to_string(&Connection {
|
||||
server: "http://127.0.0.1:3000/".into(),
|
||||
authorization: authorization.clone(),
|
||||
servers: vec![Target {
|
||||
server: "http://127.0.0.1:3000/".into(),
|
||||
authorization: authorization.clone(),
|
||||
}],
|
||||
styles: WORK,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(!line.contains('\n'), "one line");
|
||||
let back: Connection = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!(back.server, "http://127.0.0.1:3000/");
|
||||
assert_eq!(back.authorization, authorization);
|
||||
assert_eq!(back.servers[0].server, "http://127.0.0.1:3000/");
|
||||
assert_eq!(back.servers[0].authorization, authorization);
|
||||
assert_eq!(back.styles, WORK);
|
||||
}
|
||||
}
|
||||
@@ -3686,4 +3717,33 @@ mod tests {
|
||||
watcher.sync(None);
|
||||
assert!(watcher.current.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_servers_merge_into_one_logo() {
|
||||
assert_eq!(merged(&[]), Activity::default());
|
||||
assert_eq!(merged(&[working(), Activity::default()]), working());
|
||||
let all = merged(&[working(), needs_you(), waiting()]);
|
||||
assert!(all.working && all.waiting && all.needs_you);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_child_line_names_every_server() {
|
||||
let line = serde_json::to_string(&Connection {
|
||||
servers: vec![
|
||||
Target {
|
||||
server: "http://127.0.0.1:3000/".into(),
|
||||
authorization: None,
|
||||
},
|
||||
Target {
|
||||
server: "https://studio.example.ts.net/".into(),
|
||||
authorization: Some("Basic eA==".into()),
|
||||
},
|
||||
],
|
||||
styles: WORK,
|
||||
})
|
||||
.unwrap();
|
||||
let back: Connection = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!(back.servers.len(), 2);
|
||||
assert_eq!(back.servers[1].authorization.as_deref(), Some("Basic eA=="));
|
||||
}
|
||||
}
|
||||
+294
-74
@@ -21,8 +21,14 @@
|
||||
//! of it: every challenge comes back here and gets the login of that moment,
|
||||
//! never one an earlier connect left behind.
|
||||
//!
|
||||
//! Two smaller helpers live here too: `clear_cookies`, which empties the web
|
||||
//! views' cookie jar before a login so an earlier user's session cookie cannot
|
||||
//! Each server tab hands over a login of its own (`set_credentials`, keyed by
|
||||
//! the tab), and a challenge is answered with the login of the tab whose server
|
||||
//! it is (`pick`), and only to a web view of that tab (`bind_view`), so two
|
||||
//! tabs never answer for each other, even when one tab's page fetches from
|
||||
//! the other's server.
|
||||
//!
|
||||
//! Two smaller helpers live here too: `clear_cookies`, which removes one
|
||||
//! server's cookies before a login so an earlier user's session cookie cannot
|
||||
//! win over the new login, and `content_size`, the window's content area.
|
||||
//!
|
||||
//! `install` adds the missing methods to the classes of the delegates wry made,
|
||||
@@ -145,6 +151,40 @@ fn bare_host(host: &str) -> &str {
|
||||
host.strip_prefix('[').and_then(|h| h.strip_suffix(']')).unwrap_or(host)
|
||||
}
|
||||
|
||||
/// Which tab's login a challenge is for. The URL that got the 401 belongs to
|
||||
/// the tab whose server the protection space names and whose base path holds
|
||||
/// it, the deepest one when several do (a server at `/` and another below a
|
||||
/// path on the same origin, behind one proxy); then that tab answers only when
|
||||
/// the URL is in its scope (`policy::challenge_in_scope`). So a web tab of the
|
||||
/// deeper server never gets the login of the server above it. None: no tab's
|
||||
/// server, so WebKit's own handling.
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
fn pick<'a>(challenge: &Challenge<'_>, saved: &'a [(u64, BasicCredentials)]) -> Option<(u64, &'a BasicCredentials)> {
|
||||
let failed = challenge.failed?;
|
||||
let (tab, owner) = saved
|
||||
.iter()
|
||||
.filter(|(_, s)| {
|
||||
credentials_match(s, challenge.scheme, challenge.host, challenge.port)
|
||||
&& crate::policy::within_base(failed, &s.server)
|
||||
})
|
||||
.max_by_key(|(_, s)| s.server.path().len())?;
|
||||
crate::policy::challenge_in_scope(failed, &owner.server).then_some((*tab, owner))
|
||||
}
|
||||
|
||||
/// Whether a cookie the store keeps for `domain` goes to pages of `host`: a
|
||||
/// host-only cookie of that host (Codeman's own, which names no domain), or a
|
||||
/// domain cookie (`.example.ts.net`) the host lies under. Case-insensitive,
|
||||
/// IPv6 brackets ignored.
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
fn cookie_for_host(domain: &str, host: &str) -> bool {
|
||||
let host = bare_host(host).to_ascii_lowercase();
|
||||
let domain = bare_host(domain.trim()).to_ascii_lowercase();
|
||||
match domain.strip_prefix('.') {
|
||||
Some(parent) => host == parent || host.ends_with(&domain),
|
||||
None => !domain.is_empty() && host == domain,
|
||||
}
|
||||
}
|
||||
|
||||
/// How a dialog names the page that opened it ("localhost:3000"), from a
|
||||
/// security origin's host and port (0 = the scheme's default, left out).
|
||||
fn origin_label(host: &str, port: i64) -> Option<String> {
|
||||
@@ -182,25 +222,51 @@ pub fn install(webview: &wry::WebView) {
|
||||
imp::install(webview);
|
||||
}
|
||||
|
||||
/// The login HTTP Basic challenges from that server are answered with
|
||||
/// (`None`: answer none), from the next challenge on: WebKit keeps no copy of
|
||||
/// an earlier one. Also re-arms the refusal report. Main thread only.
|
||||
/// The login HTTP Basic challenges from tab `tab`'s server are answered with
|
||||
/// (`None`: that tab answers none), from the next challenge on: WebKit keeps
|
||||
/// no copy of an earlier one. Also re-arms that tab's refusal report. Main
|
||||
/// thread only.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn set_credentials(creds: Option<BasicCredentials>) {
|
||||
imp::set_credentials(creds);
|
||||
pub fn set_credentials(tab: u64, creds: Option<BasicCredentials>) {
|
||||
imp::set_credentials(tab, creds);
|
||||
}
|
||||
|
||||
/// Called on the main thread, once per `set_credentials`, when the server
|
||||
/// refused the saved login. It runs inside a WebKit callback, so it should
|
||||
/// only post an event, never touch windows directly.
|
||||
/// Called on the main thread with the tab, once per `set_credentials` of that
|
||||
/// tab, when its server refused the saved login. It runs inside a WebKit
|
||||
/// callback, so it should only post an event, never touch windows directly.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn set_auth_rejected_handler(handler: Box<dyn Fn()>) {
|
||||
pub fn set_auth_rejected_handler(handler: Box<dyn Fn(u64)>) {
|
||||
imp::set_auth_rejected_handler(handler);
|
||||
}
|
||||
|
||||
/// Removes every cookie from the app's default website data store, which all
|
||||
/// of its web views use, then calls `done`. Only cookies: local storage, where
|
||||
/// Codeman keeps per-device settings, stays. Main thread only.
|
||||
/// Ties a web view to a tab: a Basic challenge from that web view is answered
|
||||
/// with that tab's login only, never another tab's, whatever server the
|
||||
/// request went to. Call it for every server page and pop-out web view. Main
|
||||
/// thread only.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn bind_view(webview: &wry::WebView, tab: u64) {
|
||||
imp::bind_view(webview, tab);
|
||||
}
|
||||
|
||||
/// A closed tab's web views answer no challenge any more.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn forget_tab(tab: u64) {
|
||||
imp::forget_tab(tab);
|
||||
}
|
||||
|
||||
/// Whether WebKit gives each server a data store of its own
|
||||
/// (`dataStoreForIdentifier:`, macOS 14 and later). wry falls back to the
|
||||
/// default store without it, and so does `clear_cookies`.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn own_stores_available() -> bool {
|
||||
imp::os_major_version() >= 14
|
||||
}
|
||||
|
||||
/// Removes the cookies of `host` (`cookie_for_host`) from a data store: the
|
||||
/// server's own (`store`, on a macOS that has them) or the default one, then
|
||||
/// calls `done`. Only that host's cookies, so the other servers' tabs stay
|
||||
/// logged in, and only cookies: local storage, where Codeman keeps
|
||||
/// per-device settings, stays. Main thread only.
|
||||
///
|
||||
/// `done` runs exactly once, on the main thread, as its own operation on the
|
||||
/// main queue: never before this returns and never inside a WebKit callback.
|
||||
@@ -209,8 +275,8 @@ pub fn set_auth_rejected_handler(handler: Box<dyn Fn()>) {
|
||||
/// nothing and calls `done` right away on the calling thread. If WebKit never
|
||||
/// answers at all, `done` never runs: the caller's own deadline covers that.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn clear_cookies(done: Box<dyn FnOnce()>) {
|
||||
imp::clear_cookies(done);
|
||||
pub fn clear_cookies(store: Option<[u8; 16]>, host: String, done: Box<dyn FnOnce()>) {
|
||||
imp::clear_cookies(store, host, done);
|
||||
}
|
||||
|
||||
/// The window's content area in points (`contentRectForFrameRect` of its
|
||||
@@ -244,28 +310,38 @@ mod imp {
|
||||
use objc2::{msg_send, sel, ClassType, Message};
|
||||
use objc2_app_kit::{NSAlert, NSAlertFirstButtonReturn, NSTextField, NSView, NSWindow};
|
||||
use objc2_foundation::{
|
||||
MainThreadMarker, NSDate, NSInteger, NSOperationQueue, NSPoint, NSRect, NSSet, NSSize, NSString,
|
||||
NSURLAuthenticationChallenge, NSURLAuthenticationMethodHTTPBasic, NSURLCredential, NSURLCredentialPersistence,
|
||||
NSURLProtectionSpace, NSURLRequest, NSURLResponse, NSURLSessionAuthChallengeDisposition, NSURL,
|
||||
MainThreadMarker, NSArray, NSHTTPCookie, NSInteger, NSOperationQueue, NSPoint, NSProcessInfo, NSRect, NSSize,
|
||||
NSString, NSURLAuthenticationChallenge, NSURLAuthenticationMethodHTTPBasic, NSURLCredential,
|
||||
NSURLCredentialPersistence, NSURLProtectionSpace, NSURLRequest, NSURLResponse,
|
||||
NSURLSessionAuthChallengeDisposition, NSURL, NSUUID,
|
||||
};
|
||||
use objc2_web_kit::{WKFrameInfo, WKSecurityOrigin, WKWebsiteDataStore, WKWebsiteDataTypeCookies};
|
||||
use objc2_web_kit::{WKFrameInfo, WKSecurityOrigin, WKWebsiteDataStore};
|
||||
use tao::platform::macos::WindowExtMacOS;
|
||||
use url::Url;
|
||||
use wry::WebViewExtMacOS;
|
||||
|
||||
use super::{decide, dialog_title, origin_label, BasicCredentials, Challenge, ChallengeAnswer};
|
||||
use super::{
|
||||
cookie_for_host, decide, dialog_title, origin_label, pick, BasicCredentials, Challenge, ChallengeAnswer,
|
||||
};
|
||||
|
||||
/// Page text in a dialog is cut at this many UTF-16 units, so a huge
|
||||
/// message cannot push the alert's buttons off the screen.
|
||||
const MAX_DIALOG_UTF16: usize = 2000;
|
||||
|
||||
/// What the app is told, with the tab, when a server refuses its login.
|
||||
type RejectedHandler = Rc<dyn Fn(u64)>;
|
||||
|
||||
thread_local! {
|
||||
/// The login challenges are answered with; `None` answers none.
|
||||
static SAVED: RefCell<Option<BasicCredentials>> = const { RefCell::new(None) };
|
||||
/// The server refused `SAVED` and the app was told; `set_credentials` clears it.
|
||||
static REJECTED: Cell<bool> = const { Cell::new(false) };
|
||||
/// Told once when the server refuses `SAVED`.
|
||||
static ON_REJECTED: RefCell<Option<Rc<dyn Fn()>>> = const { RefCell::new(None) };
|
||||
/// The login of each tab that has one, by tab.
|
||||
static SAVED: RefCell<Vec<(u64, BasicCredentials)>> = const { RefCell::new(Vec::new()) };
|
||||
/// The tabs whose server refused their login, the app told; a tab's
|
||||
/// `set_credentials` takes it out again.
|
||||
static REJECTED: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
|
||||
/// The tab of each server page and pop-out web view, by the address of
|
||||
/// its WKWebView (`bind_view`).
|
||||
static VIEWS: RefCell<Vec<(usize, u64)>> = const { RefCell::new(Vec::new()) };
|
||||
/// Told once, with the tab, when a server refuses its login.
|
||||
static ON_REJECTED: RefCell<Option<RejectedHandler>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
// The added methods, with every object argument as a raw pointer: WebKit
|
||||
@@ -365,61 +441,145 @@ mod imp {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn set_credentials(creds: Option<BasicCredentials>) {
|
||||
pub(super) fn set_credentials(tab: u64, creds: Option<BasicCredentials>) {
|
||||
if MainThreadMarker::new().is_none() {
|
||||
eprintln!("codeman-desktop: macos::set_credentials called off the main thread; ignored");
|
||||
return;
|
||||
}
|
||||
let stored = SAVED.try_with(|saved| saved.try_borrow_mut().map(|mut saved| *saved = creds).is_ok());
|
||||
let stored = SAVED.try_with(|saved| {
|
||||
saved
|
||||
.try_borrow_mut()
|
||||
.map(|mut saved| {
|
||||
saved.retain(|(t, _)| *t != tab);
|
||||
if let Some(creds) = creds {
|
||||
saved.push((tab, creds));
|
||||
}
|
||||
})
|
||||
.is_ok()
|
||||
});
|
||||
if stored != Ok(true) {
|
||||
eprintln!("codeman-desktop: could not store the login for Basic challenges");
|
||||
}
|
||||
let _ = REJECTED.try_with(|rejected| rejected.set(false));
|
||||
let _ = REJECTED.try_with(|rejected| {
|
||||
if let Ok(mut rejected) = rejected.try_borrow_mut() {
|
||||
rejected.retain(|t| *t != tab);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn set_auth_rejected_handler(handler: Box<dyn Fn()>) {
|
||||
pub(super) fn bind_view(webview: &wry::WebView, tab: u64) {
|
||||
if MainThreadMarker::new().is_none() {
|
||||
return;
|
||||
}
|
||||
let address = Retained::as_ptr(&WebViewExtMacOS::webview(webview)) as usize;
|
||||
let _ = VIEWS.try_with(|views| {
|
||||
if let Ok(mut views) = views.try_borrow_mut() {
|
||||
// A WKWebView freed earlier may have left its address behind.
|
||||
views.retain(|(a, _)| *a != address);
|
||||
views.push((address, tab));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn forget_tab(tab: u64) {
|
||||
let _ = VIEWS.try_with(|views| {
|
||||
if let Ok(mut views) = views.try_borrow_mut() {
|
||||
views.retain(|(_, t)| *t != tab);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The tab a WKWebView belongs to, by its address.
|
||||
fn tab_of_view(web_view: *mut AnyObject) -> Option<u64> {
|
||||
let address = web_view as usize;
|
||||
VIEWS
|
||||
.try_with(|views| {
|
||||
views
|
||||
.try_borrow()
|
||||
.ok()
|
||||
.and_then(|views| views.iter().find(|(a, _)| *a == address).map(|(_, t)| *t))
|
||||
})
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
pub(super) fn os_major_version() -> isize {
|
||||
NSProcessInfo::processInfo().operatingSystemVersion().majorVersion
|
||||
}
|
||||
|
||||
pub(super) fn set_auth_rejected_handler(handler: Box<dyn Fn(u64)>) {
|
||||
if MainThreadMarker::new().is_none() {
|
||||
eprintln!("codeman-desktop: macos::set_auth_rejected_handler called off the main thread; ignored");
|
||||
return;
|
||||
}
|
||||
let handler: Rc<dyn Fn()> = Rc::from(handler);
|
||||
let handler: RejectedHandler = Rc::from(handler);
|
||||
let stored = ON_REJECTED.try_with(|slot| slot.try_borrow_mut().map(|mut slot| *slot = Some(handler)).is_ok());
|
||||
if stored != Ok(true) {
|
||||
eprintln!("codeman-desktop: could not store the login-refused handler");
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn clear_cookies(done: Box<dyn FnOnce()>) {
|
||||
if MainThreadMarker::new().is_none() {
|
||||
pub(super) fn clear_cookies(store: Option<[u8; 16]>, host: String, done: Box<dyn FnOnce()>) {
|
||||
let Some(mtm) = MainThreadMarker::new() else {
|
||||
eprintln!("codeman-desktop: macos::clear_cookies called off the main thread; cookies kept");
|
||||
// `done` was made on this thread, so it runs here instead of being
|
||||
// sent to another one.
|
||||
run_done(done);
|
||||
return;
|
||||
}
|
||||
};
|
||||
// Every way out of here, a panic included, either hands `pending` to
|
||||
// WebKit's completion handler or drops it, and both pass `done` on.
|
||||
let pending = Pending(Cell::new(Some(done)));
|
||||
let _ = catch_unwind(AssertUnwindSafe(|| autoreleasepool(|_| remove_cookies(pending))));
|
||||
// WebKit's completion handlers or drops it, and both pass `done` on.
|
||||
let pending = Rc::new(Pending(Cell::new(Some(done))));
|
||||
let _ = catch_unwind(AssertUnwindSafe(|| {
|
||||
autoreleasepool(|_| remove_cookies(mtm, store, host, pending))
|
||||
}));
|
||||
}
|
||||
|
||||
fn remove_cookies(pending: Pending) {
|
||||
// SAFETY: class methods called on the main thread (checked by the
|
||||
// caller), with nil handled by the `Option` return types.
|
||||
let store: Option<Retained<WKWebsiteDataStore>> =
|
||||
unsafe { msg_send![WKWebsiteDataStore::class(), defaultDataStore] };
|
||||
let since: Option<Retained<NSDate>> = unsafe { msg_send![NSDate::class(), distantPast] };
|
||||
let (Some(store), Some(since)) = (store, since) else {
|
||||
eprintln!("codeman-desktop: no website data store; cookies kept");
|
||||
return;
|
||||
fn remove_cookies(mtm: MainThreadMarker, store: Option<[u8; 16]>, host: String, pending: Rc<Pending>) {
|
||||
// The same store wry gave the server's web view: its own on a macOS that
|
||||
// has them, else the default one. `dataStoreForIdentifier:` does not
|
||||
// exist before macOS 14, and an all-zero identifier throws.
|
||||
let own = store.filter(|id| os_major_version() >= 14 && id.iter().any(|b| *b != 0));
|
||||
// SAFETY: class methods called on the main thread (the marker).
|
||||
let data_store: Retained<WKWebsiteDataStore> = match own {
|
||||
Some(id) => unsafe { WKWebsiteDataStore::dataStoreForIdentifier(&NSUUID::from_bytes(id), mtm) },
|
||||
None => unsafe { WKWebsiteDataStore::defaultDataStore(mtm) },
|
||||
};
|
||||
// SAFETY: an immutable string constant exported by WebKit.
|
||||
let types = NSSet::from_slice(&[unsafe { WKWebsiteDataTypeCookies }]);
|
||||
let completion = RcBlock::new(move || pending.finish());
|
||||
// SAFETY: main thread; WebKit copies the block, keeps it until the
|
||||
// cookies are gone and then calls it. Dropping our reference after the
|
||||
// call is fine.
|
||||
unsafe { store.removeDataOfTypes_modifiedSince_completionHandler(&types, &since, &completion) };
|
||||
// SAFETY: a property read on the main thread.
|
||||
let cookies = unsafe { data_store.httpCookieStore() };
|
||||
let delete_from = cookies.clone();
|
||||
let fetched = RcBlock::new(move |all: std::ptr::NonNull<NSArray<NSHTTPCookie>>| {
|
||||
// SAFETY: WebKit hands a valid array for the length of this call.
|
||||
let all = unsafe { all.as_ref() };
|
||||
let mine: Vec<Retained<NSHTTPCookie>> = autoreleasepool(|_| {
|
||||
all.to_vec()
|
||||
.into_iter()
|
||||
.filter(|cookie| rust_string(&cookie.domain()).is_some_and(|d| cookie_for_host(&d, &host)))
|
||||
.collect()
|
||||
});
|
||||
if mine.is_empty() {
|
||||
pending.finish();
|
||||
return;
|
||||
}
|
||||
// `done` goes once the last of them is deleted.
|
||||
let left = Rc::new(Cell::new(mine.len()));
|
||||
for cookie in &mine {
|
||||
let left = left.clone();
|
||||
let pending = pending.clone();
|
||||
let deleted = RcBlock::new(move || {
|
||||
left.set(left.get().saturating_sub(1));
|
||||
if left.get() == 0 {
|
||||
pending.finish();
|
||||
}
|
||||
});
|
||||
// SAFETY: main thread (WebKit calls this handler there); WebKit
|
||||
// copies the block and calls it once the cookie is gone.
|
||||
unsafe { delete_from.deleteCookie_completionHandler(cookie, Some(&deleted)) };
|
||||
}
|
||||
});
|
||||
// SAFETY: main thread; WebKit copies the block, calls it with the
|
||||
// store's cookies, and releases it.
|
||||
unsafe { cookies.getAllCookies(&fetched) };
|
||||
}
|
||||
|
||||
/// `done` until it is passed on: by the completion handler, or, when
|
||||
@@ -692,7 +852,7 @@ mod imp {
|
||||
extern "C-unwind" fn did_receive_challenge(
|
||||
_this: *mut AnyObject,
|
||||
_cmd: Sel,
|
||||
_web_view: *mut AnyObject,
|
||||
web_view: *mut AnyObject,
|
||||
challenge: *mut NSURLAuthenticationChallenge,
|
||||
handler: *mut ChallengeHandler,
|
||||
) {
|
||||
@@ -700,22 +860,24 @@ mod imp {
|
||||
let Some(handler) = (unsafe { handler.as_ref() }) else {
|
||||
return;
|
||||
};
|
||||
let reply = catch_unwind(AssertUnwindSafe(|| reply_to(unsafe { challenge.as_ref() }))).unwrap_or_default();
|
||||
let tab = tab_of_view(web_view);
|
||||
let reply = catch_unwind(AssertUnwindSafe(|| reply_to(unsafe { challenge.as_ref() }, tab))).unwrap_or_default();
|
||||
let credential = reply
|
||||
.credential
|
||||
.as_ref()
|
||||
.map_or(ptr::null_mut(), |c| Retained::as_ptr(c).cast_mut());
|
||||
handler.call((reply.disposition, credential));
|
||||
// Told after WebKit has its answer, so the app's handler cannot delay it.
|
||||
if reply.report {
|
||||
notify_rejected();
|
||||
if let Some(tab) = reply.report {
|
||||
notify_rejected(tab);
|
||||
}
|
||||
}
|
||||
|
||||
struct Reply {
|
||||
disposition: NSURLSessionAuthChallengeDisposition,
|
||||
credential: Option<Retained<NSURLCredential>>,
|
||||
report: bool,
|
||||
/// The tab whose server refused its login, to tell the app.
|
||||
report: Option<u64>,
|
||||
}
|
||||
|
||||
impl Default for Reply {
|
||||
@@ -723,12 +885,14 @@ mod imp {
|
||||
Reply {
|
||||
disposition: NSURLSessionAuthChallengeDisposition::PerformDefaultHandling,
|
||||
credential: None,
|
||||
report: false,
|
||||
report: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reply_to(challenge: Option<&NSURLAuthenticationChallenge>) -> Reply {
|
||||
/// `tab`: the tab of the web view that was challenged, whose login is the
|
||||
/// only one it may get. None (a view of no tab): no login at all.
|
||||
fn reply_to(challenge: Option<&NSURLAuthenticationChallenge>, tab: Option<u64>) -> Reply {
|
||||
let Some(challenge) = challenge else {
|
||||
return Reply::default();
|
||||
};
|
||||
@@ -762,10 +926,13 @@ mod imp {
|
||||
let failed = failure_url(challenge);
|
||||
|
||||
let saved = SAVED
|
||||
.try_with(|saved| saved.try_borrow().ok().and_then(|saved| saved.clone()))
|
||||
.try_with(|saved| saved.try_borrow().ok().map(|saved| saved.clone()))
|
||||
.ok()
|
||||
.flatten();
|
||||
let rejected = REJECTED.try_with(Cell::get).unwrap_or(false);
|
||||
.flatten()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter(|(t, _)| Some(*t) == tab)
|
||||
.collect::<Vec<_>>();
|
||||
let asked = Challenge {
|
||||
basic,
|
||||
proxy,
|
||||
@@ -775,8 +942,14 @@ mod imp {
|
||||
previous_failures: previous_failures as i64,
|
||||
failed: failed.as_ref(),
|
||||
};
|
||||
match (decide(&asked, saved.as_ref(), rejected), saved) {
|
||||
(ChallengeAnswer::UseCredential, Some(saved)) => {
|
||||
let picked = pick(&asked, &saved);
|
||||
let rejected = picked.is_some_and(|(tab, _)| {
|
||||
REJECTED
|
||||
.try_with(|rejected| rejected.try_borrow().is_ok_and(|r| r.contains(&tab)))
|
||||
.unwrap_or(false)
|
||||
});
|
||||
match (decide(&asked, picked.map(|(_, s)| s), rejected), picked) {
|
||||
(ChallengeAnswer::UseCredential, Some((_, saved))) => {
|
||||
let user = NSString::from_str(&saved.username);
|
||||
let password = NSString::from_str(&saved.password);
|
||||
// None: WebKit uses it for this request only and stores
|
||||
@@ -797,26 +970,32 @@ mod imp {
|
||||
Some(credential) => Reply {
|
||||
disposition: NSURLSessionAuthChallengeDisposition::UseCredential,
|
||||
credential: Some(credential),
|
||||
report: false,
|
||||
report: None,
|
||||
},
|
||||
None => Reply::default(),
|
||||
}
|
||||
}
|
||||
(ChallengeAnswer::CancelAndReport, _) => {
|
||||
let _ = REJECTED.try_with(|rejected| rejected.set(true));
|
||||
(ChallengeAnswer::CancelAndReport, Some((tab, _))) => {
|
||||
let _ = REJECTED.try_with(|rejected| {
|
||||
if let Ok(mut rejected) = rejected.try_borrow_mut() {
|
||||
rejected.push(tab);
|
||||
}
|
||||
});
|
||||
eprintln!("codeman-desktop: {host}:{port} refused the saved login; not sending it again");
|
||||
Reply {
|
||||
disposition: NSURLSessionAuthChallengeDisposition::CancelAuthenticationChallenge,
|
||||
credential: None,
|
||||
report: true,
|
||||
report: Some(tab),
|
||||
}
|
||||
}
|
||||
(ChallengeAnswer::Cancel, _) => Reply {
|
||||
disposition: NSURLSessionAuthChallengeDisposition::CancelAuthenticationChallenge,
|
||||
credential: None,
|
||||
report: false,
|
||||
report: None,
|
||||
},
|
||||
(ChallengeAnswer::Default | ChallengeAnswer::UseCredential, _) => Reply::default(),
|
||||
(ChallengeAnswer::Default | ChallengeAnswer::UseCredential | ChallengeAnswer::CancelAndReport, _) => {
|
||||
Reply::default()
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -833,7 +1012,7 @@ mod imp {
|
||||
Url::parse(&rust_string(&*text?)?).ok()
|
||||
}
|
||||
|
||||
fn notify_rejected() {
|
||||
fn notify_rejected(tab: u64) {
|
||||
// Cloned out first: the handler may call `set_credentials` or
|
||||
// `set_auth_rejected_handler`, which would find the cell borrowed.
|
||||
let handler = ON_REJECTED
|
||||
@@ -841,7 +1020,7 @@ mod imp {
|
||||
.ok()
|
||||
.flatten();
|
||||
if let Some(handler) = handler {
|
||||
if catch_unwind(AssertUnwindSafe(|| handler())).is_err() {
|
||||
if catch_unwind(AssertUnwindSafe(|| handler(tab))).is_err() {
|
||||
eprintln!("codeman-desktop: the login-refused handler panicked");
|
||||
}
|
||||
}
|
||||
@@ -1074,4 +1253,45 @@ mod tests {
|
||||
// gets a first line of the app's own, never its own text in bold.
|
||||
assert_eq!(dialog_title(None), "An embedded page says:");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_tab_answers_for_its_own_server() {
|
||||
let saved = vec![
|
||||
(1, saved("http://127.0.0.1:3000/")),
|
||||
(2, saved("http://127.0.0.1:5000/")),
|
||||
(3, saved("http://h:3000/")),
|
||||
(4, saved("http://h:3000/codeman/")),
|
||||
];
|
||||
let at = |port: i64, host: &'static str, failed: &Url| {
|
||||
let c = challenge("http", host, port, 0, Some(failed));
|
||||
pick(&c, &saved).map(|(tab, _)| tab)
|
||||
};
|
||||
assert_eq!(at(3000, "127.0.0.1", &url("http://127.0.0.1:3000/api/status")), Some(1));
|
||||
assert_eq!(at(5000, "127.0.0.1", &url("http://127.0.0.1:5000/api/status")), Some(2));
|
||||
assert_eq!(at(4000, "127.0.0.1", &url("http://127.0.0.1:4000/api/status")), None);
|
||||
// Below a base path the deeper server wins; elsewhere the root one.
|
||||
assert_eq!(at(3000, "h", &url("http://h:3000/codeman/api/status")), Some(4));
|
||||
assert_eq!(at(3000, "h", &url("http://h:3000/api/status")), Some(3));
|
||||
// A web tab under either is nobody's.
|
||||
assert_eq!(at(3000, "h", &url("http://h:3000/webview/cap/")), None);
|
||||
assert_eq!(at(3000, "h", &url("http://h:3000/codeman/webview/cap/")), None);
|
||||
let none: Vec<(u64, BasicCredentials)> = Vec::new();
|
||||
let c = challenge("http", "h", 3000, 0, None);
|
||||
assert!(pick(&c, &none).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cookies_go_with_their_host() {
|
||||
assert!(cookie_for_host("127.0.0.1", "127.0.0.1"));
|
||||
assert!(cookie_for_host("Studio.Example.ts.net", "studio.example.ts.net"));
|
||||
assert!(cookie_for_host(".example.ts.net", "studio.example.ts.net"));
|
||||
assert!(cookie_for_host(".example.ts.net", "example.ts.net"));
|
||||
assert!(cookie_for_host("::1", "[::1]"));
|
||||
assert!(!cookie_for_host("atlas.example.ts.net", "studio.example.ts.net"));
|
||||
assert!(!cookie_for_host(".other.ts.net", "studio.example.ts.net"));
|
||||
assert!(!cookie_for_host("example.ts.net", "studio.example.ts.net"));
|
||||
assert!(!cookie_for_host("localhost", "127.0.0.1"));
|
||||
assert!(!cookie_for_host("", "127.0.0.1"));
|
||||
assert!(!cookie_for_host(".ample.ts.net", "studio.example.ts.net"));
|
||||
}
|
||||
}
|
||||
+2235
-689
File diff suppressed because it is too large.
Load diff
@@ -3,6 +3,8 @@
|
||||
use muda::accelerator::{Accelerator, Code, Modifiers};
|
||||
use muda::{AboutMetadata, CheckMenuItem, Menu, MenuItem, PredefinedMenuItem, Submenu};
|
||||
|
||||
use crate::tabs::{PALETTE, PALETTE_NAMES};
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::keep_awake::{self, Mode};
|
||||
use crate::logo::{self, BlinkStyle, Signal};
|
||||
@@ -21,11 +23,124 @@ pub mod menu_id {
|
||||
pub const DEVTOOLS: &str = "devtools";
|
||||
pub const HELP_DOCS: &str = "help-docs";
|
||||
pub const HELP_GITHUB: &str = "help-github";
|
||||
pub const TAB_NEW: &str = "tab-new";
|
||||
pub const TAB_CLOSE: &str = "tab-close";
|
||||
pub const TAB_REOPEN: &str = "tab-reopen";
|
||||
pub const TAB_OVERVIEW: &str = "tab-overview";
|
||||
pub const TAB_NEXT: &str = "tab-next";
|
||||
pub const TAB_PREVIOUS: &str = "tab-previous";
|
||||
pub const WINDOW_CLOSE: &str = "window-close";
|
||||
/// `tab-key-<n>`: the tab ⌘n selects (tabs::index_of_key).
|
||||
pub const TAB_KEY_PREFIX: &str = "tab-key-";
|
||||
/// `tab-menu:<tab>:<action>`: an item of a tab's right-click menu.
|
||||
pub const TAB_MENU_PREFIX: &str = "tab-menu:";
|
||||
}
|
||||
|
||||
/// What a tab's right-click menu asks for.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum TabAction {
|
||||
Rename,
|
||||
/// A palette colour, by index into `tabs::PALETTE`.
|
||||
Color(usize),
|
||||
Reload,
|
||||
/// Show the connect page in this tab (another server, or the same with
|
||||
/// another login).
|
||||
Reconnect,
|
||||
Close,
|
||||
CloseOthers,
|
||||
}
|
||||
|
||||
impl TabAction {
|
||||
fn id(self, tab: u64) -> String {
|
||||
let action = match self {
|
||||
TabAction::Rename => "rename".to_string(),
|
||||
TabAction::Color(i) => format!("color-{i}"),
|
||||
TabAction::Reload => "reload".to_string(),
|
||||
TabAction::Reconnect => "reconnect".to_string(),
|
||||
TabAction::Close => "close".to_string(),
|
||||
TabAction::CloseOthers => "close-others".to_string(),
|
||||
};
|
||||
format!("{}{tab}:{action}", menu_id::TAB_MENU_PREFIX)
|
||||
}
|
||||
|
||||
/// The tab and action of a right-click menu item's id.
|
||||
pub fn parse(id: &str) -> Option<(u64, TabAction)> {
|
||||
let (tab, action) = id.strip_prefix(menu_id::TAB_MENU_PREFIX)?.split_once(':')?;
|
||||
let tab = tab.parse().ok()?;
|
||||
let action = match action {
|
||||
"rename" => TabAction::Rename,
|
||||
"reload" => TabAction::Reload,
|
||||
"reconnect" => TabAction::Reconnect,
|
||||
"close" => TabAction::Close,
|
||||
"close-others" => TabAction::CloseOthers,
|
||||
other => {
|
||||
let i: usize = other.strip_prefix("color-")?.parse().ok()?;
|
||||
(i < PALETTE.len()).then_some(TabAction::Color(i))?
|
||||
}
|
||||
};
|
||||
Some((tab, action))
|
||||
}
|
||||
}
|
||||
|
||||
/// The ⌘ number of a `tab-key-<n>` item.
|
||||
pub fn tab_key(id: &str) -> Option<usize> {
|
||||
id.strip_prefix(menu_id::TAB_KEY_PREFIX)?
|
||||
.parse()
|
||||
.ok()
|
||||
.filter(|k| (1..=9).contains(k))
|
||||
}
|
||||
|
||||
/// The right-click menu of one tab. `server`: the tab shows a server (Reload
|
||||
/// and Connect to Another Server make sense); `others`: there are other tabs.
|
||||
pub fn tab_context_menu(tab: u64, color: &str, server: bool, others: bool) -> muda::Result<Menu> {
|
||||
let menu = Menu::new();
|
||||
menu.append(&MenuItem::with_id(
|
||||
TabAction::Rename.id(tab),
|
||||
"Rename Tab\u{2026}",
|
||||
true,
|
||||
None,
|
||||
))?;
|
||||
let colors = Submenu::new("Tab Color", true);
|
||||
for (i, (value, name)) in PALETTE.iter().zip(PALETTE_NAMES).enumerate() {
|
||||
let chosen = value.eq_ignore_ascii_case(color);
|
||||
colors.append(&CheckMenuItem::with_id(
|
||||
TabAction::Color(i).id(tab),
|
||||
name,
|
||||
true,
|
||||
chosen,
|
||||
None,
|
||||
))?;
|
||||
}
|
||||
menu.append(&colors)?;
|
||||
menu.append(&PredefinedMenuItem::separator())?;
|
||||
menu.append(&MenuItem::with_id(TabAction::Reload.id(tab), "Reload", server, None))?;
|
||||
menu.append(&MenuItem::with_id(
|
||||
TabAction::Reconnect.id(tab),
|
||||
"Connect This Tab to Another Server\u{2026}",
|
||||
server,
|
||||
None,
|
||||
))?;
|
||||
menu.append(&PredefinedMenuItem::separator())?;
|
||||
menu.append(&MenuItem::with_id(TabAction::Close.id(tab), "Close Tab", true, None))?;
|
||||
menu.append(&MenuItem::with_id(
|
||||
TabAction::CloseOthers.id(tab),
|
||||
"Close Other Tabs",
|
||||
others,
|
||||
None,
|
||||
))?;
|
||||
Ok(menu)
|
||||
}
|
||||
|
||||
pub struct AppMenu {
|
||||
pub bar: Menu,
|
||||
pub window_menu: Submenu,
|
||||
/// Server: the tab commands, then one item per tab (`set_tabs`).
|
||||
server_menu: Submenu,
|
||||
/// ⌘1 to ⌘9, made once and shown as many as there are tabs.
|
||||
tab_items: Vec<CheckMenuItem>,
|
||||
/// How many of `tab_items` are in the menu.
|
||||
tab_items_shown: usize,
|
||||
pub reopen: MenuItem,
|
||||
pub help_menu: Submenu,
|
||||
pub start_fullscreen: CheckMenuItem,
|
||||
/// The one switch for the logo. None on a Mac without a lit logo, which has no
|
||||
@@ -120,6 +235,34 @@ fn build_keep_awake(config: &Config) -> muda::Result<(Submenu, KeepAwakeMenu)> {
|
||||
))
|
||||
}
|
||||
|
||||
impl AppMenu {
|
||||
/// One item per tab under Server, as (name, in front), with ⌘1 to ⌘8 for
|
||||
/// the first eight and ⌘9 for the last (`tabs::key_of`). Items past nine
|
||||
/// tabs are left out, as Safari does.
|
||||
pub fn set_tabs(&mut self, tabs: &[(String, bool)]) {
|
||||
let len = tabs.len();
|
||||
let shown: Vec<(usize, &(String, bool))> = tabs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, t)| crate::tabs::key_of(i, len).map(|k| (k, t)))
|
||||
.collect();
|
||||
for item in self.tab_items.iter().take(self.tab_items_shown) {
|
||||
let _ = self.server_menu.remove(item);
|
||||
}
|
||||
self.tab_items_shown = 0;
|
||||
// Appended in key order, which is tab order.
|
||||
for (key, (name, active)) in shown {
|
||||
if let Some(item) = self.tab_items.get(key - 1) {
|
||||
item.set_text(name);
|
||||
item.set_checked(*active);
|
||||
if self.server_menu.append(item).is_ok() {
|
||||
self.tab_items_shown = self.tab_items_shown.max(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_menu(config: &Config) -> muda::Result<AppMenu> {
|
||||
let bar = Menu::new();
|
||||
let about = PredefinedMenuItem::about(
|
||||
@@ -243,6 +386,52 @@ pub fn build_menu(config: &Config) -> muda::Result<AppMenu> {
|
||||
logo_switch = Some(switch);
|
||||
logo_lid = Some(lid);
|
||||
}
|
||||
let cmd = |code| Some(Accelerator::new(Modifiers::META, code));
|
||||
let cmd_shift = |code| Some(Accelerator::new(Modifiers::META | Modifiers::SHIFT, code));
|
||||
let reopen = MenuItem::with_id(menu_id::TAB_REOPEN, "Reopen Closed Tab", false, cmd_shift(Code::KeyT));
|
||||
let server_menu = Submenu::with_items(
|
||||
"Server",
|
||||
true,
|
||||
&[
|
||||
&MenuItem::with_id(menu_id::TAB_NEW, "New Server Tab", true, cmd(Code::KeyT)),
|
||||
&MenuItem::with_id(menu_id::TAB_CLOSE, "Close Tab", true, cmd(Code::KeyW)),
|
||||
&reopen,
|
||||
&PredefinedMenuItem::separator(),
|
||||
&MenuItem::with_id(menu_id::TAB_OVERVIEW, "Show All Servers", true, cmd(Code::Digit0)),
|
||||
&MenuItem::with_id(
|
||||
menu_id::TAB_PREVIOUS,
|
||||
"Show Previous Tab",
|
||||
true,
|
||||
cmd_shift(Code::BracketLeft),
|
||||
),
|
||||
&MenuItem::with_id(menu_id::TAB_NEXT, "Show Next Tab", true, cmd_shift(Code::BracketRight)),
|
||||
&PredefinedMenuItem::separator(),
|
||||
],
|
||||
)?;
|
||||
const DIGITS: [Code; 9] = [
|
||||
Code::Digit1,
|
||||
Code::Digit2,
|
||||
Code::Digit3,
|
||||
Code::Digit4,
|
||||
Code::Digit5,
|
||||
Code::Digit6,
|
||||
Code::Digit7,
|
||||
Code::Digit8,
|
||||
Code::Digit9,
|
||||
];
|
||||
let tab_items = DIGITS
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, code)| {
|
||||
CheckMenuItem::with_id(
|
||||
format!("{}{}", menu_id::TAB_KEY_PREFIX, i + 1),
|
||||
"",
|
||||
true,
|
||||
false,
|
||||
cmd(*code),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let window_menu = Submenu::with_items(
|
||||
"Window",
|
||||
true,
|
||||
@@ -250,7 +439,9 @@ pub fn build_menu(config: &Config) -> muda::Result<AppMenu> {
|
||||
&PredefinedMenuItem::minimize(None),
|
||||
&PredefinedMenuItem::maximize(None),
|
||||
&PredefinedMenuItem::separator(),
|
||||
&PredefinedMenuItem::close_window(None),
|
||||
// Not the predefined Close Window: ⌘W closes a tab (Server menu),
|
||||
// as in Safari, so closing the window is ⇧⌘W.
|
||||
&MenuItem::with_id(menu_id::WINDOW_CLOSE, "Close Window", true, cmd_shift(Code::KeyW)),
|
||||
&PredefinedMenuItem::separator(),
|
||||
&PredefinedMenuItem::bring_all_to_front(None),
|
||||
],
|
||||
@@ -263,10 +454,14 @@ pub fn build_menu(config: &Config) -> muda::Result<AppMenu> {
|
||||
&MenuItem::with_id(menu_id::HELP_GITHUB, "Codeman on GitHub", true, None),
|
||||
],
|
||||
)?;
|
||||
bar.append_items(&[&app_menu, &edit, &view, &window_menu, &help_menu])?;
|
||||
bar.append_items(&[&app_menu, &edit, &view, &server_menu, &window_menu, &help_menu])?;
|
||||
Ok(AppMenu {
|
||||
bar,
|
||||
window_menu,
|
||||
server_menu,
|
||||
tab_items,
|
||||
tab_items_shown: 0,
|
||||
reopen,
|
||||
help_menu,
|
||||
start_fullscreen,
|
||||
logo_switch,
|
||||
@@ -275,3 +470,31 @@ pub fn build_menu(config: &Config) -> muda::Result<AppMenu> {
|
||||
logo_lid,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn tab_menu_ids_round_trip() {
|
||||
for action in [
|
||||
TabAction::Rename,
|
||||
TabAction::Color(0),
|
||||
TabAction::Color(5),
|
||||
TabAction::Reload,
|
||||
TabAction::Reconnect,
|
||||
TabAction::Close,
|
||||
TabAction::CloseOthers,
|
||||
] {
|
||||
assert_eq!(TabAction::parse(&action.id(42)), Some((42, action)));
|
||||
}
|
||||
assert_eq!(TabAction::parse("tab-menu:42:color-6"), None);
|
||||
assert_eq!(TabAction::parse("tab-menu:x:close"), None);
|
||||
assert_eq!(TabAction::parse("tab-menu:42:other"), None);
|
||||
assert_eq!(TabAction::parse("reload"), None);
|
||||
assert_eq!(tab_key("tab-key-1"), Some(1));
|
||||
assert_eq!(tab_key("tab-key-9"), Some(9));
|
||||
assert_eq!(tab_key("tab-key-0"), None);
|
||||
assert_eq!(tab_key("tab-key-10"), None);
|
||||
}
|
||||
}
|
||||
@@ -826,6 +826,141 @@ pub fn parse_ipc(frame_url: &str, body: &str, phase: &Phase, is_main_window: boo
|
||||
Some(Ipc::Host(cmd))
|
||||
}
|
||||
|
||||
/// The tab strip across the top of the window (assets/tabs.html).
|
||||
pub const STRIP_PAGE: &str = "codemanapp://localhost/tabs.html";
|
||||
/// The overview of every server (assets/overview.html).
|
||||
pub const OVERVIEW_PAGE: &str = "codemanapp://localhost/overview.html";
|
||||
|
||||
/// What the tab strip asks for. Tab ids are the app's own numbers; a stale or
|
||||
/// made-up one matches no tab and does nothing.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum StripCmd {
|
||||
Ready,
|
||||
Select(u64),
|
||||
Close(u64),
|
||||
New,
|
||||
Overview,
|
||||
/// Right-click on a tab: the native menu for it.
|
||||
Menu(u64),
|
||||
/// The name the user typed (cleaned by `tabs::clean_name`; empty puts the
|
||||
/// default back).
|
||||
Rename {
|
||||
id: u64,
|
||||
name: String,
|
||||
},
|
||||
Move {
|
||||
id: u64,
|
||||
to: usize,
|
||||
},
|
||||
/// A rename started: the strip takes the keyboard for its name field.
|
||||
Editing,
|
||||
/// A mouse-down on the strip's empty space: drag the window.
|
||||
Drag,
|
||||
/// A double-click there: what a title bar double-click does.
|
||||
Zoom,
|
||||
}
|
||||
|
||||
/// What the overview asks for.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum OverviewCmd {
|
||||
Ready,
|
||||
Open(u64),
|
||||
/// Show that tab and select the session in Codeman's page
|
||||
/// (`tabs::is_session_id` is checked before it goes anywhere).
|
||||
OpenSession {
|
||||
tab: u64,
|
||||
session: String,
|
||||
},
|
||||
New,
|
||||
Retry(u64),
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "cmd", rename_all = "camelCase", deny_unknown_fields)]
|
||||
enum RawStrip {
|
||||
Ready,
|
||||
Select { id: u64 },
|
||||
Close { id: u64 },
|
||||
New,
|
||||
Overview,
|
||||
Menu { id: u64 },
|
||||
Rename { id: u64, name: String },
|
||||
Move { id: u64, to: usize },
|
||||
Editing,
|
||||
Drag,
|
||||
Zoom,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "cmd", rename_all = "camelCase", deny_unknown_fields)]
|
||||
enum RawOverview {
|
||||
Ready,
|
||||
Open { tab: u64 },
|
||||
OpenSession { tab: u64, session: String },
|
||||
New,
|
||||
Retry { tab: u64 },
|
||||
}
|
||||
|
||||
/// Whether `frame_url` is exactly the bundled page `page` (a query or
|
||||
/// fragment does not matter).
|
||||
fn is_bundled_page(frame_url: &str, page: &str) -> bool {
|
||||
let (Ok(frame), Ok(page)) = (Url::parse(frame_url), Url::parse(page)) else {
|
||||
return false;
|
||||
};
|
||||
frame.scheme() == APP_SCHEME && frame.host_str() == page.host_str() && frame.path() == page.path()
|
||||
}
|
||||
|
||||
/// A message from the tab strip. Only its own page in its own web view is
|
||||
/// listened to: the caller passes only what came from the strip's web view,
|
||||
/// and the frame must be the strip page.
|
||||
pub fn parse_strip_ipc(frame_url: &str, body: &str) -> Option<StripCmd> {
|
||||
if body.len() > MAX_MESSAGE_LEN || !is_bundled_page(frame_url, STRIP_PAGE) {
|
||||
return None;
|
||||
}
|
||||
Some(match serde_json::from_str::<RawStrip>(body).ok()? {
|
||||
RawStrip::Ready => StripCmd::Ready,
|
||||
RawStrip::Select { id } => StripCmd::Select(id),
|
||||
RawStrip::Close { id } => StripCmd::Close(id),
|
||||
RawStrip::New => StripCmd::New,
|
||||
RawStrip::Overview => StripCmd::Overview,
|
||||
RawStrip::Menu { id } => StripCmd::Menu(id),
|
||||
RawStrip::Rename { id, name } if name.len() <= MAX_FIELD_LEN => StripCmd::Rename { id, name },
|
||||
RawStrip::Move { id, to } => StripCmd::Move { id, to },
|
||||
RawStrip::Editing => StripCmd::Editing,
|
||||
RawStrip::Drag => StripCmd::Drag,
|
||||
RawStrip::Zoom => StripCmd::Zoom,
|
||||
RawStrip::Rename { .. } => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// A message from the overview, under the same rule as the strip's.
|
||||
pub fn parse_overview_ipc(frame_url: &str, body: &str) -> Option<OverviewCmd> {
|
||||
if body.len() > MAX_MESSAGE_LEN || !is_bundled_page(frame_url, OVERVIEW_PAGE) {
|
||||
return None;
|
||||
}
|
||||
Some(match serde_json::from_str::<RawOverview>(body).ok()? {
|
||||
RawOverview::Ready => OverviewCmd::Ready,
|
||||
RawOverview::Open { tab } => OverviewCmd::Open(tab),
|
||||
RawOverview::OpenSession { tab, session } if session.len() <= MAX_FIELD_LEN => {
|
||||
OverviewCmd::OpenSession { tab, session }
|
||||
}
|
||||
RawOverview::New => OverviewCmd::New,
|
||||
RawOverview::Retry { tab } => OverviewCmd::Retry(tab),
|
||||
RawOverview::OpenSession { .. } => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The navigations the strip's and the overview's web views allow: their own
|
||||
/// bundled page and nothing else, so neither can ever show a server's page or
|
||||
/// another site.
|
||||
pub fn bundled_navigation(target: &str, page: &str) -> Navigation {
|
||||
if is_bundled_page(target, page) {
|
||||
Navigation::Allow
|
||||
} else {
|
||||
Navigation::Block
|
||||
}
|
||||
}
|
||||
|
||||
/// Only http(s) URLs ever reach the default browser (never `file:`, a custom
|
||||
/// app scheme, or anything `open` would hand to another program).
|
||||
pub fn external_url(target: &str) -> Option<Url> {
|
||||
@@ -1886,4 +2021,98 @@ mod tests {
|
||||
assert!(external_url("codemanapp://localhost/").is_none());
|
||||
assert!(external_url("vscode://file/x").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strip_messages_only_from_the_strip_page() {
|
||||
let strip = STRIP_PAGE;
|
||||
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"ready"}"#), Some(StripCmd::Ready));
|
||||
assert_eq!(
|
||||
parse_strip_ipc(strip, r#"{"cmd":"select","id":3}"#),
|
||||
Some(StripCmd::Select(3))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_strip_ipc(strip, r#"{"cmd":"close","id":3}"#),
|
||||
Some(StripCmd::Close(3))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_strip_ipc(strip, r#"{"cmd":"menu","id":3}"#),
|
||||
Some(StripCmd::Menu(3))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_strip_ipc(strip, r#"{"cmd":"rename","id":3,"name":"studio"}"#),
|
||||
Some(StripCmd::Rename {
|
||||
id: 3,
|
||||
name: "studio".into()
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
parse_strip_ipc(strip, r#"{"cmd":"move","id":3,"to":0}"#),
|
||||
Some(StripCmd::Move { id: 3, to: 0 })
|
||||
);
|
||||
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"drag"}"#), Some(StripCmd::Drag));
|
||||
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"zoom"}"#), Some(StripCmd::Zoom));
|
||||
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"editing"}"#), Some(StripCmd::Editing));
|
||||
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"new"}"#), Some(StripCmd::New));
|
||||
assert_eq!(
|
||||
parse_strip_ipc(strip, r#"{"cmd":"overview"}"#),
|
||||
Some(StripCmd::Overview)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_strip_ipc("codemanapp://localhost/tabs.html?x=1", r#"{"cmd":"new"}"#),
|
||||
Some(StripCmd::New)
|
||||
);
|
||||
// Other frames, other pages, other shapes.
|
||||
assert_eq!(parse_strip_ipc(CONNECT_PAGE, r#"{"cmd":"new"}"#), None);
|
||||
assert_eq!(parse_strip_ipc(OVERVIEW_PAGE, r#"{"cmd":"new"}"#), None);
|
||||
assert_eq!(parse_strip_ipc("http://localhost/tabs.html", r#"{"cmd":"new"}"#), None);
|
||||
assert_eq!(parse_strip_ipc("codemanapp://evil/tabs.html", r#"{"cmd":"new"}"#), None);
|
||||
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"select","id":-1}"#), None);
|
||||
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"select","id":"3"}"#), None);
|
||||
assert_eq!(parse_strip_ipc(strip, r#"{"cmd":"connect","url":"http://x/"}"#), None);
|
||||
let long = format!(
|
||||
r#"{{"cmd":"rename","id":1,"name":"{}"}}"#,
|
||||
"x".repeat(MAX_FIELD_LEN + 1)
|
||||
);
|
||||
assert_eq!(parse_strip_ipc(strip, &long), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overview_messages_only_from_the_overview_page() {
|
||||
let page = OVERVIEW_PAGE;
|
||||
assert_eq!(parse_overview_ipc(page, r#"{"cmd":"ready"}"#), Some(OverviewCmd::Ready));
|
||||
assert_eq!(
|
||||
parse_overview_ipc(page, r#"{"cmd":"open","tab":2}"#),
|
||||
Some(OverviewCmd::Open(2))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_overview_ipc(page, r#"{"cmd":"retry","tab":2}"#),
|
||||
Some(OverviewCmd::Retry(2))
|
||||
);
|
||||
assert_eq!(parse_overview_ipc(page, r#"{"cmd":"new"}"#), Some(OverviewCmd::New));
|
||||
assert_eq!(
|
||||
parse_overview_ipc(page, r#"{"cmd":"openSession","tab":2,"session":"abc-1"}"#),
|
||||
Some(OverviewCmd::OpenSession {
|
||||
tab: 2,
|
||||
session: "abc-1".into()
|
||||
})
|
||||
);
|
||||
assert_eq!(parse_overview_ipc(STRIP_PAGE, r#"{"cmd":"new"}"#), None);
|
||||
assert_eq!(parse_overview_ipc(CONNECT_PAGE, r#"{"cmd":"ready"}"#), None);
|
||||
assert_eq!(parse_overview_ipc(page, r#"{"cmd":"select","id":1}"#), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bundled_pages_navigate_nowhere_else() {
|
||||
assert_eq!(bundled_navigation(STRIP_PAGE, STRIP_PAGE), Navigation::Allow);
|
||||
assert_eq!(bundled_navigation(OVERVIEW_PAGE, STRIP_PAGE), Navigation::Block);
|
||||
assert_eq!(bundled_navigation(CONNECT_PAGE, STRIP_PAGE), Navigation::Block);
|
||||
assert_eq!(
|
||||
bundled_navigation("http://127.0.0.1:3000/", STRIP_PAGE),
|
||||
Navigation::Block
|
||||
);
|
||||
assert_eq!(bundled_navigation("about:blank", OVERVIEW_PAGE), Navigation::Block);
|
||||
// The connect page's own gate does not admit the two new pages.
|
||||
assert!(!is_connect_page(&Url::parse(STRIP_PAGE).unwrap()));
|
||||
assert!(!is_connect_page(&Url::parse(OVERVIEW_PAGE).unwrap()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,650 @@
|
||||
//! Server tabs: the pure half. One window holds a tab per Codeman server (or a
|
||||
//! "New server" tab that shows the connect page), a strip across the top of
|
||||
//! the window draws them (`assets/tabs.html`), and an overview of every server
|
||||
//! (`assets/overview.html`) can take the place of the active tab. Everything
|
||||
//! here is a decision with no window behind it, so it is unit-tested on its own:
|
||||
//! names, colours, order, which data store a server's pages use, and the state
|
||||
//! the two pages are sent.
|
||||
|
||||
use serde::Serialize;
|
||||
use url::{Host, Url};
|
||||
|
||||
use crate::agents::{Detail, SessionState};
|
||||
|
||||
/// The height of the tab strip, in points. The window's other web views start
|
||||
/// below it.
|
||||
pub const STRIP_HEIGHT: f64 = 38.0;
|
||||
/// Where the window's traffic lights go so they sit centred in the strip: the
|
||||
/// close button's left edge and the buttons' centre line, in points.
|
||||
pub const TRAFFIC_LIGHTS: (f64, f64) = (14.0, 19.0);
|
||||
/// The longest tab name the strip accepts, in characters.
|
||||
pub const MAX_NAME: usize = 40;
|
||||
/// How many session rows a card of the overview gets.
|
||||
pub const OVERVIEW_ROWS: usize = 4;
|
||||
/// How many closed tabs Reopen Closed Tab remembers.
|
||||
pub const MAX_CLOSED: usize = 10;
|
||||
|
||||
/// The colours a new tab is given, in turn: violet, cyan, emerald, pink,
|
||||
/// amber, slate. None of them is the red, amber dot or blue of a status badge
|
||||
/// at the same lightness, so a stripe never reads as an alert.
|
||||
pub const PALETTE: [&str; 6] = ["#a78bfa", "#22d3ee", "#34d399", "#f472b6", "#f59e0b", "#94a3b8"];
|
||||
/// The names the right-click menu gives the palette, in the same order.
|
||||
pub const PALETTE_NAMES: [&str; 6] = ["Violet", "Cyan", "Green", "Pink", "Amber", "Slate"];
|
||||
|
||||
/// A colour the strip may draw: `#rrggbb` and nothing else, so a value read
|
||||
/// from the settings file can never carry CSS.
|
||||
pub fn is_color(value: &str) -> bool {
|
||||
value.len() == 7 && value.starts_with('#') && value[1..].bytes().all(|b| b.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
/// The first palette colour no open tab uses, else the palette again in turn.
|
||||
pub fn next_color<'a>(used: impl IntoIterator<Item = &'a str>) -> String {
|
||||
let used: Vec<String> = used.into_iter().map(str::to_ascii_lowercase).collect();
|
||||
PALETTE
|
||||
.iter()
|
||||
.find(|c| !used.iter().any(|u| u == *c))
|
||||
.copied()
|
||||
.unwrap_or(PALETTE[used.len() % PALETTE.len()])
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// What a tab is called until the user names it: `This Mac` for a server on
|
||||
/// loopback, else the first label of its host name (`studio` for
|
||||
/// `studio.example.ts.net`), or the whole address for an IP literal. A port
|
||||
/// other than Codeman's 3000 (or the scheme's own) is added, so two servers on
|
||||
/// one machine do not look alike.
|
||||
pub fn default_name(url: &Url) -> String {
|
||||
let base = match url.host() {
|
||||
_ if crate::policy::is_loopback(url) => "This Mac".to_string(),
|
||||
Some(Host::Domain(name)) => name
|
||||
.split('.')
|
||||
.next()
|
||||
.filter(|l| !l.is_empty())
|
||||
.unwrap_or(name)
|
||||
.to_string(),
|
||||
Some(Host::Ipv4(ip)) => ip.to_string(),
|
||||
Some(Host::Ipv6(ip)) => format!("[{ip}]"),
|
||||
None => url.as_str().to_string(),
|
||||
};
|
||||
match url.port() {
|
||||
Some(port) if port != 3000 => format!("{base}:{port}"),
|
||||
_ => base,
|
||||
}
|
||||
}
|
||||
|
||||
/// A name the user typed, cleaned: trimmed, control characters dropped, cut at
|
||||
/// `MAX_NAME` characters. None when nothing is left, which puts the default
|
||||
/// name back.
|
||||
pub fn clean_name(raw: &str) -> Option<String> {
|
||||
let kept: String = raw.chars().filter(|c| !c.is_control()).collect();
|
||||
let trimmed: String = kept.trim().chars().take(MAX_NAME).collect();
|
||||
let trimmed = trimmed.trim_end().to_string();
|
||||
(!trimmed.is_empty()).then_some(trimmed)
|
||||
}
|
||||
|
||||
/// What a rename the strip finished does to a tab's own name: None, nothing
|
||||
/// (it ended without a change: Escape, or Enter on the same text, sends the
|
||||
/// name the tab shows, and kept, that would pin "New server" to a tab before
|
||||
/// it has a server); `Some(None)`, back to the default name (an empty name,
|
||||
/// or the default typed out); `Some(Some(name))`, that name.
|
||||
pub fn renamed(typed: &str, shown: &str, default: Option<&str>) -> Option<Option<String>> {
|
||||
let Some(name) = clean_name(typed) else {
|
||||
return Some(None);
|
||||
};
|
||||
if clean_name(shown).as_deref() == Some(name.as_str()) {
|
||||
return None;
|
||||
}
|
||||
Some((default != Some(name.as_str())).then_some(name))
|
||||
}
|
||||
|
||||
/// The identifier of the WebKit data store (cookies and local storage) that a
|
||||
/// server's pages use. Each server gets one of its own, so two servers on one
|
||||
/// host (a Codeman on port 3000 and a beta on 5000) never share a login cookie,
|
||||
/// which carries the same name on both and is not told apart by port. Derived
|
||||
/// from the server's address, so the same server finds its store, and with it
|
||||
/// Codeman's per-device settings, at every launch. Two 64-bit FNV-1a hashes
|
||||
/// with different starting values: stable across Rust releases, which the
|
||||
/// standard library's hasher is not promised to be.
|
||||
pub fn store_id(server: &str) -> [u8; 16] {
|
||||
fn fnv(bytes: &[u8], basis: u64) -> u64 {
|
||||
bytes
|
||||
.iter()
|
||||
.fold(basis, |hash, b| (hash ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3))
|
||||
}
|
||||
let bytes = server.as_bytes();
|
||||
let hi = fnv(bytes, 0xcbf2_9ce4_8422_2325);
|
||||
let lo = fnv(bytes, 0x8422_2325_cbf2_9ce4 ^ 0x5eed);
|
||||
let mut id = [0u8; 16];
|
||||
id[..8].copy_from_slice(&hi.to_be_bytes());
|
||||
id[8..].copy_from_slice(&lo.to_be_bytes());
|
||||
// A well-formed UUID: version 8 (custom), RFC 4122 variant.
|
||||
id[6] = (id[6] & 0x0f) | 0x80;
|
||||
id[8] = (id[8] & 0x3f) | 0x80;
|
||||
id
|
||||
}
|
||||
|
||||
/// Where `from` lands when the strip asks to move it to `to`, both indexes
|
||||
/// into a list of `len`. None for an index out of range or no move.
|
||||
pub fn moved(len: usize, from: usize, to: usize) -> Option<usize> {
|
||||
(from < len && to < len && from != to).then_some(to)
|
||||
}
|
||||
|
||||
/// The tab after (or before) `active` in a list of `len`, wrapping around.
|
||||
pub fn neighbour(len: usize, active: usize, forward: bool) -> Option<usize> {
|
||||
match len {
|
||||
0 => None,
|
||||
_ if forward => Some((active + 1) % len),
|
||||
_ => Some((active + len - 1) % len),
|
||||
}
|
||||
}
|
||||
|
||||
/// Which tab to show after closing the one at `closed` (of `len` before the
|
||||
/// close), when it was the active one: the tab that took its place, else the
|
||||
/// one before it.
|
||||
pub fn after_close(len: usize, closed: usize) -> Option<usize> {
|
||||
match len {
|
||||
0 | 1 => None,
|
||||
_ if closed + 1 < len => Some(closed),
|
||||
_ => Some(closed - 1),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `id` can be handed to Codeman's page as a session id: what Codeman
|
||||
/// makes (UUIDs) and nothing that could step out of a string.
|
||||
pub fn is_session_id(id: &str) -> bool {
|
||||
!id.is_empty() && id.len() <= 128 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||
}
|
||||
|
||||
/// What a tab shows.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Kind {
|
||||
/// The connect page, nothing chosen yet.
|
||||
Connect,
|
||||
/// A server's page is on its way; the connect page still shows.
|
||||
Loading,
|
||||
/// A server's page.
|
||||
Server,
|
||||
}
|
||||
|
||||
/// What the badges of a tab are counted from: the last status read of its
|
||||
/// server, and whether that server answers at all.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Seen {
|
||||
pub detail: Option<Detail>,
|
||||
/// The last few reads failed.
|
||||
pub offline: bool,
|
||||
/// The server refused the login: nothing is asked any more.
|
||||
pub refused: bool,
|
||||
}
|
||||
|
||||
/// One tab as the strip and the overview see it.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct View<'a> {
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
pub color: &'a str,
|
||||
pub kind: Kind,
|
||||
pub url: Option<&'a Url>,
|
||||
pub version: Option<&'a str>,
|
||||
pub seen: &'a Seen,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, PartialEq, Eq, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Counts {
|
||||
pub needs_you: usize,
|
||||
pub waiting: usize,
|
||||
pub working: usize,
|
||||
pub sessions: usize,
|
||||
}
|
||||
|
||||
fn counts(seen: &Seen) -> Counts {
|
||||
let Some(detail) = &seen.detail else {
|
||||
return Counts::default();
|
||||
};
|
||||
let of = |state: SessionState| detail.sessions.iter().filter(|s| s.state == state).count();
|
||||
Counts {
|
||||
needs_you: of(SessionState::Needs),
|
||||
waiting: of(SessionState::Waiting),
|
||||
working: of(SessionState::Working),
|
||||
sessions: detail.sessions.len(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct StripStatus {
|
||||
working: usize,
|
||||
waiting: usize,
|
||||
needs_you: usize,
|
||||
offline: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct StripTab<'a> {
|
||||
id: u64,
|
||||
name: &'a str,
|
||||
color: &'a str,
|
||||
active: bool,
|
||||
kind: Kind,
|
||||
local: bool,
|
||||
url: Option<&'a str>,
|
||||
key: Option<usize>,
|
||||
status: StripStatus,
|
||||
}
|
||||
|
||||
/// The ⌘ number of the tab at `index`: ⌘1 to ⌘8 for the first eight, ⌘9 for
|
||||
/// the last one, as in Safari.
|
||||
pub fn key_of(index: usize, len: usize) -> Option<usize> {
|
||||
match index {
|
||||
_ if index + 1 == len && len > 8 => Some(9),
|
||||
i if i < 8 => Some(i + 1),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The tab ⌘`key` selects in a list of `len`.
|
||||
pub fn index_of_key(key: usize, len: usize) -> Option<usize> {
|
||||
match key {
|
||||
9 if len > 0 => Some(len - 1),
|
||||
k @ 1..=8 if k <= len => Some(k - 1),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The strip's whole state (`assets/tabs.html`, message `state`).
|
||||
pub fn strip_state(tabs: &[View<'_>], active: Option<usize>, overview: bool, fullscreen: bool) -> serde_json::Value {
|
||||
let len = tabs.len();
|
||||
let list: Vec<StripTab<'_>> = tabs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, t)| {
|
||||
let c = counts(t.seen);
|
||||
StripTab {
|
||||
id: t.id,
|
||||
name: &t.name,
|
||||
color: t.color,
|
||||
active: !overview && active == Some(i),
|
||||
kind: t.kind,
|
||||
local: t.url.is_some_and(crate::policy::is_loopback),
|
||||
url: t.url.map(Url::as_str),
|
||||
key: key_of(i, len),
|
||||
status: StripStatus {
|
||||
working: c.working,
|
||||
waiting: c.waiting,
|
||||
needs_you: c.needs_you,
|
||||
offline: t.kind == Kind::Server && t.seen.offline,
|
||||
},
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
serde_json::json!({
|
||||
"type": "state",
|
||||
"tabs": list,
|
||||
"overviewActive": overview,
|
||||
"fullscreen": fullscreen,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Row<'a> {
|
||||
id: &'a str,
|
||||
name: &'a str,
|
||||
state: SessionState,
|
||||
text: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Card<'a> {
|
||||
tab: u64,
|
||||
name: &'a str,
|
||||
color: &'a str,
|
||||
url: Option<&'a str>,
|
||||
local: bool,
|
||||
key: Option<usize>,
|
||||
version: Option<&'a str>,
|
||||
kind: Kind,
|
||||
offline: bool,
|
||||
refused: bool,
|
||||
sessions: Vec<Row<'a>>,
|
||||
counts: Counts,
|
||||
}
|
||||
|
||||
/// The overview's whole state (`assets/overview.html`, message `state`): a
|
||||
/// card per tab, the servers that need someone first, then those with an agent
|
||||
/// waiting, then the rest in tab order. Each card lists its sessions most
|
||||
/// urgent first, `OVERVIEW_ROWS` at most.
|
||||
pub fn overview_state(tabs: &[View<'_>]) -> serde_json::Value {
|
||||
let len = tabs.len();
|
||||
let mut cards: Vec<(usize, Card<'_>)> = tabs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, t)| {
|
||||
let mut rows: Vec<Row<'_>> = t
|
||||
.seen
|
||||
.detail
|
||||
.iter()
|
||||
.flat_map(|d| d.sessions.iter())
|
||||
.map(|s| Row {
|
||||
id: &s.id,
|
||||
name: &s.name,
|
||||
state: s.state,
|
||||
text: &s.text,
|
||||
})
|
||||
.collect();
|
||||
rows.sort_by_key(|r| r.state.rank());
|
||||
rows.truncate(OVERVIEW_ROWS);
|
||||
(
|
||||
i,
|
||||
Card {
|
||||
tab: t.id,
|
||||
name: &t.name,
|
||||
color: t.color,
|
||||
url: t.url.map(Url::as_str),
|
||||
local: t.url.is_some_and(crate::policy::is_loopback),
|
||||
key: key_of(i, len),
|
||||
version: t.version,
|
||||
kind: t.kind,
|
||||
offline: t.kind == Kind::Server && t.seen.offline,
|
||||
refused: t.seen.refused,
|
||||
sessions: rows,
|
||||
counts: counts(t.seen),
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
cards.sort_by_key(|(i, card)| {
|
||||
let urgency = match (card.counts.needs_you, card.counts.waiting) {
|
||||
(n, _) if n > 0 => 0,
|
||||
(_, w) if w > 0 => 1,
|
||||
_ => 2,
|
||||
};
|
||||
(urgency, *i)
|
||||
});
|
||||
let servers: Vec<Card<'_>> = cards.into_iter().map(|(_, c)| c).collect();
|
||||
serde_json::json!({ "type": "state", "servers": servers })
|
||||
}
|
||||
|
||||
/// The window title while a tab shows: the page's own title, else the tab's
|
||||
/// name.
|
||||
pub fn window_title(page_title: Option<&str>, name: &str) -> String {
|
||||
match page_title.map(str::trim) {
|
||||
Some(t) if !t.is_empty() => t.to_string(),
|
||||
_ => name.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether two server addresses are on the same host (scheme and port aside):
|
||||
/// the case where, without a data store of their own, they would share a login
|
||||
/// cookie.
|
||||
pub fn same_host(a: &Url, b: &Url) -> bool {
|
||||
match (a.host_str(), b.host_str()) {
|
||||
(Some(x), Some(y)) => x.eq_ignore_ascii_case(y),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::agents::SessionRow;
|
||||
|
||||
fn u(s: &str) -> Url {
|
||||
Url::parse(s).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colours_are_hex_only() {
|
||||
assert!(is_color("#a78bfa"));
|
||||
assert!(is_color("#A78BFA"));
|
||||
assert!(!is_color("a78bfa"));
|
||||
assert!(!is_color("#a78bf"));
|
||||
assert!(!is_color("#a78bfg"));
|
||||
assert!(!is_color("red;background:url(x)"));
|
||||
assert!(!is_color("#a78bfa;"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_tabs_take_the_first_free_colour() {
|
||||
assert_eq!(next_color([]), PALETTE[0]);
|
||||
assert_eq!(next_color([PALETTE[0]]), PALETTE[1]);
|
||||
assert_eq!(next_color([PALETTE[1], "#A78BFA"]), PALETTE[2]);
|
||||
let all: Vec<&str> = PALETTE.to_vec();
|
||||
assert_eq!(next_color(all.clone()), PALETTE[0]);
|
||||
let mut seven = all;
|
||||
seven.push(PALETTE[0]);
|
||||
assert_eq!(next_color(seven), PALETTE[1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_names() {
|
||||
assert_eq!(default_name(&u("http://127.0.0.1:3000/")), "This Mac");
|
||||
assert_eq!(default_name(&u("http://localhost:3000/")), "This Mac");
|
||||
assert_eq!(default_name(&u("http://127.0.0.1:5000/")), "This Mac:5000");
|
||||
assert_eq!(default_name(&u("https://studio.example.ts.net/")), "studio");
|
||||
assert_eq!(default_name(&u("http://build-01.lan:3000/")), "build-01");
|
||||
assert_eq!(default_name(&u("http://192.168.1.40:3000/")), "192.168.1.40");
|
||||
assert_eq!(
|
||||
default_name(&u("http://192.168.1.40:8080/codeman/")),
|
||||
"192.168.1.40:8080"
|
||||
);
|
||||
assert_eq!(default_name(&u("http://[fd00::1]:3000/")), "[fd00::1]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_are_cleaned() {
|
||||
assert_eq!(clean_name(" studio ").as_deref(), Some("studio"));
|
||||
assert_eq!(clean_name("a\u{0}b\nc").as_deref(), Some("abc"));
|
||||
assert_eq!(clean_name(" "), None);
|
||||
assert_eq!(clean_name(""), None);
|
||||
let long = "x".repeat(100);
|
||||
assert_eq!(clean_name(&long).map(|n| n.chars().count()), Some(MAX_NAME));
|
||||
// Characters, not bytes: a multi-byte name is not cut inside a character.
|
||||
let wide = "ü".repeat(60);
|
||||
assert_eq!(clean_name(&wide).map(|n| n.chars().count()), Some(MAX_NAME));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renames() {
|
||||
// Escape on a new tab sends back what it shows: nothing changes.
|
||||
assert_eq!(renamed("New server", "New server", None), None);
|
||||
assert_eq!(renamed(" studio ", "studio", Some("studio")), None);
|
||||
assert_eq!(
|
||||
renamed("prod box", "studio", Some("studio")),
|
||||
Some(Some("prod box".into()))
|
||||
);
|
||||
// The default typed out, or nothing at all, is the default again.
|
||||
assert_eq!(renamed("studio", "prod box", Some("studio")), Some(None));
|
||||
assert_eq!(renamed(" ", "prod box", Some("studio")), Some(None));
|
||||
// A shown name longer than a name may be, sent back unchanged.
|
||||
let long = "x".repeat(60);
|
||||
assert_eq!(renamed(&long, &long, None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn store_ids_are_stable_and_distinct() {
|
||||
let a = store_id("http://127.0.0.1:3000/");
|
||||
assert_eq!(a, store_id("http://127.0.0.1:3000/"));
|
||||
assert_ne!(a, store_id("http://127.0.0.1:5000/"));
|
||||
assert_ne!(a, store_id("http://127.0.0.1:3000/x/"));
|
||||
// Version 8, RFC 4122 variant.
|
||||
assert_eq!(a[6] >> 4, 8);
|
||||
assert_eq!(a[8] >> 6, 0b10);
|
||||
// Pinned, so a change of the hash (which would cost every server its
|
||||
// local storage) fails here first.
|
||||
assert_eq!(
|
||||
store_id(""),
|
||||
[0xcb, 0xf2, 0x9c, 0xe4, 0x84, 0x22, 0x83, 0x25, 0x84, 0x22, 0x23, 0x25, 0xcb, 0xf2, 0xc2, 0x09]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn order_helpers() {
|
||||
assert_eq!(moved(3, 0, 2), Some(2));
|
||||
assert_eq!(moved(3, 1, 1), None);
|
||||
assert_eq!(moved(3, 3, 0), None);
|
||||
assert_eq!(moved(3, 0, 3), None);
|
||||
assert_eq!(neighbour(3, 2, true), Some(0));
|
||||
assert_eq!(neighbour(3, 0, false), Some(2));
|
||||
assert_eq!(neighbour(0, 0, true), None);
|
||||
assert_eq!(after_close(3, 0), Some(0));
|
||||
assert_eq!(after_close(3, 2), Some(1));
|
||||
assert_eq!(after_close(1, 0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_numbers() {
|
||||
assert_eq!(key_of(0, 3), Some(1));
|
||||
assert_eq!(key_of(2, 3), Some(3));
|
||||
assert_eq!(key_of(7, 12), Some(8));
|
||||
assert_eq!(key_of(8, 12), None);
|
||||
assert_eq!(key_of(11, 12), Some(9));
|
||||
assert_eq!(key_of(8, 9), Some(9));
|
||||
assert_eq!(index_of_key(1, 3), Some(0));
|
||||
assert_eq!(index_of_key(3, 3), Some(2));
|
||||
assert_eq!(index_of_key(4, 3), None);
|
||||
assert_eq!(index_of_key(9, 3), Some(2));
|
||||
assert_eq!(index_of_key(9, 0), None);
|
||||
assert_eq!(index_of_key(0, 3), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_ids() {
|
||||
assert!(is_session_id("0f8d0215-661e-4a1c-bfad-d7f6fd2ed4b5"));
|
||||
assert!(!is_session_id(""));
|
||||
assert!(!is_session_id("a'b"));
|
||||
assert!(!is_session_id("a\"); alert(1); (\""));
|
||||
assert!(!is_session_id(&"a".repeat(129)));
|
||||
}
|
||||
|
||||
fn row(id: &str, state: SessionState) -> SessionRow {
|
||||
SessionRow {
|
||||
id: id.into(),
|
||||
name: id.into(),
|
||||
state,
|
||||
text: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn seen(rows: Vec<SessionRow>) -> Seen {
|
||||
Seen {
|
||||
detail: Some(Detail { sessions: rows }),
|
||||
offline: false,
|
||||
refused: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strip_state_marks_the_active_tab_and_counts() {
|
||||
let a = u("http://127.0.0.1:3000/");
|
||||
let b = u("https://studio.example.ts.net/");
|
||||
let busy = seen(vec![
|
||||
row("1", SessionState::Working),
|
||||
row("2", SessionState::Needs),
|
||||
row("3", SessionState::Needs),
|
||||
row("4", SessionState::Waiting),
|
||||
]);
|
||||
let none = Seen {
|
||||
offline: true,
|
||||
..Seen::default()
|
||||
};
|
||||
let tabs = [
|
||||
View {
|
||||
id: 1,
|
||||
name: "This Mac".into(),
|
||||
color: PALETTE[0],
|
||||
kind: Kind::Server,
|
||||
url: Some(&a),
|
||||
version: None,
|
||||
seen: &busy,
|
||||
},
|
||||
View {
|
||||
id: 2,
|
||||
name: "studio".into(),
|
||||
color: PALETTE[1],
|
||||
kind: Kind::Server,
|
||||
url: Some(&b),
|
||||
version: None,
|
||||
seen: &none,
|
||||
},
|
||||
];
|
||||
let state = strip_state(&tabs, Some(1), false, true);
|
||||
assert_eq!(state["type"], "state");
|
||||
assert_eq!(state["fullscreen"], true);
|
||||
assert_eq!(state["tabs"][0]["active"], false);
|
||||
assert_eq!(state["tabs"][1]["active"], true);
|
||||
assert_eq!(state["tabs"][0]["local"], true);
|
||||
assert_eq!(state["tabs"][0]["status"]["needsYou"], 2);
|
||||
assert_eq!(state["tabs"][0]["status"]["waiting"], 1);
|
||||
assert_eq!(state["tabs"][0]["status"]["working"], 1);
|
||||
assert_eq!(state["tabs"][1]["status"]["offline"], true);
|
||||
assert_eq!(state["tabs"][1]["key"], 2);
|
||||
// The overview takes the place of the active tab.
|
||||
let state = strip_state(&tabs, Some(1), true, false);
|
||||
assert_eq!(state["tabs"][1]["active"], false);
|
||||
assert_eq!(state["overviewActive"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overview_puts_urgent_servers_and_sessions_first() {
|
||||
let a = u("http://127.0.0.1:3000/");
|
||||
let b = u("https://studio.example.ts.net/");
|
||||
let calm = seen(vec![row("w", SessionState::Working), row("i", SessionState::Idle)]);
|
||||
let urgent = seen(vec![
|
||||
row("i1", SessionState::Idle),
|
||||
row("i2", SessionState::Idle),
|
||||
row("w1", SessionState::Working),
|
||||
row("n1", SessionState::Needs),
|
||||
row("y1", SessionState::Waiting),
|
||||
row("i3", SessionState::Idle),
|
||||
]);
|
||||
let tabs = [
|
||||
View {
|
||||
id: 10,
|
||||
name: "This Mac".into(),
|
||||
color: PALETTE[0],
|
||||
kind: Kind::Server,
|
||||
url: Some(&a),
|
||||
version: Some("1.51.0"),
|
||||
seen: &calm,
|
||||
},
|
||||
View {
|
||||
id: 11,
|
||||
name: "studio".into(),
|
||||
color: PALETTE[1],
|
||||
kind: Kind::Server,
|
||||
url: Some(&b),
|
||||
version: None,
|
||||
seen: &urgent,
|
||||
},
|
||||
];
|
||||
let state = overview_state(&tabs);
|
||||
let servers = state["servers"].as_array().unwrap();
|
||||
assert_eq!(servers[0]["tab"], 11);
|
||||
assert_eq!(servers[0]["key"], 2);
|
||||
assert_eq!(servers[1]["tab"], 10);
|
||||
let rows: Vec<&str> = servers[0]["sessions"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|r| r["id"].as_str().unwrap())
|
||||
.collect();
|
||||
assert_eq!(rows, ["n1", "y1", "w1", "i1"]);
|
||||
assert_eq!(servers[0]["counts"]["sessions"], 6);
|
||||
assert_eq!(servers[0]["sessions"][0]["state"], "needs");
|
||||
assert_eq!(servers[1]["version"], "1.51.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn titles_and_hosts() {
|
||||
assert_eq!(window_title(Some(" Codeman "), "atlas"), "Codeman");
|
||||
assert_eq!(window_title(Some(""), "atlas"), "atlas");
|
||||
assert_eq!(window_title(None, "atlas"), "atlas");
|
||||
assert!(same_host(&u("http://127.0.0.1:3000/"), &u("http://127.0.0.1:5000/")));
|
||||
assert!(same_host(&u("http://Studio.lan:3000/"), &u("https://studio.lan/")));
|
||||
assert!(!same_host(&u("http://127.0.0.1:3000/"), &u("http://localhost:3000/")));
|
||||
}
|
||||
}
|
||||
@@ -157,7 +157,6 @@ console.log('\n[build] content-hash cache busting');
|
||||
'settings-ui.js',
|
||||
'panels-ui.js',
|
||||
'session-ui.js',
|
||||
'ralph-wizard.js',
|
||||
'api-client.js',
|
||||
'subagent-windows.js',
|
||||
'image-input.js',
|
||||
|
||||
@@ -1,482 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* capture-readme-gifs.mjs
|
||||
*
|
||||
* Deterministic README GIFs — no real server, Claude CLI, or tmux. Reuses the
|
||||
* mock-injection pipeline from capture-readme-screenshots.mjs (static file
|
||||
* server + page.route mocks), drives a scripted timeline in the page, records
|
||||
* it with Playwright video, and converts to GIF via ffmpeg palette encoding.
|
||||
*
|
||||
* Scenes:
|
||||
* 1. subagent-demo.gif — terminal spawns 3 parallel agents; floating agent
|
||||
* windows open one by one and stream tool-call activity live (driven
|
||||
* through the real _onSubagentDiscovered/_onSubagentToolCall handlers).
|
||||
* 2. zerolag-demo.gif — side-by-side typing: instant local echo (zerolag)
|
||||
* vs bursty ~350 ms server echo, rendered with the vendored xterm.
|
||||
*
|
||||
* Usage: node scripts/capture-readme-gifs.mjs
|
||||
* SCREENSHOT_OUT_DIR=/path/to/review node scripts/capture-readme-gifs.mjs
|
||||
* Output: docs/images/ (or flat into SCREENSHOT_OUT_DIR)
|
||||
* Requires: ffmpeg
|
||||
*/
|
||||
|
||||
import { chromium } from 'playwright';
|
||||
import { execSync } from 'child_process';
|
||||
import { mkdtempSync, rmSync } from 'fs';
|
||||
import { tmpdir } from 'os';
|
||||
import { join } from 'path';
|
||||
import {
|
||||
PORT,
|
||||
SESSION_IDS,
|
||||
STANDARD_SESSIONS,
|
||||
buildInitPayload,
|
||||
startStaticServer,
|
||||
setupRoutes,
|
||||
injectState,
|
||||
outPath,
|
||||
RST, GRN, YEL, MAG, CYN, GRY, BOLD,
|
||||
} from './capture-readme-screenshots.mjs';
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
const GIF_COLORS = 192;
|
||||
|
||||
// ─── ffmpeg conversion (palette recipe from capture-subagent-gif.mjs) ────────
|
||||
|
||||
function webmToGif(videoPath, gifPath, { ss, duration, width, fps }) {
|
||||
// One GLOBAL palette (default stats_mode=full) + ordered dither: per-frame
|
||||
// palettes (stats_mode=single:new=1) make dirty rectangles visibly mismatch
|
||||
// on flat dark UI, and error-diffusion dither shimmers between frames.
|
||||
const filters = `fps=${fps},scale=${width}:-1:flags=lanczos`;
|
||||
execSync(
|
||||
`ffmpeg -y -loglevel error -ss ${ss.toFixed(2)} -t ${duration} -i "${videoPath}" ` +
|
||||
`-vf "${filters},split[s0][s1];[s0]palettegen=max_colors=${GIF_COLORS}:reserve_transparent=0[p];` +
|
||||
`[s1][p]paletteuse=dither=bayer:bayer_scale=5:diff_mode=rectangle" "${gifPath}"`,
|
||||
{ stdio: 'inherit' }
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Scene 1: subagent demo ──────────────────────────────────────────────────
|
||||
|
||||
const SUBAGENT_VIEWPORT = { width: 1440, height: 810 };
|
||||
|
||||
// Terminal content visible before the agents spawn
|
||||
const TERMINAL_PRESPAWN = [
|
||||
'',
|
||||
`${GRN}●${RST} Working on ${CYN}/home/arkon/codeman-cases/testcase${RST} - I'll use the ${BOLD}Task tool${RST} to spawn parallel agents.`,
|
||||
'',
|
||||
`${GRN}●${RST} ${BOLD}Read${RST}(/home/arkon/codeman-cases/testcase/CLAUDE.md)`,
|
||||
` ${GRY}░${RST} Read ${BOLD}127${RST} lines ${GRY}│${RST} ${CYN}1.2KB${RST}`,
|
||||
'',
|
||||
`${GRN}●${RST} ${BOLD}Bash${RST}(find . -name "*.ts" -not -path "*/node_modules/*" | head -20)`,
|
||||
` ${GRY}░${RST} ./src/index.ts`,
|
||||
` ${GRY}░${RST} ./src/session.ts`,
|
||||
` ${GRY}░${RST} ./src/web/server.ts`,
|
||||
` ${GRY}░${RST} ${GRY}... (17 more)${RST}`,
|
||||
'',
|
||||
`${GRN}●${RST} I'll spawn 3 parallel research agents to analyze different parts of the codebase simultaneously.`,
|
||||
'',
|
||||
].join('\r\n');
|
||||
|
||||
function makeAgent(agentId, description, startedOffsetMs) {
|
||||
return {
|
||||
agentId,
|
||||
sessionId: 'claude-sess-w1-0001',
|
||||
projectHash: 'abc123',
|
||||
filePath: `/tmp/${agentId}.jsonl`,
|
||||
startedAt: new Date(Date.now() - startedOffsetMs).toISOString(),
|
||||
lastActivityAt: Date.now(),
|
||||
status: 'active',
|
||||
toolCallCount: 0,
|
||||
entryCount: 0,
|
||||
fileSize: 4000,
|
||||
description,
|
||||
model: 'claude-haiku-4-5-20251001',
|
||||
modelShort: 'haiku',
|
||||
totalInputTokens: 0,
|
||||
totalOutputTokens: 0,
|
||||
parentSessionId: SESSION_IDS.w1,
|
||||
};
|
||||
}
|
||||
|
||||
// Timeline events: t (ms from scene start) + kind
|
||||
// term — write raw data to the session terminal
|
||||
// discover — register subagent + open + position its floating window
|
||||
// tool — stream a tool call into an agent window
|
||||
// msg — stream an assistant message into an agent window
|
||||
// complete — flip an agent to completed
|
||||
function buildSubagentTimeline() {
|
||||
const T = (lines) => lines.join('\r\n') + '\r\n';
|
||||
const tool = (t, agentId, name, input) => ({ t, kind: 'tool', agentId, tool: name, input });
|
||||
const msg = (t, agentId, text) => ({ t, kind: 'msg', agentId, text });
|
||||
|
||||
return [
|
||||
{
|
||||
t: 600,
|
||||
kind: 'term',
|
||||
data: T([
|
||||
`${GRN}●${RST} ${BOLD}Task${RST}(Find and document all API endpoints in src/)`,
|
||||
` ${GRY}░${RST} Spawned ${CYN}agent-001${RST} ${GRY}(haiku)${RST}`,
|
||||
'',
|
||||
]),
|
||||
},
|
||||
{
|
||||
t: 1000,
|
||||
kind: 'discover',
|
||||
agent: makeAgent('agent-001', 'Find and document all API endpoints in src/', 2000),
|
||||
x: 440, y: 45,
|
||||
},
|
||||
tool(1500, 'agent-001', 'Glob', { pattern: 'src/**/*.ts' }),
|
||||
{
|
||||
t: 2000,
|
||||
kind: 'term',
|
||||
data: T([
|
||||
`${GRN}●${RST} ${BOLD}Task${RST}(Explore and understand test structure in test/)`,
|
||||
` ${GRY}░${RST} Spawned ${CYN}agent-002${RST} ${GRY}(haiku)${RST}`,
|
||||
'',
|
||||
]),
|
||||
},
|
||||
tool(2200, 'agent-001', 'Read', { file_path: '/home/arkon/codeman/src/web/server.ts' }),
|
||||
{
|
||||
t: 2500,
|
||||
kind: 'discover',
|
||||
agent: makeAgent('agent-002', 'Explore and understand test structure in test/', 1200),
|
||||
x: 880, y: 45,
|
||||
},
|
||||
tool(3000, 'agent-002', 'Glob', { pattern: 'test/**/*.test.ts' }),
|
||||
{
|
||||
t: 3300,
|
||||
kind: 'term',
|
||||
data: T([
|
||||
`${GRN}●${RST} ${BOLD}Task${RST}(Analyze TypeScript type definitions in src/types.ts)`,
|
||||
` ${GRY}░${RST} Spawned ${CYN}agent-003${RST} ${GRY}(haiku)${RST}`,
|
||||
'',
|
||||
]),
|
||||
},
|
||||
tool(3500, 'agent-001', 'Grep', { pattern: 'app\\.get|app\\.post|app\\.delete', path: 'src/' }),
|
||||
{
|
||||
t: 3800,
|
||||
kind: 'discover',
|
||||
agent: makeAgent('agent-003', 'Analyze TypeScript type definitions in src/types.ts', 400),
|
||||
x: 660, y: 400,
|
||||
},
|
||||
tool(4100, 'agent-002', 'Read', { file_path: '/home/arkon/codeman/test/respawn-test-utils.ts' }),
|
||||
{
|
||||
t: 4500,
|
||||
kind: 'term',
|
||||
data: T([
|
||||
`${MAG}✻${RST} ${YEL}Waiting for agents...${RST} ${GRY}(${BOLD}esc${RST}${GRY} to interrupt · 32s · ↓ 1.7k tokens · thinking)${RST}`,
|
||||
'',
|
||||
]),
|
||||
},
|
||||
tool(4700, 'agent-003', 'Read', { file_path: '/home/arkon/codeman/src/types.ts' }),
|
||||
tool(5200, 'agent-001', 'Read', { file_path: '/home/arkon/codeman/src/web/schemas.ts' }),
|
||||
tool(5600, 'agent-002', 'Read', { file_path: '/home/arkon/codeman/config/vitest.config.ts' }),
|
||||
tool(6100, 'agent-003', 'Grep', { pattern: 'export (interface|type)', path: 'src/types/' }),
|
||||
msg(6700, 'agent-001', 'Found 47 API endpoints across server.ts. Documenting REST paths...'),
|
||||
tool(7100, 'agent-002', 'Grep', { pattern: 'const PORT =', path: 'test/' }),
|
||||
msg(7700, 'agent-002', 'Analyzing test patterns: MockSession, unique ports, fileParallelism: false...'),
|
||||
tool(8100, 'agent-003', 'Read', { file_path: '/home/arkon/codeman/src/types/index.ts' }),
|
||||
msg(8700, 'agent-003', 'Mapped 38 exported interfaces across 15 domain files. Building summary...'),
|
||||
{
|
||||
t: 9300,
|
||||
kind: 'term',
|
||||
data: T([
|
||||
`${GRN}●${RST} ${CYN}agent-001${RST}: ${GRY}12 tool calls — Glob, Read(server.ts), Grep(endpoints)...${RST}`,
|
||||
`${GRN}●${RST} ${CYN}agent-002${RST}: ${GRY}8 tool calls — Glob, Read(test-utils), Read(vitest.config)...${RST}`,
|
||||
`${GRN}●${RST} ${CYN}agent-003${RST}: ${GRY}7 tool calls — Read(types.ts), Grep(interface)...${RST}`,
|
||||
'',
|
||||
]),
|
||||
},
|
||||
tool(10100, 'agent-001', 'Glob', { pattern: 'src/web/routes/*.ts' }),
|
||||
tool(10600, 'agent-002', 'Read', { file_path: '/home/arkon/codeman/test/setup.ts' }),
|
||||
tool(11100, 'agent-003', 'Grep', { pattern: 'assertNever', path: 'src/' }),
|
||||
{
|
||||
t: 11600,
|
||||
kind: 'term',
|
||||
data: T([`${GRN}●${RST} ${GRY}171.8k, 13s${RST} ${GRY}│${RST} ${GRY}1.7k tokens${RST} ${GRY}│${RST} ${GRY}thinking${RST}`, '']),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const SUBAGENT_TAIL_HOLD = 2500; // hold the final frame
|
||||
|
||||
async function recordSubagentScene(browser, videoDir) {
|
||||
console.log('\n1/2 Recording subagent-demo...');
|
||||
|
||||
const context = await browser.newContext({
|
||||
viewport: SUBAGENT_VIEWPORT,
|
||||
deviceScaleFactor: 1,
|
||||
recordVideo: { dir: videoDir, size: SUBAGENT_VIEWPORT },
|
||||
});
|
||||
const recStart = Date.now();
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
|
||||
// Start with NO subagents — they appear during the recording
|
||||
const initPayload = buildInitPayload(STANDARD_SESSIONS);
|
||||
await setupRoutes(page, initPayload, TERMINAL_PRESPAWN);
|
||||
await page.goto(`http://localhost:${PORT}`, { waitUntil: 'domcontentloaded' });
|
||||
await injectState(page, initPayload, TERMINAL_PRESPAWN, SESSION_IDS.w1);
|
||||
|
||||
await page.evaluate(() => {
|
||||
try { window.app?.fitAddon?.fit(); } catch {}
|
||||
window.app?.terminal?.scrollToBottom();
|
||||
});
|
||||
await sleep(500);
|
||||
|
||||
const timeline = buildSubagentTimeline();
|
||||
const totalMs = Math.max(...timeline.map((e) => e.t)) + SUBAGENT_TAIL_HOLD;
|
||||
const sceneStart = Date.now();
|
||||
|
||||
// Run the whole timeline inside the page so events interleave naturally
|
||||
await page.evaluate((events) => {
|
||||
const app = window.app;
|
||||
for (const ev of events) {
|
||||
setTimeout(() => {
|
||||
try {
|
||||
if (ev.kind === 'term') {
|
||||
app.terminal.write(ev.data);
|
||||
app.terminal.scrollToBottom();
|
||||
} else if (ev.kind === 'discover') {
|
||||
app._onSubagentDiscovered(ev.agent);
|
||||
app.openSubagentWindow(ev.agent.agentId);
|
||||
// The spawn animation (400ms) lands on the auto-grid; glide to our tile after it
|
||||
setTimeout(() => {
|
||||
const win = app.subagentWindows.get(ev.agent.agentId);
|
||||
if (win?.element) {
|
||||
win.element.style.transition = 'left 0.25s ease, top 0.25s ease';
|
||||
win.element.style.left = `${ev.x}px`;
|
||||
win.element.style.top = `${ev.y}px`;
|
||||
}
|
||||
}, 520);
|
||||
setTimeout(() => {
|
||||
const win = app.subagentWindows.get(ev.agent.agentId);
|
||||
if (win?.element) win.element.style.transition = '';
|
||||
app.updateConnectionLines();
|
||||
}, 850);
|
||||
} else if (ev.kind === 'tool') {
|
||||
app._onSubagentToolCall({
|
||||
agentId: ev.agentId,
|
||||
tool: ev.tool,
|
||||
input: ev.input,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
} else if (ev.kind === 'msg') {
|
||||
app._onSubagentMessage({
|
||||
agentId: ev.agentId,
|
||||
role: 'assistant',
|
||||
text: ev.text,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
} else if (ev.kind === 'complete') {
|
||||
app._onSubagentCompleted({ agentId: ev.agentId, timestamp: new Date().toISOString() });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('timeline event failed', ev, err);
|
||||
}
|
||||
}, ev.t);
|
||||
}
|
||||
}, timeline);
|
||||
|
||||
await sleep(totalMs + 500);
|
||||
|
||||
await page.close();
|
||||
const videoPath = await page.video().path();
|
||||
await context.close();
|
||||
|
||||
return {
|
||||
videoPath,
|
||||
ss: (sceneStart - recStart) / 1000 - 0.4,
|
||||
duration: (totalMs + 400) / 1000,
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Scene 2: zerolag typing comparison ──────────────────────────────────────
|
||||
|
||||
const ZEROLAG_VIEWPORT = { width: 1280, height: 470 };
|
||||
const TYPED_TEXT = 'echo "zero lag typing from anywhere"';
|
||||
const TYPE_INTERVAL_MS = 110;
|
||||
const REMOTE_FLUSH_MS = 350; // server-echo pane flushes queued chars in bursts
|
||||
const ZEROLAG_TAIL_HOLD = 1800;
|
||||
|
||||
const ZEROLAG_HTML = `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<link rel="stylesheet" href="http://localhost:${PORT}/vendor/xterm.css">
|
||||
<script src="http://localhost:${PORT}/vendor/xterm.min.js"></script>
|
||||
<style>
|
||||
* { margin: 0; box-sizing: border-box; }
|
||||
body {
|
||||
width: 1280px; height: 470px; background: #0a0a0c;
|
||||
display: flex; align-items: center; justify-content: center; gap: 48px;
|
||||
font-family: -apple-system, 'Segoe UI', Roboto, sans-serif;
|
||||
}
|
||||
.pane { width: 560px; }
|
||||
.card {
|
||||
background: #131316; border: 1px solid rgba(255,255,255,0.08);
|
||||
border-radius: 10px; overflow: hidden;
|
||||
box-shadow: 0 8px 32px rgba(0,0,0,0.45);
|
||||
}
|
||||
.card-head {
|
||||
display: flex; align-items: baseline; gap: 10px;
|
||||
padding: 12px 16px; border-bottom: 1px solid rgba(255,255,255,0.06);
|
||||
}
|
||||
.dot { width: 9px; height: 9px; border-radius: 50%; align-self: center; }
|
||||
.title { font-size: 15px; font-weight: 600; color: #e8e8ea; }
|
||||
.sub { font-size: 12.5px; color: #8b8b92; }
|
||||
.term { padding: 16px 8px 12px 16px; height: 165px; }
|
||||
.good .dot { background: #22c55e; box-shadow: 0 0 8px rgba(34,197,94,0.7); }
|
||||
.bad .dot { background: #ef4444; box-shadow: 0 0 8px rgba(239,68,68,0.7); }
|
||||
.tag {
|
||||
margin-top: 14px; text-align: center; font-size: 14.5px; color: #7e7e86;
|
||||
}
|
||||
.tag b { color: #22c55e; font-weight: 600; }
|
||||
.bad-tag b { color: #ef4444; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="pane">
|
||||
<div class="card good">
|
||||
<div class="card-head">
|
||||
<span class="dot"></span>
|
||||
<span class="title">With zerolag-input</span>
|
||||
<span class="sub">instant local echo</span>
|
||||
</div>
|
||||
<div class="term" id="termLeft"></div>
|
||||
</div>
|
||||
<div class="tag">keystrokes echo in <b>0 ms</b></div>
|
||||
</div>
|
||||
<div class="pane">
|
||||
<div class="card bad">
|
||||
<div class="card-head">
|
||||
<span class="dot"></span>
|
||||
<span class="title">Without</span>
|
||||
<span class="sub">server round-trip echo</span>
|
||||
</div>
|
||||
<div class="term" id="termRight"></div>
|
||||
</div>
|
||||
<div class="tag bad-tag">keystrokes echo after <b>~350 ms</b></div>
|
||||
</div>
|
||||
</body>
|
||||
</html>`;
|
||||
|
||||
async function recordZerolagScene(browser, videoDir) {
|
||||
console.log('\n2/2 Recording zerolag-demo...');
|
||||
|
||||
const context = await browser.newContext({
|
||||
viewport: ZEROLAG_VIEWPORT,
|
||||
deviceScaleFactor: 1,
|
||||
recordVideo: { dir: videoDir, size: ZEROLAG_VIEWPORT },
|
||||
});
|
||||
const recStart = Date.now();
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
|
||||
await page.setContent(ZEROLAG_HTML, { waitUntil: 'load' });
|
||||
await page.waitForFunction(() => typeof Terminal !== 'undefined');
|
||||
|
||||
await page.evaluate(() => {
|
||||
const theme = {
|
||||
background: '#131316',
|
||||
foreground: '#e8e8ea',
|
||||
cursor: '#22c55e',
|
||||
cursorAccent: '#131316',
|
||||
};
|
||||
const mk = (id) => {
|
||||
const term = new Terminal({
|
||||
cols: 44,
|
||||
rows: 5,
|
||||
fontSize: 20,
|
||||
fontFamily: "'SF Mono', 'Cascadia Code', Menlo, monospace",
|
||||
cursorBlink: true,
|
||||
cursorStyle: 'block',
|
||||
theme,
|
||||
});
|
||||
term.open(document.getElementById(id));
|
||||
term.write('\x1b[32m❯\x1b[0m ');
|
||||
return term;
|
||||
};
|
||||
window.termLeft = mk('termLeft');
|
||||
window.termRight = mk('termRight');
|
||||
});
|
||||
await sleep(600);
|
||||
|
||||
const sceneStart = Date.now();
|
||||
const typingMs = TYPED_TEXT.length * TYPE_INTERVAL_MS;
|
||||
const totalMs = typingMs + REMOTE_FLUSH_MS + ZEROLAG_TAIL_HOLD;
|
||||
|
||||
await page.evaluate(
|
||||
({ text, interval, flushEvery }) => {
|
||||
let i = 0;
|
||||
const remoteQueue = [];
|
||||
const typer = setInterval(() => {
|
||||
if (i >= text.length) { clearInterval(typer); return; }
|
||||
const ch = text[i++];
|
||||
window.termLeft.write(ch); // local echo: instant
|
||||
remoteQueue.push(ch); // server echo: waits for the round-trip
|
||||
}, interval);
|
||||
const flusher = setInterval(() => {
|
||||
if (remoteQueue.length) window.termRight.write(remoteQueue.splice(0).join(''));
|
||||
if (i >= text.length && remoteQueue.length === 0) clearInterval(flusher);
|
||||
}, flushEvery);
|
||||
},
|
||||
{ text: TYPED_TEXT, interval: TYPE_INTERVAL_MS, flushEvery: REMOTE_FLUSH_MS }
|
||||
);
|
||||
|
||||
await sleep(totalMs + 400);
|
||||
|
||||
await page.close();
|
||||
const videoPath = await page.video().path();
|
||||
await context.close();
|
||||
|
||||
return {
|
||||
videoPath,
|
||||
ss: (sceneStart - recStart) / 1000 - 0.6, // small lead-in with idle cursors
|
||||
duration: (totalMs + 600) / 1000,
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Main ────────────────────────────────────────────────────────────────────
|
||||
|
||||
async function main() {
|
||||
console.log('='.repeat(60));
|
||||
console.log('Codeman README GIF Capture');
|
||||
console.log('='.repeat(60));
|
||||
|
||||
const server = await startStaticServer();
|
||||
const videoDir = mkdtempSync(join(tmpdir(), 'codeman-gifs-'));
|
||||
let browser;
|
||||
|
||||
try {
|
||||
browser = await chromium.launch({
|
||||
headless: true,
|
||||
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],
|
||||
});
|
||||
|
||||
const sub = await recordSubagentScene(browser, videoDir);
|
||||
const subGif = outPath('images', 'subagent-demo.gif');
|
||||
webmToGif(sub.videoPath, subGif, { ss: Math.max(0, sub.ss), duration: sub.duration, width: 960, fps: 8 });
|
||||
console.log(` Saved: ${subGif}`);
|
||||
|
||||
const zl = await recordZerolagScene(browser, videoDir);
|
||||
const zlGif = outPath('images', 'zerolag-demo.gif');
|
||||
webmToGif(zl.videoPath, zlGif, { ss: Math.max(0, zl.ss), duration: zl.duration, width: 900, fps: 10 });
|
||||
console.log(` Saved: ${zlGif}`);
|
||||
|
||||
console.log('\nDone.');
|
||||
} catch (err) {
|
||||
console.error('\nFatal error:', err.message);
|
||||
console.error(err.stack);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
if (browser) await browser.close().catch(() => {});
|
||||
server.close();
|
||||
rmSync(videoDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
process.on('SIGINT', () => process.exit(1));
|
||||
|
||||
main();
|
||||
@@ -1,253 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* capture-readme-real.mjs
|
||||
*
|
||||
* Captures README desktop scenes (multi-session dashboard, monitor, subagent
|
||||
* windows) from a REAL Codeman instance — intended to run against an ISOLATED
|
||||
* dev/beta instance (CODEMAN_INSTANCE=beta on :5000) seeded from prod's settings,
|
||||
* NOT prod itself (never touch prod's live sessions).
|
||||
*
|
||||
* Reuses the high-quality capture recipe proven in capture-real-overview.mjs:
|
||||
* - DSF=2 + ?nowebgl → crisp retina at the TRUE font size (WebGL doubles
|
||||
* glyphs under DSF=2; the DOM renderer respects devicePixelRatio).
|
||||
* - per-device localStorage seeding so the capture matches a real device.
|
||||
*
|
||||
* SCENE=dashboard|monitor|subagent|all BASE=http://localhost:5000 \
|
||||
* OUT=screenshots-readme-real/desktop node scripts/capture-readme-real.mjs
|
||||
*/
|
||||
import { chromium } from 'playwright';
|
||||
import { mkdirSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
const BASE = process.env.BASE || 'http://localhost:5000';
|
||||
const OUT = process.env.OUT || 'screenshots-readme-real/desktop';
|
||||
const SKIN = process.env.SKIN || 'daylight-blue';
|
||||
const SCENE = process.env.SCENE || 'all';
|
||||
const FONT = Math.max(10, Math.min(24, Number(process.env.FONT || 13)));
|
||||
const VIEWPORT = { width: Number(process.env.VW || 1280), height: Number(process.env.VH || 720) };
|
||||
const DSF = Number(process.env.DSF || 2);
|
||||
const PLAN_USAGE = process.env.PLAN_USAGE !== '0';
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
const url = (extra = '') => {
|
||||
const sep = BASE.includes('?') ? '&' : '?';
|
||||
const params = [];
|
||||
if (DSF > 1) params.push('nowebgl'); // DOM renderer → correct font size at DSF>1
|
||||
if (extra) params.push(extra);
|
||||
return params.length ? `${BASE}${sep}${params.join('&')}` : BASE;
|
||||
};
|
||||
|
||||
async function newCtx(browser) {
|
||||
const context = await browser.newContext({
|
||||
viewport: VIEWPORT,
|
||||
deviceScaleFactor: DSF,
|
||||
ignoreHTTPSErrors: BASE.startsWith('https'),
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
await page.addInitScript(
|
||||
([skin, planUsage, font]) => {
|
||||
try {
|
||||
localStorage.setItem('codeman:skin', skin);
|
||||
localStorage.setItem('codeman-font-size', String(font));
|
||||
const blob = { skin, showFileBrowser: false, showProjectInsights: false, showTokenCount: false };
|
||||
// Don't auto-hide subagent windows that belong to a non-active tab — the
|
||||
// subagent scene re-homes agents and needs both windows visible at once.
|
||||
blob.subagentActiveTabOnly = false;
|
||||
if (planUsage) blob.showPlanUsageLimits = true;
|
||||
localStorage.setItem('codeman-app-settings', JSON.stringify(blob));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
},
|
||||
[SKIN, PLAN_USAGE, FONT]
|
||||
);
|
||||
return { context, page };
|
||||
}
|
||||
|
||||
async function bootstrap(page) {
|
||||
await page.waitForFunction(() => window.app && window.app.terminal, { timeout: 20000 });
|
||||
await sleep(1200);
|
||||
}
|
||||
|
||||
async function listSessions(page) {
|
||||
return page.evaluate(() =>
|
||||
Array.from(window.app.sessions.values()).map((s) => ({ id: s.id, name: s.name, mode: s.mode }))
|
||||
);
|
||||
}
|
||||
|
||||
async function shoot(page, name) {
|
||||
const out = join(OUT, name);
|
||||
await page.evaluate((f) => {
|
||||
try {
|
||||
if (window.app.setFontSize) window.app.setFontSize(f);
|
||||
} catch {}
|
||||
try {
|
||||
window.app.fitAddon && window.app.fitAddon.fit();
|
||||
} catch {}
|
||||
try {
|
||||
window.app.applyHeaderVisibilitySettings && window.app.applyHeaderVisibilitySettings();
|
||||
} catch {}
|
||||
}, FONT);
|
||||
await sleep(1500);
|
||||
await page.screenshot({ path: out, fullPage: false });
|
||||
console.log(' Saved: ' + out);
|
||||
}
|
||||
|
||||
async function sceneDashboard(browser) {
|
||||
console.log('Scene: dashboard');
|
||||
const { context, page } = await newCtx(browser);
|
||||
await page.goto(url(), { waitUntil: 'domcontentloaded' });
|
||||
await bootstrap(page);
|
||||
const sessions = await listSessions(page);
|
||||
// Select a claude session so the active terminal shows rich content; all tabs render.
|
||||
const target = sessions.find((s) => s.mode === 'claude') || sessions[0];
|
||||
if (target) await page.evaluate((id) => window.app.selectSession(id), target.id);
|
||||
await sleep(4000);
|
||||
await shoot(page, 'multi-session-dashboard.png');
|
||||
await context.close();
|
||||
}
|
||||
|
||||
async function sceneMonitor(browser) {
|
||||
console.log('Scene: monitor');
|
||||
const { context, page } = await newCtx(browser);
|
||||
await page.goto(url(), { waitUntil: 'domcontentloaded' });
|
||||
await bootstrap(page);
|
||||
const sessions = await listSessions(page);
|
||||
const target = sessions.find((s) => s.mode === 'claude') || sessions[0];
|
||||
if (target) await page.evaluate((id) => window.app.selectSession(id), target.id);
|
||||
await sleep(2500);
|
||||
// toggleMonitorPanel() opens the panel, clears the hidden state, loads REAL
|
||||
// mux sessions (/api/mux), starts stats, and renders the task panel.
|
||||
await page.evaluate(async () => {
|
||||
try {
|
||||
await window.app.toggleMonitorPanel();
|
||||
} catch {}
|
||||
});
|
||||
await sleep(3000);
|
||||
await shoot(page, 'multi-session-monitor.png');
|
||||
await context.close();
|
||||
}
|
||||
|
||||
async function sceneSubagent(browser) {
|
||||
console.log('Scene: subagent');
|
||||
const { context, page } = await newCtx(browser);
|
||||
await page.goto(url(), { waitUntil: 'domcontentloaded' });
|
||||
await bootstrap(page);
|
||||
// Select the session whose subagents we want (subagentActiveTabOnly means
|
||||
// app.subagents only fills for the active tab). Prefer SUBAGENT_SID env.
|
||||
const sessions = await listSessions(page);
|
||||
const targetId = process.env.SUBAGENT_SID || (sessions.find((s) => s.mode === 'claude') || sessions[0])?.id;
|
||||
if (targetId) await page.evaluate((id) => window.app.selectSession(id), targetId);
|
||||
// Wait (up to ~45s) for live subagents to arrive via SSE into app.subagents.
|
||||
let agents = [];
|
||||
for (let i = 0; i < 45; i++) {
|
||||
agents = await page.evaluate(() =>
|
||||
Array.from(window.app.subagents?.entries?.() || []).map(([id, a]) => ({ id, name: a.name ?? a.agentType ?? '' }))
|
||||
);
|
||||
if (agents.length >= 1) break;
|
||||
await sleep(1000);
|
||||
}
|
||||
console.log(' live in-browser subagents:', JSON.stringify(agents));
|
||||
if (agents.length === 0) {
|
||||
console.log(' NO live subagents — skipping (stage a longer subagent task and run this while it runs).');
|
||||
await context.close();
|
||||
return;
|
||||
}
|
||||
// The window body renders from app.subagentActivity, which fills ONLY from live
|
||||
// SSE tool-call/progress events — a fresh client never gets past activity replayed.
|
||||
// So sit connected and wait for live activity to accumulate, then open the two
|
||||
// agents that actually have content (otherwise the windows read "No activity yet").
|
||||
let active = [];
|
||||
for (let i = 0; i < 100; i++) {
|
||||
active = await page.evaluate(() =>
|
||||
Array.from(window.app.subagentActivity?.entries?.() || [])
|
||||
.filter(([, arr]) => Array.isArray(arr) && arr.length >= 1)
|
||||
.map(([id, arr]) => ({ id, n: arr.length }))
|
||||
.sort((a, b) => b.n - a.n)
|
||||
);
|
||||
if (active.length >= 2) break;
|
||||
// xhigh-effort agents churn in bursts between long thinking pauses, so be
|
||||
// patient (~150s); accept a single populated window after ~45s if that's all.
|
||||
if (i >= 30 && active.length >= 1) break;
|
||||
await sleep(1500);
|
||||
}
|
||||
console.log(' agents with live activity:', JSON.stringify(active));
|
||||
const openIds = (active.length ? active : agents).map((a) => a.id);
|
||||
// Capture-only DOM nudge: on fresh dev sessions, a tab's claudeSessionId stays the
|
||||
// Codeman id and never becomes the real Claude conversation UUID, so the window
|
||||
// open-gate (claudeSessionId === agent.sessionId) + the activeTabOnly hide rule both
|
||||
// fail. Re-home the chosen agents onto the active tab and align its claudeSessionId
|
||||
// to the agents' (shared) sessionId so the windows open AND show their live activity.
|
||||
await page.evaluate(
|
||||
(ids) => {
|
||||
const activeId = window.app.activeSessionId;
|
||||
const tab = window.app.sessions.get(activeId);
|
||||
ids.slice(0, 2).forEach((id) => {
|
||||
const a = window.app.subagents.get(id);
|
||||
if (!a) return;
|
||||
a.parentSessionId = activeId;
|
||||
if (tab && a.sessionId) tab.claudeSessionId = a.sessionId;
|
||||
});
|
||||
},
|
||||
openIds
|
||||
);
|
||||
await page.evaluate(
|
||||
(ids) => {
|
||||
ids.slice(0, 2).forEach((id) => {
|
||||
try {
|
||||
window.app.openSubagentWindow(id);
|
||||
} catch {}
|
||||
});
|
||||
},
|
||||
openIds
|
||||
);
|
||||
await sleep(2000);
|
||||
await page.evaluate(() => {
|
||||
// Viewport-relative tiling: center two subagent windows over the terminal so
|
||||
// the layout adapts to whatever VW/VH the capture uses (e.g. the HQ 1100×650
|
||||
// recipe) instead of overflowing at narrower widths.
|
||||
const wins = Array.from(window.app.subagentWindows.values());
|
||||
const W = window.innerWidth;
|
||||
const H = window.innerHeight;
|
||||
const winW = Math.min(440, Math.floor((W - 60) / 2 - 10));
|
||||
const winH = Math.min(360, Math.floor(H * 0.56));
|
||||
const top = Math.floor(H * 0.16);
|
||||
const gap = 16;
|
||||
const totalW = winW * 2 + gap;
|
||||
const startLeft = Math.max(16, Math.floor((W - totalW) / 2));
|
||||
wins.slice(0, 2).forEach((win, i) => {
|
||||
const el = win.element;
|
||||
// Force visible: a freshly opened window may be hidden by the activeTabOnly
|
||||
// rule before we override it (we also seed subagentActiveTabOnly:false).
|
||||
win.hidden = false;
|
||||
win.minimized = false;
|
||||
el.style.display = 'flex';
|
||||
el.style.left = startLeft + i * (winW + gap) + 'px';
|
||||
el.style.top = top + 'px';
|
||||
el.style.width = winW + 'px';
|
||||
el.style.height = winH + 'px';
|
||||
});
|
||||
});
|
||||
await sleep(1500);
|
||||
await shoot(page, 'subagent-spawn.png');
|
||||
await context.close();
|
||||
}
|
||||
|
||||
async function main() {
|
||||
mkdirSync(OUT, { recursive: true });
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],
|
||||
});
|
||||
console.log(`BASE=${BASE} SKIN=${SKIN} DSF=${DSF} VIEWPORT=${VIEWPORT.width}x${VIEWPORT.height} SCENE=${SCENE}`);
|
||||
if (SCENE === 'dashboard' || SCENE === 'all') await sceneDashboard(browser);
|
||||
if (SCENE === 'monitor' || SCENE === 'all') await sceneMonitor(browser);
|
||||
if (SCENE === 'subagent' || SCENE === 'all') await sceneSubagent(browser);
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error('FATAL', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,731 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* capture-video-screenshots.mjs
|
||||
*
|
||||
* Captures real Codeman UI screenshots for the Remotion demo video.
|
||||
* Uses Playwright + page.route() mock injection (same pattern as capture-readme-screenshots.mjs).
|
||||
* No real Claude CLI or server needed — all API responses are mocked.
|
||||
*
|
||||
* Usage: node scripts/capture-video-screenshots.mjs
|
||||
* Port: 3198 (static file server)
|
||||
* Output: scripts/scripts/remotion/public/ (6 PNGs)
|
||||
*/
|
||||
|
||||
import { chromium } from 'playwright';
|
||||
import { createServer } from 'http';
|
||||
import { readFileSync, existsSync } from 'fs';
|
||||
import { join, extname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = fileURLToPath(new URL('.', import.meta.url));
|
||||
const PROJECT_ROOT = join(__dirname, '..');
|
||||
const PUBLIC_DIR = join(PROJECT_ROOT, 'src', 'web', 'public');
|
||||
const OUTPUT_DIR = join(PROJECT_ROOT, 'scripts', 'remotion', 'public');
|
||||
const PORT = 3198;
|
||||
|
||||
const DESKTOP_VIEWPORT = { width: 1920, height: 1080 };
|
||||
const MOBILE_VIEWPORT = { width: 390, height: 844 };
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
// ─── MIME Types ──────────────────────────────────────────────────────────────
|
||||
|
||||
const MIME_TYPES = {
|
||||
'.html': 'text/html',
|
||||
'.js': 'text/javascript',
|
||||
'.css': 'text/css',
|
||||
'.json': 'application/json',
|
||||
'.png': 'image/png',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.ico': 'image/x-icon',
|
||||
'.woff2': 'font/woff2',
|
||||
'.woff': 'font/woff',
|
||||
'.ttf': 'font/ttf',
|
||||
};
|
||||
|
||||
// ─── Static File Server ──────────────────────────────────────────────────────
|
||||
|
||||
function startStaticServer() {
|
||||
return new Promise((resolve) => {
|
||||
const server = createServer((req, res) => {
|
||||
let urlPath = req.url.split('?')[0];
|
||||
if (urlPath === '/') urlPath = '/index.html';
|
||||
|
||||
const filePath = join(PUBLIC_DIR, urlPath);
|
||||
|
||||
if (!existsSync(filePath)) {
|
||||
res.writeHead(404);
|
||||
res.end('Not Found');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const data = readFileSync(filePath);
|
||||
const ext = extname(filePath);
|
||||
res.writeHead(200, {
|
||||
'Content-Type': MIME_TYPES[ext] || 'application/octet-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
});
|
||||
res.end(data);
|
||||
} catch {
|
||||
res.writeHead(500);
|
||||
res.end('Internal Server Error');
|
||||
}
|
||||
});
|
||||
|
||||
server.listen(PORT, () => {
|
||||
console.log(`Static server on http://localhost:${PORT}`);
|
||||
resolve(server);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Mock Data ───────────────────────────────────────────────────────────────
|
||||
|
||||
function makeSession(id, name, mode, status, extra = {}) {
|
||||
return {
|
||||
id,
|
||||
pid: status === 'idle' ? null : 12345 + Math.floor(Math.random() * 10000),
|
||||
status,
|
||||
workingDir: '/home/user/my-project',
|
||||
currentTaskId: null,
|
||||
createdAt: Date.now() - 3600000,
|
||||
lastActivityAt: Date.now() - (status === 'idle' ? 60000 : 5000),
|
||||
name,
|
||||
mode,
|
||||
autoClearEnabled: false,
|
||||
autoClearThreshold: 140000,
|
||||
autoCompactEnabled: false,
|
||||
autoCompactThreshold: 110000,
|
||||
autoCompactPrompt: '',
|
||||
imageWatcherEnabled: false,
|
||||
totalCost: mode === 'claude' ? 0.12 : 0,
|
||||
inputTokens: mode === 'claude' ? 18000 : 0,
|
||||
outputTokens: mode === 'claude' ? 11500 : 0,
|
||||
ralphEnabled: false,
|
||||
niceEnabled: false,
|
||||
niceValue: 10,
|
||||
color: 'default',
|
||||
flickerFilterEnabled: false,
|
||||
cliVersion: '2.1.61',
|
||||
cliModel: mode === 'claude' ? 'Opus 4.6' : 'GPT-4o',
|
||||
cliAccountType: mode === 'claude' ? 'Claude Max' : 'API Key',
|
||||
cliLatestVersion: '2.1.61',
|
||||
messageCount: 15,
|
||||
isWorking: status === 'busy',
|
||||
lastPromptTime: Date.now() - 30000,
|
||||
bufferStats: {
|
||||
terminalBufferSize: 4096,
|
||||
textOutputSize: 2048,
|
||||
messageCount: 15,
|
||||
maxTerminalBuffer: 2097152,
|
||||
maxTextOutput: 1048576,
|
||||
maxMessages: 1000,
|
||||
},
|
||||
taskStats: { total: 0, running: 0, completed: 0, failed: 0 },
|
||||
taskTree: [],
|
||||
tokens: {
|
||||
input: mode === 'claude' ? 18000 : 0,
|
||||
output: mode === 'claude' ? 11500 : 0,
|
||||
total: mode === 'claude' ? 29500 : 0,
|
||||
},
|
||||
autoClear: { enabled: false, threshold: 140000 },
|
||||
nice: { enabled: false, niceValue: 10 },
|
||||
ralphLoop: null,
|
||||
ralphTodos: [],
|
||||
ralphTodoStats: { total: 0, completed: 0, percentComplete: 0 },
|
||||
respawnEnabled: false,
|
||||
respawnConfig: null,
|
||||
respawn: null,
|
||||
claudeSessionId: `claude-${id}`,
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
function buildInitPayload(sessions) {
|
||||
const respawnStatus = {};
|
||||
for (const s of sessions) {
|
||||
respawnStatus[s.id] = {
|
||||
state: 'idle',
|
||||
cycleCount: 0,
|
||||
lastActivityTime: Date.now(),
|
||||
timeSinceActivity: 0,
|
||||
promptDetected: false,
|
||||
workingDetected: false,
|
||||
detection: {},
|
||||
config: null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
version: '0.1651',
|
||||
sessions,
|
||||
scheduledRuns: [],
|
||||
respawnStatus,
|
||||
globalStats: {
|
||||
totalInputTokens: 145000,
|
||||
totalOutputTokens: 87000,
|
||||
totalCost: 1.82,
|
||||
totalSessionsCreated: 12,
|
||||
firstRecordedAt: Date.now() - 86400000,
|
||||
lastUpdatedAt: Date.now(),
|
||||
},
|
||||
subagents: [],
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Terminal Content (ANSI) ─────────────────────────────────────────────────
|
||||
|
||||
const RST = '\x1b[0m';
|
||||
const RED = '\x1b[31m';
|
||||
const GRN = '\x1b[32m';
|
||||
const YEL = '\x1b[33m';
|
||||
const MAG = '\x1b[35m';
|
||||
const GRY = '\x1b[90m';
|
||||
const BOLD = '\x1b[1m';
|
||||
const DIM = '\x1b[2m';
|
||||
|
||||
// Claude Code init banner
|
||||
const TERMINAL_CLAUDE = [
|
||||
'',
|
||||
` ${RED}████${RST} ${BOLD}Claude Code${RST} v2.1.61`,
|
||||
` ${RED}████${RST} ${GRY}Opus 4.6${RST} ${DIM}·${RST} ${GRY}Claude Max${RST}`,
|
||||
` ${RED}██${RST} ${RED}██${RST} ${GRY}~/my-project${RST}`,
|
||||
'',
|
||||
'',
|
||||
`${GRY}❯ Try "how do I log an error?"${RST}`,
|
||||
'',
|
||||
'',
|
||||
`${YEL}»»${RST} ${BOLD}bypass permissions on${RST} ${GRY}(shift+tab to cycle)${RST}`,
|
||||
` ${BOLD}0 tokens${RST}`,
|
||||
` ${GRY}current: 2.1.61${RST} ${DIM}·${RST} ${GRY}latest: 2.1.61${RST}`,
|
||||
].join('\r\n');
|
||||
|
||||
// OpenCode init banner
|
||||
const TERMINAL_OPENCODE = [
|
||||
'',
|
||||
` ${GRN}████${RST} ${BOLD}OpenCode${RST} v0.3.12`,
|
||||
` ${GRN}████${RST} ${GRY}GPT-4o${RST} ${DIM}·${RST} ${GRY}API Key${RST}`,
|
||||
` ${GRN}██${RST} ${GRN}██${RST} ${GRY}~/my-project${RST}`,
|
||||
'',
|
||||
'',
|
||||
`${GRY}❯ Try "explain this codebase"${RST}`,
|
||||
'',
|
||||
'',
|
||||
`${YEL}»»${RST} ${BOLD}bypass permissions on${RST}`,
|
||||
` ${BOLD}0 tokens${RST}`,
|
||||
].join('\r\n');
|
||||
|
||||
// ─── Route Interceptors ──────────────────────────────────────────────────────
|
||||
|
||||
async function setupRoutes(page, initPayload, terminalContent) {
|
||||
// Block SSE to prevent reconnection loops
|
||||
await page.route('**/api/events', async (route) => {
|
||||
await route.abort();
|
||||
});
|
||||
|
||||
// Terminal buffer endpoint
|
||||
await page.route('**/api/sessions/*/terminal**', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
terminalBuffer: terminalContent,
|
||||
status: 'busy',
|
||||
fullSize: terminalContent.length,
|
||||
truncated: false,
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
// Mux sessions
|
||||
await page.route('**/api/mux-sessions/**', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ success: true }),
|
||||
});
|
||||
});
|
||||
|
||||
await page.route('**/api/mux-sessions', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ sessions: [], muxAvailable: true }),
|
||||
});
|
||||
});
|
||||
|
||||
// Settings
|
||||
await page.route('**/api/settings', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
showSubagents: false,
|
||||
subagentTrackingEnabled: false,
|
||||
subagentActiveTabOnly: false,
|
||||
showMonitor: false,
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
// Subagent window states
|
||||
await page.route('**/api/subagent-window-states', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
});
|
||||
|
||||
// Subagent parents
|
||||
await page.route('**/api/subagent-parents', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
});
|
||||
|
||||
// Session-specific subagents
|
||||
await page.route('**/api/sessions/*/subagents', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ success: true, data: [] }),
|
||||
});
|
||||
});
|
||||
|
||||
// Interactive attach
|
||||
await page.route('**/api/sessions/*/interactive', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ success: true }),
|
||||
});
|
||||
});
|
||||
|
||||
// Resize
|
||||
await page.route('**/api/sessions/*/resize', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ success: true }),
|
||||
});
|
||||
});
|
||||
|
||||
// Catch-all API
|
||||
await page.route('**/api/**', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ success: true }),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Inject mock state and render the app.
|
||||
*/
|
||||
async function injectState(page, initPayload, terminalContent, activeSessionId) {
|
||||
await page.waitForFunction(() => window.app && window.app.terminal, { timeout: 15000 });
|
||||
await sleep(2000);
|
||||
|
||||
// Cancel SSE fallback timer and inject state
|
||||
await page.evaluate((payload) => {
|
||||
const app = window.app;
|
||||
if (app._initFallbackTimer) {
|
||||
clearTimeout(app._initFallbackTimer);
|
||||
app._initFallbackTimer = null;
|
||||
}
|
||||
app.handleInit(payload);
|
||||
}, initPayload);
|
||||
|
||||
await sleep(3000);
|
||||
|
||||
// Select the target session
|
||||
if (activeSessionId) {
|
||||
await page.evaluate((sid) => {
|
||||
window.app.activeSessionId = null;
|
||||
window.app.selectSession(sid);
|
||||
}, activeSessionId);
|
||||
await sleep(4000);
|
||||
}
|
||||
|
||||
// Write terminal content directly as backup
|
||||
if (terminalContent && activeSessionId) {
|
||||
await page.evaluate((content) => {
|
||||
const app = window.app;
|
||||
if (app.terminal) {
|
||||
const buf = app.terminal.buffer?.active;
|
||||
const hasContent = buf && buf.length > 2 && buf.getLine(1)?.translateToString().trim();
|
||||
if (!hasContent) {
|
||||
app.terminal.clear();
|
||||
app.terminal.reset();
|
||||
app.terminal.write(content);
|
||||
app.terminal.scrollToBottom();
|
||||
}
|
||||
}
|
||||
}, terminalContent);
|
||||
await sleep(3000);
|
||||
}
|
||||
|
||||
// Clean up UI artifacts
|
||||
await page.evaluate(() => {
|
||||
const app = window.app;
|
||||
if (app) {
|
||||
if (app.sseReconnectTimeout) clearTimeout(app.sseReconnectTimeout);
|
||||
if (app.eventSource) { app.eventSource.close(); app.eventSource = null; }
|
||||
app._connectionStatus = 'connected';
|
||||
app._updateConnectionIndicator = () => {};
|
||||
app.connectSSE = () => {};
|
||||
app.setConnectionStatus = () => {};
|
||||
}
|
||||
|
||||
// Remove connection indicator
|
||||
const indicator = document.getElementById('connectionIndicator');
|
||||
if (indicator) indicator.remove();
|
||||
|
||||
// Hide respawn banner
|
||||
const respawnBanner = document.getElementById('respawnBanner');
|
||||
if (respawnBanner) respawnBanner.style.display = 'none';
|
||||
|
||||
// Mock CPU/MEM stats
|
||||
const statsEl = document.getElementById('headerSystemStats');
|
||||
if (statsEl) {
|
||||
statsEl.innerHTML = `
|
||||
<span class="stat-label">CPU</span>
|
||||
<div class="stat-bar"><div class="stat-bar-fill cpu-bar" style="width: 18%"></div></div>
|
||||
<span class="stat-value">18%</span>
|
||||
<span class="stat-label">MEM</span>
|
||||
<div class="stat-bar"><div class="stat-bar-fill mem-bar" style="width: 42%"></div></div>
|
||||
<span class="stat-value">13.7G</span>
|
||||
`;
|
||||
}
|
||||
|
||||
// Hide subagents panel entirely
|
||||
const subagentsPanel = document.getElementById('subagentsPanel');
|
||||
if (subagentsPanel) subagentsPanel.style.display = 'none';
|
||||
|
||||
// Close and hide monitor panel
|
||||
const monitorPanel = document.getElementById('monitorPanel');
|
||||
if (monitorPanel) {
|
||||
monitorPanel.classList.remove('open');
|
||||
monitorPanel.style.display = 'none';
|
||||
}
|
||||
|
||||
// Hide monitor toggle button in toolbar
|
||||
const monitorBtn = document.getElementById('monitorToggle');
|
||||
if (monitorBtn) monitorBtn.style.display = 'none';
|
||||
|
||||
// Update token display
|
||||
if (app && app.activeSessionId) {
|
||||
const session = app.sessions.get(app.activeSessionId);
|
||||
if (session) {
|
||||
const tokens = (session.tokens?.total || 0);
|
||||
const tokenEl = document.getElementById('headerTokens');
|
||||
if (tokenEl) {
|
||||
const formatted = tokens >= 1000 ? `${(tokens / 1000).toFixed(1)}k` : String(tokens);
|
||||
tokenEl.innerHTML = `<span class="token-icon">⊙</span> <span class="token-count">${formatted} tokens</span>`;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Final settle — let xterm.js WebGL renderer, fonts, and layout fully stabilize
|
||||
await sleep(4000);
|
||||
}
|
||||
|
||||
// ─── Screenshot Scenarios ────────────────────────────────────────────────────
|
||||
|
||||
// 1. Desktop welcome — no sessions, welcome overlay visible
|
||||
async function captureDesktopWelcome(browser) {
|
||||
console.log('\n1/6 Capturing desktop-welcome.png...');
|
||||
|
||||
const context = await browser.newContext({
|
||||
viewport: DESKTOP_VIEWPORT,
|
||||
deviceScaleFactor: 1,
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
|
||||
try {
|
||||
const initPayload = buildInitPayload([]);
|
||||
await setupRoutes(page, initPayload, '');
|
||||
|
||||
await page.goto(`http://localhost:${PORT}`, { waitUntil: 'domcontentloaded' });
|
||||
await page.waitForFunction(() => window.app && window.app.terminal, { timeout: 15000 });
|
||||
await sleep(2000);
|
||||
|
||||
// Inject empty state — welcome overlay should show automatically
|
||||
await page.evaluate((payload) => {
|
||||
const app = window.app;
|
||||
if (app._initFallbackTimer) {
|
||||
clearTimeout(app._initFallbackTimer);
|
||||
app._initFallbackTimer = null;
|
||||
}
|
||||
app.handleInit(payload);
|
||||
}, initPayload);
|
||||
await sleep(3000);
|
||||
|
||||
// Clean up UI
|
||||
await page.evaluate(() => {
|
||||
const app = window.app;
|
||||
if (app) {
|
||||
if (app.sseReconnectTimeout) clearTimeout(app.sseReconnectTimeout);
|
||||
if (app.eventSource) { app.eventSource.close(); app.eventSource = null; }
|
||||
app._connectionStatus = 'connected';
|
||||
app._updateConnectionIndicator = () => {};
|
||||
app.connectSSE = () => {};
|
||||
app.setConnectionStatus = () => {};
|
||||
}
|
||||
const indicator = document.getElementById('connectionIndicator');
|
||||
if (indicator) indicator.remove();
|
||||
const respawnBanner = document.getElementById('respawnBanner');
|
||||
if (respawnBanner) respawnBanner.style.display = 'none';
|
||||
|
||||
// Mock stats
|
||||
const statsEl = document.getElementById('headerSystemStats');
|
||||
if (statsEl) {
|
||||
statsEl.innerHTML = `
|
||||
<span class="stat-label">CPU</span>
|
||||
<div class="stat-bar"><div class="stat-bar-fill cpu-bar" style="width: 18%"></div></div>
|
||||
<span class="stat-value">18%</span>
|
||||
<span class="stat-label">MEM</span>
|
||||
<div class="stat-bar"><div class="stat-bar-fill mem-bar" style="width: 42%"></div></div>
|
||||
<span class="stat-value">13.7G</span>
|
||||
`;
|
||||
}
|
||||
|
||||
// Hide monitor and subagent panels
|
||||
const subagentsPanel = document.getElementById('subagentsPanel');
|
||||
if (subagentsPanel) subagentsPanel.style.display = 'none';
|
||||
const monitorPanel = document.getElementById('monitorPanel');
|
||||
if (monitorPanel) {
|
||||
monitorPanel.classList.remove('open');
|
||||
monitorPanel.style.display = 'none';
|
||||
}
|
||||
const monitorBtn = document.getElementById('monitorToggle');
|
||||
if (monitorBtn) monitorBtn.style.display = 'none';
|
||||
});
|
||||
await sleep(3000);
|
||||
|
||||
await page.screenshot({
|
||||
path: join(OUTPUT_DIR, 'desktop-welcome.png'),
|
||||
fullPage: false,
|
||||
});
|
||||
console.log(' Saved: scripts/remotion/public/desktop-welcome.png');
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Desktop with single Claude tab active
|
||||
async function captureDesktopClaude(browser) {
|
||||
console.log('\n2/6 Capturing desktop-claude.png...');
|
||||
|
||||
const claudeSession = makeSession('sess-claude-1', 'w1-my-project', 'claude', 'busy');
|
||||
const initPayload = buildInitPayload([claudeSession]);
|
||||
|
||||
const context = await browser.newContext({
|
||||
viewport: DESKTOP_VIEWPORT,
|
||||
deviceScaleFactor: 1,
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
|
||||
try {
|
||||
await setupRoutes(page, initPayload, TERMINAL_CLAUDE);
|
||||
await page.goto(`http://localhost:${PORT}`, { waitUntil: 'domcontentloaded' });
|
||||
await injectState(page, initPayload, TERMINAL_CLAUDE, 'sess-claude-1');
|
||||
|
||||
await page.screenshot({
|
||||
path: join(OUTPUT_DIR, 'desktop-claude.png'),
|
||||
fullPage: false,
|
||||
});
|
||||
console.log(' Saved: scripts/remotion/public/desktop-claude.png');
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Desktop with 2 tabs (Claude + OpenCode), Claude active
|
||||
async function captureDesktopBothClaude(browser) {
|
||||
console.log('\n3/6 Capturing desktop-both-claude.png...');
|
||||
|
||||
const claudeSession = makeSession('sess-claude-2', 'w1-my-project', 'claude', 'busy');
|
||||
const opencodeSession = makeSession('sess-opencode-2', 'w2-my-project', 'opencode', 'busy');
|
||||
const initPayload = buildInitPayload([claudeSession, opencodeSession]);
|
||||
|
||||
const context = await browser.newContext({
|
||||
viewport: DESKTOP_VIEWPORT,
|
||||
deviceScaleFactor: 1,
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
|
||||
try {
|
||||
await setupRoutes(page, initPayload, TERMINAL_CLAUDE);
|
||||
await page.goto(`http://localhost:${PORT}`, { waitUntil: 'domcontentloaded' });
|
||||
await injectState(page, initPayload, TERMINAL_CLAUDE, 'sess-claude-2');
|
||||
|
||||
await page.screenshot({
|
||||
path: join(OUTPUT_DIR, 'desktop-both-claude.png'),
|
||||
fullPage: false,
|
||||
});
|
||||
console.log(' Saved: scripts/remotion/public/desktop-both-claude.png');
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Desktop with 2 tabs (Claude + OpenCode), OpenCode active
|
||||
async function captureDesktopBothOpencode(browser) {
|
||||
console.log('\n4/6 Capturing desktop-both-opencode.png...');
|
||||
|
||||
const claudeSession = makeSession('sess-claude-3', 'w1-my-project', 'claude', 'busy');
|
||||
const opencodeSession = makeSession('sess-opencode-3', 'w2-my-project', 'opencode', 'busy');
|
||||
const initPayload = buildInitPayload([claudeSession, opencodeSession]);
|
||||
|
||||
const context = await browser.newContext({
|
||||
viewport: DESKTOP_VIEWPORT,
|
||||
deviceScaleFactor: 1,
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
|
||||
try {
|
||||
await setupRoutes(page, initPayload, TERMINAL_OPENCODE);
|
||||
await page.goto(`http://localhost:${PORT}`, { waitUntil: 'domcontentloaded' });
|
||||
await injectState(page, initPayload, TERMINAL_OPENCODE, 'sess-opencode-3');
|
||||
|
||||
await page.screenshot({
|
||||
path: join(OUTPUT_DIR, 'desktop-both-opencode.png'),
|
||||
fullPage: false,
|
||||
});
|
||||
console.log(' Saved: scripts/remotion/public/desktop-both-opencode.png');
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Mobile with Claude tab
|
||||
async function captureMobileClaude(browser) {
|
||||
console.log('\n5/6 Capturing mobile-claude.png...');
|
||||
|
||||
const claudeSession = makeSession('sess-claude-m1', 'w1-my-project', 'claude', 'busy');
|
||||
const initPayload = buildInitPayload([claudeSession]);
|
||||
|
||||
const context = await browser.newContext({
|
||||
viewport: MOBILE_VIEWPORT,
|
||||
deviceScaleFactor: 2,
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
|
||||
try {
|
||||
await setupRoutes(page, initPayload, TERMINAL_CLAUDE);
|
||||
await page.goto(`http://localhost:${PORT}`, { waitUntil: 'domcontentloaded' });
|
||||
await injectState(page, initPayload, TERMINAL_CLAUDE, 'sess-claude-m1');
|
||||
|
||||
await page.screenshot({
|
||||
path: join(OUTPUT_DIR, 'mobile-claude.png'),
|
||||
fullPage: false,
|
||||
});
|
||||
console.log(' Saved: scripts/remotion/public/mobile-claude.png');
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Mobile with OpenCode tab
|
||||
async function captureMobileOpencode(browser) {
|
||||
console.log('\n6/6 Capturing mobile-opencode.png...');
|
||||
|
||||
const opencodeSession = makeSession('sess-opencode-m1', 'w1-my-project', 'opencode', 'busy');
|
||||
const initPayload = buildInitPayload([opencodeSession]);
|
||||
|
||||
const context = await browser.newContext({
|
||||
viewport: MOBILE_VIEWPORT,
|
||||
deviceScaleFactor: 2,
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
|
||||
try {
|
||||
await setupRoutes(page, initPayload, TERMINAL_OPENCODE);
|
||||
await page.goto(`http://localhost:${PORT}`, { waitUntil: 'domcontentloaded' });
|
||||
await injectState(page, initPayload, TERMINAL_OPENCODE, 'sess-opencode-m1');
|
||||
|
||||
await page.screenshot({
|
||||
path: join(OUTPUT_DIR, 'mobile-opencode.png'),
|
||||
fullPage: false,
|
||||
});
|
||||
console.log(' Saved: scripts/remotion/public/mobile-opencode.png');
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Main ────────────────────────────────────────────────────────────────────
|
||||
|
||||
async function main() {
|
||||
console.log('='.repeat(60));
|
||||
console.log('Codeman Video Screenshot Capture');
|
||||
console.log('='.repeat(60));
|
||||
console.log(`Port: ${PORT}`);
|
||||
console.log(`Desktop: ${DESKTOP_VIEWPORT.width}x${DESKTOP_VIEWPORT.height}`);
|
||||
console.log(`Mobile: ${MOBILE_VIEWPORT.width}x${MOBILE_VIEWPORT.height} @2x`);
|
||||
console.log(`Output: ${OUTPUT_DIR}`);
|
||||
console.log('');
|
||||
|
||||
const server = await startStaticServer();
|
||||
let browser;
|
||||
|
||||
try {
|
||||
browser = await chromium.launch({
|
||||
headless: true,
|
||||
args: [
|
||||
'--no-sandbox',
|
||||
'--disable-setuid-sandbox',
|
||||
'--disable-dev-shm-usage',
|
||||
'--disable-gpu',
|
||||
],
|
||||
});
|
||||
|
||||
await captureDesktopWelcome(browser);
|
||||
await captureDesktopClaude(browser);
|
||||
await captureDesktopBothClaude(browser);
|
||||
await captureDesktopBothOpencode(browser);
|
||||
await captureMobileClaude(browser);
|
||||
await captureMobileOpencode(browser);
|
||||
|
||||
console.log('\n' + '='.repeat(60));
|
||||
console.log('All 6 screenshots captured!');
|
||||
console.log('='.repeat(60));
|
||||
console.log('\nOutput files:');
|
||||
console.log(' scripts/remotion/public/desktop-welcome.png');
|
||||
console.log(' scripts/remotion/public/desktop-claude.png');
|
||||
console.log(' scripts/remotion/public/desktop-both-claude.png');
|
||||
console.log(' scripts/remotion/public/desktop-both-opencode.png');
|
||||
console.log(' scripts/remotion/public/mobile-claude.png');
|
||||
console.log(' scripts/remotion/public/mobile-opencode.png');
|
||||
} catch (err) {
|
||||
console.error('\nFatal error:', err.message);
|
||||
console.error(err.stack);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
if (browser) await browser.close().catch(() => {});
|
||||
server.close();
|
||||
console.log('\nDone.');
|
||||
}
|
||||
}
|
||||
|
||||
process.on('SIGINT', () => {
|
||||
console.log('\nInterrupted.');
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,270 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Frontend dead-code check.
|
||||
*
|
||||
* `src/web/public/*.js` is loaded as plain <script> files: no imports, so knip cannot
|
||||
* follow it, and it is outside ESLint. A method that lost its last caller therefore
|
||||
* stays in the tree unnoticed (the November 2026 cleanup removed about 2,000 such
|
||||
* lines of JS and 1,500 lines of CSS). This script finds them.
|
||||
*
|
||||
* JavaScript: every function, method and top-level binding the frontend files
|
||||
* define, checked against every identifier and every string or template literal in
|
||||
* those files, `index.html` (inline handlers), the gesture overlay's source and the
|
||||
* tests. A name that appears nowhere but at its own definition is reported.
|
||||
*
|
||||
* CSS: every class and id selector in `styles.css` and `mobile.css`, checked against
|
||||
* the same text. A class built at runtime (`tab-state-${state}`) is recognised by its
|
||||
* prefix and skipped, so the report holds only names no code can produce.
|
||||
*
|
||||
* Text matching is deliberately conservative: a mention in a comment does not count,
|
||||
* a mention in any string does. So a clean run does not prove everything is used,
|
||||
* but a reported name really has no reference. To keep one on purpose, add it to
|
||||
* ALLOW below with the reason.
|
||||
*
|
||||
* Usage: node scripts/check-frontend-dead-code.mjs [--production]
|
||||
* --production also report what only tests reference (informational, exit 0)
|
||||
*
|
||||
* Parsed with the TypeScript compiler (already a dev dependency), so this needs no
|
||||
* package of its own.
|
||||
*/
|
||||
import { readFileSync, readdirSync, statSync, existsSync } from 'node:fs';
|
||||
import { join, dirname, relative } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { createRequire } from 'node:module';
|
||||
|
||||
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const PUBLIC_DIR = join(ROOT, 'src', 'web', 'public');
|
||||
const require = createRequire(join(ROOT, 'package.json'));
|
||||
const ts = require('typescript');
|
||||
const postcss = require('postcss');
|
||||
|
||||
/**
|
||||
* Names kept on purpose although nothing references them. Key: the name as reported
|
||||
* (a JS name, or a selector with its `.` or `#`). Value: why it stays.
|
||||
*/
|
||||
const ALLOW = new Map([
|
||||
// ['exampleMethod', 'called from the browser console when debugging X'],
|
||||
]);
|
||||
|
||||
/** Class prefixes that belong to vendored code, which the scan does not read. */
|
||||
const EXTERNAL_CLASS_PREFIXES = ['xterm'];
|
||||
|
||||
const productionMode = process.argv.includes('--production');
|
||||
|
||||
function walk(dir, filter, skipDirs = []) {
|
||||
const out = [];
|
||||
if (!existsSync(dir)) return out;
|
||||
for (const entry of readdirSync(dir)) {
|
||||
if (entry === 'node_modules' || skipDirs.includes(entry)) continue;
|
||||
const path = join(dir, entry);
|
||||
if (statSync(path).isDirectory()) out.push(...walk(path, filter, skipDirs));
|
||||
else if (filter.test(entry)) out.push(path);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const rel = (path) => relative(ROOT, path);
|
||||
const read = (path) => readFileSync(path, 'utf8');
|
||||
|
||||
// ── What counts as a reference ────────────────────────────────────────────────
|
||||
|
||||
// Shipped scripts. The vendored bundles and the generated gesture bundle are not ours
|
||||
// to judge; the gesture overlay is read from its source instead.
|
||||
const frontendFiles = walk(PUBLIC_DIR, /\.js$/, ['vendor', 'gesture', 'fonts']);
|
||||
const htmlText = walk(PUBLIC_DIR, /\.html$/, ['vendor', 'gesture']).map(read).join('\n');
|
||||
const gestureText = walk(join(ROOT, 'packages', 'gesture-control', 'src'), /\.(ts|js)$/)
|
||||
.map(read)
|
||||
.join('\n');
|
||||
const serverText = walk(join(ROOT, 'src'), /\.ts$/, ['public']).map(read).join('\n');
|
||||
const overlayText = walk(join(ROOT, 'packages', 'xterm-zerolag-input', 'src'), /\.(ts|js)$/)
|
||||
.map(read)
|
||||
.join('\n');
|
||||
const testText = walk(join(ROOT, 'test'), /\.(ts|mjs|js)$/).map(read).join('\n');
|
||||
|
||||
const identifierCount = new Map();
|
||||
const literalParts = [];
|
||||
const definitions = [];
|
||||
|
||||
function bump(name) {
|
||||
identifierCount.set(name, (identifierCount.get(name) ?? 0) + 1);
|
||||
}
|
||||
|
||||
function isFunctionLike(node) {
|
||||
return !!node && (ts.isFunctionExpression(node) || ts.isArrowFunction(node));
|
||||
}
|
||||
|
||||
function propertyName(name) {
|
||||
if (!name) return null;
|
||||
if (ts.isIdentifier(name) || ts.isStringLiteral(name)) return name.text;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Top-level statements, looking one level into an IIFE wrapper. */
|
||||
function topLevelStatements(sourceFile) {
|
||||
const out = [...sourceFile.statements];
|
||||
for (const statement of sourceFile.statements) {
|
||||
if (!ts.isExpressionStatement(statement)) continue;
|
||||
let expr = statement.expression;
|
||||
while (ts.isParenthesizedExpression(expr) || ts.isPrefixUnaryExpression(expr)) {
|
||||
expr = ts.isParenthesizedExpression(expr) ? expr.expression : expr.operand;
|
||||
}
|
||||
if (!ts.isCallExpression(expr)) continue;
|
||||
let callee = expr.expression;
|
||||
while (ts.isParenthesizedExpression(callee)) callee = callee.expression;
|
||||
if (ts.isPropertyAccessExpression(callee)) callee = callee.expression;
|
||||
while (ts.isParenthesizedExpression(callee)) callee = callee.expression;
|
||||
if ((ts.isFunctionExpression(callee) || ts.isArrowFunction(callee)) && ts.isBlock(callee.body)) {
|
||||
out.push(...callee.body.statements);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
for (const file of frontendFiles) {
|
||||
const text = read(file);
|
||||
const sourceFile = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
|
||||
const lineOf = (node) => sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
|
||||
const define = (name, node, kind) => {
|
||||
if (name) definitions.push({ name, file: rel(file), line: lineOf(node), kind });
|
||||
};
|
||||
|
||||
for (const statement of topLevelStatements(sourceFile)) {
|
||||
if (ts.isVariableStatement(statement)) {
|
||||
for (const decl of statement.declarationList.declarations) {
|
||||
if (ts.isIdentifier(decl.name)) define(decl.name.text, decl, 'binding');
|
||||
}
|
||||
} else if (ts.isClassDeclaration(statement) && statement.name) {
|
||||
define(statement.name.text, statement, 'binding');
|
||||
}
|
||||
}
|
||||
|
||||
const visit = (node) => {
|
||||
if (ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) bump(node.text);
|
||||
else if (
|
||||
ts.isStringLiteral(node) ||
|
||||
ts.isNoSubstitutionTemplateLiteral(node) ||
|
||||
node.kind === ts.SyntaxKind.TemplateHead ||
|
||||
node.kind === ts.SyntaxKind.TemplateMiddle ||
|
||||
node.kind === ts.SyntaxKind.TemplateTail
|
||||
) {
|
||||
literalParts.push(node.text);
|
||||
}
|
||||
|
||||
if (ts.isFunctionDeclaration(node) && node.name) define(node.name.text, node, 'function');
|
||||
else if (ts.isMethodDeclaration(node) || ts.isGetAccessor(node) || ts.isSetAccessor(node)) {
|
||||
define(propertyName(node.name), node, 'method');
|
||||
} else if (ts.isPropertyAssignment(node) && isFunctionLike(node.initializer)) {
|
||||
define(propertyName(node.name), node, 'method');
|
||||
} else if (ts.isPropertyDeclaration(node) && isFunctionLike(node.initializer)) {
|
||||
define(propertyName(node.name), node, 'method');
|
||||
} else if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && isFunctionLike(node.initializer)) {
|
||||
define(node.name.text, node, 'function');
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
};
|
||||
visit(sourceFile);
|
||||
}
|
||||
|
||||
const literalText = literalParts.join('\n');
|
||||
const wordPattern = (name) => new RegExp(`(?<![\\w$])${name.replace(/[$]/g, '\\$&')}(?![\\w$])`, 'g');
|
||||
const count = (text, pattern) => (text.match(pattern) ?? []).length;
|
||||
|
||||
// ── JavaScript ────────────────────────────────────────────────────────────────
|
||||
|
||||
const byName = new Map();
|
||||
for (const def of definitions) {
|
||||
// A binding and a function for the same declaration are one definition.
|
||||
const list = byName.get(def.name) ?? [];
|
||||
if (!list.some((d) => d.file === def.file && d.line === def.line)) list.push(def);
|
||||
byName.set(def.name, list);
|
||||
}
|
||||
|
||||
const deadJs = [];
|
||||
const testOnlyJs = [];
|
||||
for (const [name, defs] of byName) {
|
||||
if (name.length < 3 || name === 'constructor' || ALLOW.has(name)) continue;
|
||||
const pattern = wordPattern(name);
|
||||
const shipped =
|
||||
(identifierCount.get(name) ?? 0) -
|
||||
defs.length +
|
||||
count(literalText, pattern) +
|
||||
count(htmlText, pattern) +
|
||||
count(gestureText, pattern);
|
||||
if (shipped > 0) continue;
|
||||
const inTests = count(testText, pattern);
|
||||
(inTests > 0 ? testOnlyJs : deadJs).push({ name, defs, inTests });
|
||||
}
|
||||
|
||||
// ── CSS ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
const cssCorpus = [
|
||||
...frontendFiles.map(read),
|
||||
htmlText,
|
||||
gestureText,
|
||||
overlayText,
|
||||
serverText,
|
||||
...walk(PUBLIC_DIR, /\.json$/, ['vendor', 'gesture']).map(read),
|
||||
].join('\n');
|
||||
const corpusWords = new Set(cssCorpus.match(/[A-Za-z_][\w-]*/g) ?? []);
|
||||
// `foo-${x}` and 'foo-' + x build a class at runtime: everything with that prefix may exist.
|
||||
const dynamicPrefixes = new Set();
|
||||
for (const m of cssCorpus.matchAll(/([A-Za-z_][\w-]*-)(?:\$\{|['"`]\s*\+)/g)) dynamicPrefixes.add(m[1]);
|
||||
// `${x}-suffix` and x + '-suffix' likewise, when the stem itself is a known word.
|
||||
const dynamicSuffixes = new Set();
|
||||
for (const m of cssCorpus.matchAll(/(?:\}|\+\s*['"`])(-[\w-]+)/g)) dynamicSuffixes.add(m[1]);
|
||||
|
||||
const deadCss = [];
|
||||
for (const cssFile of [join(PUBLIC_DIR, 'styles.css'), join(PUBLIC_DIR, 'mobile.css')]) {
|
||||
const seen = new Map();
|
||||
postcss.parse(read(cssFile), { from: cssFile }).walkRules((rule) => {
|
||||
const selector = rule.selector.replace(/\[[^\]]*\]/g, ' ').replace(/"[^"]*"|'[^']*'/g, ' ');
|
||||
for (const m of selector.matchAll(/([.#])(-?[A-Za-z_][\w-]*)/g)) {
|
||||
const key = m[1] + m[2];
|
||||
if (!seen.has(key)) seen.set(key, rule.source.start.line);
|
||||
}
|
||||
});
|
||||
for (const [key, line] of seen) {
|
||||
const name = key.slice(1);
|
||||
if (ALLOW.has(key) || corpusWords.has(name)) continue;
|
||||
if (EXTERNAL_CLASS_PREFIXES.some((prefix) => name === prefix || name.startsWith(prefix + '-'))) continue;
|
||||
if ([...dynamicPrefixes].some((prefix) => name.startsWith(prefix))) continue;
|
||||
if ([...dynamicSuffixes].some((suffix) => name.endsWith(suffix) && corpusWords.has(name.slice(0, -suffix.length)))) {
|
||||
continue;
|
||||
}
|
||||
if (deadCss.some((d) => d.key === key)) continue;
|
||||
deadCss.push({ key, file: rel(cssFile), line });
|
||||
}
|
||||
}
|
||||
|
||||
// ── Report ────────────────────────────────────────────────────────────────────
|
||||
|
||||
const where = (defs) => defs.map((d) => `${d.file}:${d.line}`).join(', ');
|
||||
const sortByPlace = (a, b) => where(a.defs).localeCompare(where(b.defs), undefined, { numeric: true });
|
||||
|
||||
if (productionMode && testOnlyJs.length > 0) {
|
||||
console.log(`Referenced by tests only (${testOnlyJs.length}):`);
|
||||
for (const item of testOnlyJs.sort(sortByPlace)) {
|
||||
console.log(` ${item.name} ${where(item.defs)} (${item.inTests} mention${item.inTests === 1 ? '' : 's'} in test/)`);
|
||||
}
|
||||
console.log('');
|
||||
}
|
||||
|
||||
if (deadJs.length === 0 && deadCss.length === 0) {
|
||||
console.log(
|
||||
`✓ no unreferenced frontend code: ${byName.size} names in ${frontendFiles.length} scripts and the selectors of 2 stylesheets checked`
|
||||
);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (deadJs.length > 0) {
|
||||
console.error(`Unreferenced frontend functions and bindings (${deadJs.length}):`);
|
||||
for (const item of deadJs.sort(sortByPlace)) console.error(` ${item.name} ${where(item.defs)}`);
|
||||
}
|
||||
if (deadCss.length > 0) {
|
||||
console.error(`${deadJs.length > 0 ? '\n' : ''}CSS selectors nothing can produce (${deadCss.length}):`);
|
||||
for (const item of deadCss) console.error(` ${item.key} ${item.file}:${item.line}`);
|
||||
}
|
||||
console.error(
|
||||
'\nRemove each one, or add it to ALLOW in scripts/check-frontend-dead-code.mjs with the reason it stays.'
|
||||
);
|
||||
process.exit(1);
|
||||
@@ -1,17 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Generates timestamped data to a file for testing
|
||||
# Usage: ./scripts/data-generator.sh [output_file] [interval_seconds]
|
||||
# Then: tail -f /tmp/test-data.log
|
||||
|
||||
OUTPUT="${1:-/tmp/test-data.log}"
|
||||
INTERVAL="${2:-1}"
|
||||
|
||||
echo "Writing to $OUTPUT every ${INTERVAL}s (Ctrl+C to stop)"
|
||||
echo "Run: tail -f $OUTPUT"
|
||||
|
||||
i=0
|
||||
while true; do
|
||||
((i++))
|
||||
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Line $i - Random: $RANDOM" >> "$OUTPUT"
|
||||
sleep "$INTERVAL"
|
||||
done
|
||||
@@ -1,187 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Take mobile screenshots of Codeman using Playwright
|
||||
* Emulates iPhone 15 Pro (closest to iPhone 17 Pro)
|
||||
* Includes keyboard simulation
|
||||
*/
|
||||
|
||||
import { chromium, devices } from 'playwright';
|
||||
import { join, dirname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { mkdirSync } from 'fs';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const BASE_URL = 'http://localhost:3000';
|
||||
const OUTPUT_DIR = join(__dirname, '..', 'docs', 'screenshots');
|
||||
|
||||
// Ensure output directory exists
|
||||
try { mkdirSync(OUTPUT_DIR, { recursive: true }); } catch {}
|
||||
|
||||
// iPhone 15 Pro specs (closest to requested iPhone 17 Pro)
|
||||
// Screen: 393 x 852 at 3x = 1179 x 2556 physical pixels
|
||||
const VIEWPORT_WIDTH = 393;
|
||||
const VIEWPORT_HEIGHT = 852;
|
||||
const KEYBOARD_HEIGHT = 336; // Typical iOS keyboard height
|
||||
|
||||
const iPhone15Pro = {
|
||||
...devices['iPhone 14 Pro'],
|
||||
viewport: { width: VIEWPORT_WIDTH, height: VIEWPORT_HEIGHT },
|
||||
deviceScaleFactor: 3,
|
||||
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1',
|
||||
};
|
||||
|
||||
async function takeScreenshots() {
|
||||
console.log('Launching browser with iPhone 15 Pro emulation...');
|
||||
console.log('Output directory:', OUTPUT_DIR);
|
||||
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
const context = await browser.newContext({
|
||||
...iPhone15Pro,
|
||||
hasTouch: true,
|
||||
isMobile: true,
|
||||
});
|
||||
|
||||
const page = await context.newPage();
|
||||
|
||||
try {
|
||||
// Screenshot 1: Main view (no keyboard)
|
||||
console.log('Loading main page...');
|
||||
await page.goto(BASE_URL, { waitUntil: 'domcontentloaded', timeout: 10000 });
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
await page.screenshot({
|
||||
path: join(OUTPUT_DIR, 'mobile-no-keyboard.png'),
|
||||
fullPage: false
|
||||
});
|
||||
console.log('✓ Saved: mobile-no-keyboard.png');
|
||||
|
||||
// Screenshot 2: Simulate keyboard appearing
|
||||
console.log('Simulating virtual keyboard...');
|
||||
|
||||
// Trigger the keyboard handler manually - simulate what happens when keyboard shows
|
||||
await page.evaluate((keyboardHeight) => {
|
||||
// Add keyboard-visible class
|
||||
document.body.classList.add('keyboard-visible');
|
||||
|
||||
// Move toolbar up by keyboard height
|
||||
const toolbar = document.querySelector('.toolbar');
|
||||
if (toolbar) {
|
||||
toolbar.style.transform = `translateY(${-keyboardHeight}px)`;
|
||||
}
|
||||
|
||||
// Show and move accessory bar
|
||||
const accessoryBar = document.querySelector('.keyboard-accessory-bar');
|
||||
if (accessoryBar) {
|
||||
accessoryBar.classList.add('visible');
|
||||
accessoryBar.style.transform = `translateY(${-keyboardHeight}px)`;
|
||||
}
|
||||
|
||||
// Shrink main content area so terminal doesn't extend behind keyboard
|
||||
// Account for toolbar (40px) + accessory bar (44px)
|
||||
const main = document.querySelector('.main');
|
||||
if (main) {
|
||||
main.style.paddingBottom = `${keyboardHeight + 94}px`;
|
||||
}
|
||||
}, KEYBOARD_HEIGHT);
|
||||
|
||||
await page.waitForTimeout(300);
|
||||
|
||||
// Take screenshot of the reduced viewport (simulating keyboard up)
|
||||
await page.screenshot({
|
||||
path: join(OUTPUT_DIR, 'mobile-keyboard-visible.png'),
|
||||
fullPage: false
|
||||
});
|
||||
console.log('✓ Saved: mobile-keyboard-visible.png');
|
||||
|
||||
// Screenshot 3: Full view with keyboard overlay visualization
|
||||
// Reset viewport but keep toolbar position to show the effect
|
||||
await page.setViewportSize({
|
||||
width: VIEWPORT_WIDTH,
|
||||
height: VIEWPORT_HEIGHT
|
||||
});
|
||||
|
||||
// Add a visual keyboard overlay
|
||||
await page.evaluate((keyboardHeight) => {
|
||||
const overlay = document.createElement('div');
|
||||
overlay.id = 'keyboard-overlay';
|
||||
overlay.style.cssText = `
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: ${keyboardHeight}px;
|
||||
background: linear-gradient(to bottom, #2a2a2a 0%, #1a1a1a 100%);
|
||||
border-top: 1px solid #444;
|
||||
z-index: 9999;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-content: flex-start;
|
||||
padding: 8px 4px;
|
||||
gap: 4px;
|
||||
`;
|
||||
|
||||
// Add fake keyboard keys
|
||||
const rows = [
|
||||
'Q W E R T Y U I O P',
|
||||
'A S D F G H J K L',
|
||||
'⇧ Z X C V B N M ⌫',
|
||||
'123 🌐 space return'
|
||||
];
|
||||
|
||||
rows.forEach((row, rowIndex) => {
|
||||
const rowDiv = document.createElement('div');
|
||||
rowDiv.style.cssText = 'display: flex; width: 100%; justify-content: center; gap: 4px;';
|
||||
|
||||
row.split(' ').forEach(key => {
|
||||
const keyEl = document.createElement('div');
|
||||
const isSpecial = ['⇧', '⌫', '123', '🌐', 'space', 'return'].includes(key);
|
||||
const isSpace = key === 'space';
|
||||
const isReturn = key === 'return';
|
||||
|
||||
keyEl.style.cssText = `
|
||||
background: ${isSpecial ? '#3a3a3a' : '#505050'};
|
||||
color: #fff;
|
||||
border-radius: 5px;
|
||||
padding: ${isSpace ? '10px 60px' : isReturn ? '10px 20px' : '10px 8px'};
|
||||
font-size: ${rowIndex === 3 ? '12px' : '14px'};
|
||||
min-width: ${isSpace ? '120px' : isReturn ? '60px' : '28px'};
|
||||
text-align: center;
|
||||
box-shadow: 0 1px 0 #222;
|
||||
`;
|
||||
keyEl.textContent = isSpace ? '' : key;
|
||||
rowDiv.appendChild(keyEl);
|
||||
});
|
||||
|
||||
overlay.appendChild(rowDiv);
|
||||
});
|
||||
|
||||
document.body.appendChild(overlay);
|
||||
}, KEYBOARD_HEIGHT);
|
||||
|
||||
await page.waitForTimeout(200);
|
||||
|
||||
await page.screenshot({
|
||||
path: join(OUTPUT_DIR, 'mobile-with-keyboard.png'),
|
||||
fullPage: false
|
||||
});
|
||||
console.log('✓ Saved: mobile-with-keyboard.png');
|
||||
|
||||
// Screenshot 4: Toolbar close-up with keyboard
|
||||
const toolbar = page.locator('.toolbar');
|
||||
if (await toolbar.count() > 0) {
|
||||
await toolbar.screenshot({
|
||||
path: join(OUTPUT_DIR, 'mobile-toolbar-above-keyboard.png')
|
||||
});
|
||||
console.log('✓ Saved: mobile-toolbar-above-keyboard.png');
|
||||
}
|
||||
|
||||
console.log('\n✅ All screenshots saved to:', OUTPUT_DIR);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error taking screenshots:', error.message);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
}
|
||||
|
||||
takeScreenshots();
|
||||
@@ -1,124 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Respawn Controller Monitor - 12 hour monitoring script
|
||||
# Usage: ./scripts/monitor-respawn.sh <session_id> [duration_hours]
|
||||
|
||||
SESSION_ID="${1:-5ecdf859-3605-42d8-b0a2-f8f0a1b5ff98}"
|
||||
DURATION_HOURS="${2:-12}"
|
||||
ISSUES_FILE="/home/arkon/default/codeman/respawn-monitor-issues.md"
|
||||
FIXES_FILE="/home/arkon/default/codeman/respawn-monitor-fixes.md"
|
||||
API_URL="https://localhost:3000"
|
||||
POLL_INTERVAL=60 # seconds
|
||||
|
||||
# Calculate end time
|
||||
END_TIME=$(($(date +%s) + DURATION_HOURS * 3600))
|
||||
|
||||
log_issue() {
|
||||
local severity="$1"
|
||||
local message="$2"
|
||||
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
echo "" >> "$ISSUES_FILE"
|
||||
echo "### [$severity] $timestamp" >> "$ISSUES_FILE"
|
||||
echo "$message" >> "$ISSUES_FILE"
|
||||
echo "" >> "$ISSUES_FILE"
|
||||
}
|
||||
|
||||
add_fix() {
|
||||
local issue="$1"
|
||||
local fix="$2"
|
||||
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
echo "" >> "$FIXES_FILE"
|
||||
echo "### Issue: $issue" >> "$FIXES_FILE"
|
||||
echo "**Detected:** $timestamp" >> "$FIXES_FILE"
|
||||
echo "" >> "$FIXES_FILE"
|
||||
echo "**Proposed Fix:**" >> "$FIXES_FILE"
|
||||
echo "$fix" >> "$FIXES_FILE"
|
||||
echo "" >> "$FIXES_FILE"
|
||||
echo "---" >> "$FIXES_FILE"
|
||||
}
|
||||
|
||||
# State tracking
|
||||
PREV_STATE=""
|
||||
STATE_STUCK_COUNT=0
|
||||
PREV_CYCLE=0
|
||||
LAST_ACTIVITY=0
|
||||
AI_CHECK_ERRORS=0
|
||||
|
||||
echo "Starting respawn monitoring for session $SESSION_ID"
|
||||
echo "Duration: $DURATION_HOURS hours"
|
||||
echo "Issues logged to: $ISSUES_FILE"
|
||||
echo "Fixes logged to: $FIXES_FILE"
|
||||
|
||||
while [ $(date +%s) -lt $END_TIME ]; do
|
||||
# Get respawn status
|
||||
RESP=$(curl -sk "$API_URL/api/sessions/$SESSION_ID" 2>/dev/null)
|
||||
|
||||
if [ -z "$RESP" ]; then
|
||||
log_issue "ERROR" "API not responding - server may be down"
|
||||
add_fix "API not responding" "Check if codeman-web service is running:\n\`\`\`bash\nsystemctl --user status codeman-web\nsystemctl --user restart codeman-web\n\`\`\`"
|
||||
sleep $POLL_INTERVAL
|
||||
continue
|
||||
fi
|
||||
|
||||
# Parse response
|
||||
STATE=$(echo "$RESP" | jq -r '.respawn.state // "null"')
|
||||
CYCLE=$(echo "$RESP" | jq -r '.respawn.cycleCount // 0')
|
||||
ENABLED=$(echo "$RESP" | jq -r '.respawnEnabled // false')
|
||||
TOKENS=$(echo "$RESP" | jq -r '.respawn.config.lastTokenCount // 0')
|
||||
AI_STATUS=$(echo "$RESP" | jq -r '.respawn.detection.aiCheck.status // "unknown"')
|
||||
AI_ERRORS=$(echo "$RESP" | jq -r '.respawn.detection.aiCheck.consecutiveErrors // 0')
|
||||
TIME_SINCE_ACTIVITY=$(echo "$RESP" | jq -r '.respawn.timeSinceActivity // 0')
|
||||
CONFIDENCE=$(echo "$RESP" | jq -r '.respawn.detection.confidenceLevel // 0')
|
||||
SESSION_STATUS=$(echo "$RESP" | jq -r '.status // "unknown"')
|
||||
|
||||
# Check for issues
|
||||
|
||||
# 1. Session not running
|
||||
if [ "$SESSION_STATUS" = "stopped" ] || [ "$SESSION_STATUS" = "error" ]; then
|
||||
log_issue "CRITICAL" "Session status is '$SESSION_STATUS' - respawn may not function correctly"
|
||||
add_fix "Session stopped/error" "Check session health and restart if needed:\n\`\`\`bash\ncurl -sk $API_URL/api/sessions/$SESSION_ID\n# If needed, create new session or restart\n\`\`\`"
|
||||
fi
|
||||
|
||||
# 2. Respawn disabled unexpectedly
|
||||
if [ "$ENABLED" = "false" ] && [ "$PREV_STATE" != "" ] && [ "$PREV_STATE" != "null" ]; then
|
||||
log_issue "WARNING" "Respawn appears to have been disabled (was in state: $PREV_STATE)"
|
||||
add_fix "Respawn disabled" "Re-enable respawn controller:\n\`\`\`bash\ncurl -sk -X POST $API_URL/api/sessions/$SESSION_ID/respawn/enable\n\`\`\`"
|
||||
fi
|
||||
|
||||
# 3. State stuck for too long (>30 minutes in same state)
|
||||
if [ "$STATE" = "$PREV_STATE" ] && [ "$STATE" != "watching" ]; then
|
||||
STATE_STUCK_COUNT=$((STATE_STUCK_COUNT + 1))
|
||||
if [ $STATE_STUCK_COUNT -ge 30 ]; then # 30 minutes
|
||||
log_issue "WARNING" "State stuck in '$STATE' for $STATE_STUCK_COUNT minutes. Detection: confidence=$CONFIDENCE, timeSinceActivity=${TIME_SINCE_ACTIVITY}ms"
|
||||
add_fix "State stuck in $STATE" "The respawn controller may be stuck. Options:\n1. Check terminal for blocking prompts\n2. Send input to unstick:\n\`\`\`bash\ncurl -sk -X POST $API_URL/api/sessions/$SESSION_ID/input -d '{\"input\": \"\\\\r\"}'\n\`\`\`\n3. Restart respawn:\n\`\`\`bash\ncurl -sk -X POST $API_URL/api/sessions/$SESSION_ID/respawn/stop\ncurl -sk -X POST $API_URL/api/sessions/$SESSION_ID/respawn/start\n\`\`\`"
|
||||
STATE_STUCK_COUNT=0 # Reset to avoid spam
|
||||
fi
|
||||
else
|
||||
STATE_STUCK_COUNT=0
|
||||
fi
|
||||
|
||||
# 4. AI check errors
|
||||
if [ "$AI_ERRORS" -gt 2 ] && [ "$AI_ERRORS" -gt "$AI_CHECK_ERRORS" ]; then
|
||||
log_issue "WARNING" "AI idle check has $AI_ERRORS consecutive errors (status: $AI_STATUS)"
|
||||
add_fix "AI check errors" "AI idle checker is failing. Check:\n1. Claude CLI is working\n2. Sufficient context available\n3. Consider disabling AI check temporarily:\n\`\`\`bash\ncurl -sk -X POST $API_URL/api/sessions/$SESSION_ID/respawn/config -H 'Content-Type: application/json' -d '{\"aiIdleCheckEnabled\": false}'\n\`\`\`"
|
||||
AI_CHECK_ERRORS=$AI_ERRORS
|
||||
fi
|
||||
|
||||
# 5. Cycle completed - log success
|
||||
if [ "$CYCLE" -gt "$PREV_CYCLE" ] && [ "$PREV_CYCLE" -gt 0 ]; then
|
||||
log_issue "INFO" "Respawn cycle $CYCLE completed successfully (tokens: $TOKENS)"
|
||||
fi
|
||||
|
||||
# 6. Very high time since activity (>10 minutes) while not in watching state
|
||||
if [ "$TIME_SINCE_ACTIVITY" -gt 600000 ] && [ "$STATE" != "watching" ]; then
|
||||
log_issue "WARNING" "No activity for ${TIME_SINCE_ACTIVITY}ms while in state '$STATE' - may be stuck"
|
||||
fi
|
||||
|
||||
# Update tracking vars
|
||||
PREV_STATE="$STATE"
|
||||
PREV_CYCLE="$CYCLE"
|
||||
|
||||
sleep $POLL_INTERVAL
|
||||
done
|
||||
|
||||
log_issue "INFO" "Monitoring completed after $DURATION_HOURS hours"
|
||||
echo "Monitoring complete. Check $ISSUES_FILE and $FIXES_FILE"
|
||||
@@ -1,98 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Ralph Loop Wizard Demo - runs through browser, leaves session running
|
||||
*/
|
||||
import { chromium } from 'playwright';
|
||||
import { readFileSync, existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
|
||||
const BASE_URL = 'https://localhost:3000';
|
||||
const CASE_NAME = 'codeman-ios';
|
||||
|
||||
async function main() {
|
||||
console.log('🎬 Starting Ralph Loop Wizard demo...\n');
|
||||
|
||||
// Launch browser (visible)
|
||||
const browser = await chromium.launch({
|
||||
headless: false,
|
||||
args: ['--no-sandbox', '--disable-setuid-sandbox', '--ignore-certificate-errors'],
|
||||
slowMo: 500, // Slow down so you can see what's happening
|
||||
});
|
||||
|
||||
const context = await browser.newContext({
|
||||
ignoreHTTPSErrors: true,
|
||||
});
|
||||
const page = await context.newPage();
|
||||
|
||||
console.log('📱 Opening Codeman web UI...');
|
||||
await page.goto(BASE_URL);
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
console.log('🔄 Clicking Ralph Loop button...');
|
||||
await page.waitForSelector('.btn-ralph', { timeout: 10000 });
|
||||
await page.click('.btn-ralph');
|
||||
|
||||
console.log('📋 Waiting for wizard modal...');
|
||||
await page.waitForSelector('#ralphWizardModal.active', { timeout: 10000 });
|
||||
|
||||
// Select case
|
||||
console.log(`📁 Selecting case: ${CASE_NAME}`);
|
||||
await page.selectOption('#ralphCaseSelect', CASE_NAME);
|
||||
|
||||
// Load initprompt.md if it exists
|
||||
const initPromptPath = join(homedir(), 'codeman-cases', CASE_NAME, 'initprompt.md');
|
||||
let taskDescription = 'Build an awesome iOS app for Codeman!';
|
||||
if (existsSync(initPromptPath)) {
|
||||
taskDescription = readFileSync(initPromptPath, 'utf-8').trim();
|
||||
console.log(`📝 Loaded initprompt.md (${taskDescription.length} chars)`);
|
||||
}
|
||||
|
||||
// Enter task description
|
||||
await page.fill('#ralphTaskDescription', taskDescription);
|
||||
|
||||
// Set completion phrase
|
||||
await page.evaluate(() => {
|
||||
const input = document.getElementById('ralphCompletionPhrase');
|
||||
if (input) input.value = 'IOS_APP_COMPLETE';
|
||||
});
|
||||
|
||||
console.log('➡️ Clicking Next (Step 1 → Step 2)...');
|
||||
await page.click('#ralphNextBtn');
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
// Check for existing plan
|
||||
const existingPlan = await page.$('#existingPlanSection:not(.hidden)');
|
||||
if (existingPlan) {
|
||||
console.log('📋 Existing plan detected, using it...');
|
||||
await page.evaluate(() => {
|
||||
const btns = Array.from(document.querySelectorAll('button'));
|
||||
const useBtn = btns.find(b => b.textContent?.includes('Use Existing'));
|
||||
if (useBtn) useBtn.click();
|
||||
});
|
||||
await page.waitForTimeout(500);
|
||||
}
|
||||
|
||||
console.log('➡️ Clicking Next (Step 2 → Step 3)...');
|
||||
await page.click('#ralphNextBtn');
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
console.log('🚀 Clicking Start Loop...');
|
||||
await page.click('#ralphStartBtn');
|
||||
|
||||
// Wait for session to be created
|
||||
console.log('⏳ Waiting for session to start...');
|
||||
await page.waitForSelector('.session-tab', { timeout: 30000 });
|
||||
|
||||
console.log('\n✅ Ralph Loop started! Session is running.');
|
||||
console.log('👀 Browser will stay open so you can observe.');
|
||||
console.log(' Press Ctrl+C in terminal when done.\n');
|
||||
|
||||
// Keep the script running
|
||||
await new Promise(() => {});
|
||||
}
|
||||
|
||||
main().catch(err => {
|
||||
console.error('Error:', err.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,171 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Start Ralph Loop on PRODUCTION server (port 3000) using E2E fixtures
|
||||
* Uses initprompt.md and @fix_plan.md from the case directory
|
||||
* Does NOT clean up - leaves session running for user verification
|
||||
*/
|
||||
import { chromium } from 'playwright';
|
||||
import { readFileSync, existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
|
||||
const BASE_URL = 'https://localhost:3000';
|
||||
const CASE_NAME = 'codeman-ios';
|
||||
const CASE_PATH = join(homedir(), 'codeman-cases', CASE_NAME);
|
||||
|
||||
async function main() {
|
||||
// Read initprompt.md
|
||||
const initPromptPath = join(CASE_PATH, 'initprompt.md');
|
||||
const fixPlanPath = join(CASE_PATH, '@fix_plan.md');
|
||||
|
||||
if (!existsSync(initPromptPath)) {
|
||||
console.error(`Missing: ${initPromptPath}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const taskDescription = readFileSync(initPromptPath, 'utf-8').trim();
|
||||
const hasFixPlan = existsSync(fixPlanPath);
|
||||
|
||||
console.log('=== Ralph Loop Wizard E2E (Production) ===');
|
||||
console.log(`Case: ${CASE_NAME}`);
|
||||
console.log(`initprompt.md: ${taskDescription.length} chars`);
|
||||
console.log(`@fix_plan.md exists: ${hasFixPlan}`);
|
||||
console.log('');
|
||||
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
args: ['--no-sandbox', '--disable-setuid-sandbox'],
|
||||
});
|
||||
|
||||
const context = await browser.newContext({ ignoreHTTPSErrors: true });
|
||||
const page = await context.newPage();
|
||||
|
||||
// Capture browser console logs
|
||||
page.on('console', msg => {
|
||||
if (msg.type() === 'error' || msg.text().includes('RalphWizard')) {
|
||||
console.log(`[Browser ${msg.type()}] ${msg.text()}`);
|
||||
}
|
||||
});
|
||||
page.on('pageerror', err => console.log(`[Browser Error] ${err.message}`));
|
||||
|
||||
try {
|
||||
console.log('[1/10] Navigating to Codeman...');
|
||||
await page.goto(BASE_URL, { timeout: 10000 });
|
||||
|
||||
console.log('[2/10] Clicking Ralph Loop button (.btn-ralph)...');
|
||||
await page.waitForSelector('.btn-ralph', { timeout: 5000 });
|
||||
await page.click('.btn-ralph');
|
||||
|
||||
console.log('[3/10] Waiting for wizard modal (#ralphWizardModal.active)...');
|
||||
await page.waitForSelector('#ralphWizardModal.active', { timeout: 5000 });
|
||||
|
||||
console.log(`[4/10] Selecting case: ${CASE_NAME}...`);
|
||||
await page.selectOption('#ralphCaseSelect', CASE_NAME);
|
||||
|
||||
console.log('[5/10] Filling task description from initprompt.md...');
|
||||
await page.fill('#ralphTaskDescription', taskDescription);
|
||||
|
||||
console.log('[6/10] Setting completion phrase: IOS_APP_COMPLETE...');
|
||||
await page.evaluate(() => {
|
||||
const input = document.getElementById('ralphCompletionPhrase');
|
||||
if (input) input.value = 'IOS_APP_COMPLETE';
|
||||
});
|
||||
|
||||
console.log('[7/10] Clicking Next -> Step 2...');
|
||||
await page.evaluate(() => {
|
||||
document.getElementById('ralphNextBtn')?.click();
|
||||
});
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
// Check for existing @fix_plan.md detection
|
||||
const existingPlanSection = await page.$('#existingPlanSection:not(.hidden)');
|
||||
if (existingPlanSection) {
|
||||
console.log('[8/10] Existing @fix_plan.md detected, clicking "Use Existing"...');
|
||||
await page.evaluate(() => {
|
||||
const btns = Array.from(document.querySelectorAll('button'));
|
||||
const useBtn = btns.find(b => b.textContent?.includes('Use Existing'));
|
||||
if (useBtn) useBtn.click();
|
||||
});
|
||||
await page.waitForTimeout(500);
|
||||
} else {
|
||||
console.log('[8/10] No existing plan section visible...');
|
||||
}
|
||||
|
||||
console.log('[9/10] Clicking Next -> Step 3 (Launch)...');
|
||||
await page.evaluate(() => {
|
||||
document.getElementById('ralphNextBtn')?.click();
|
||||
});
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
console.log('[10/10] Clicking Start Loop...');
|
||||
await page.evaluate(() => {
|
||||
document.getElementById('ralphStartBtn')?.click();
|
||||
});
|
||||
|
||||
console.log('Waiting for session tab to appear...');
|
||||
await page.waitForSelector('.session-tab', { timeout: 30000 });
|
||||
|
||||
// IMPORTANT: Wait for the wizard's async startRalphLoop() to complete
|
||||
// The wizard needs time to: wait for session ready, then send the prompt
|
||||
console.log('Waiting for wizard to send prompt (checking for busy status)...');
|
||||
|
||||
let session = null;
|
||||
let attempts = 0;
|
||||
const maxAttempts = 30; // 30 seconds max
|
||||
|
||||
while (attempts < maxAttempts) {
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
const sessions = await page.evaluate(async () => {
|
||||
const res = await fetch('/api/sessions');
|
||||
return res.json();
|
||||
});
|
||||
|
||||
session = sessions
|
||||
.filter(s => s.workingDir?.includes('codeman-ios'))
|
||||
.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))[0];
|
||||
|
||||
if (session) {
|
||||
// Check if session is working (prompt was sent)
|
||||
const detail = await page.evaluate(async (id) => {
|
||||
const res = await fetch(`/api/sessions/${id}`);
|
||||
return res.json();
|
||||
}, session.id);
|
||||
|
||||
if (detail.isWorking || detail.tokens?.total > 0) {
|
||||
console.log(`Session is working! Tokens: ${detail.tokens?.total}`);
|
||||
break;
|
||||
}
|
||||
console.log(` Attempt ${attempts + 1}: status=${detail.status}, tokens=${detail.tokens?.total || 0}`);
|
||||
}
|
||||
|
||||
attempts++;
|
||||
}
|
||||
|
||||
if (!session || attempts >= maxAttempts) {
|
||||
console.error('WARNING: Session may not have received the prompt!');
|
||||
}
|
||||
|
||||
console.log('');
|
||||
console.log('========================================');
|
||||
console.log('SUCCESS! Ralph Loop started.');
|
||||
console.log('========================================');
|
||||
console.log(`Session ID: ${session?.id}`);
|
||||
console.log(`Screen: codeman-${session?.id?.slice(0, 8)}`);
|
||||
console.log(`Status: ${session?.status}`);
|
||||
console.log('');
|
||||
console.log('Session is now running. View at: https://localhost:3000');
|
||||
console.log('');
|
||||
console.log('To delete when done:');
|
||||
console.log(` curl -sk -X DELETE "https://localhost:3000/api/sessions/${session?.id}"`);
|
||||
console.log('========================================');
|
||||
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(err => {
|
||||
console.error('FAILED:', err.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,109 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Start Ralph Loop via wizard on production server, leave it running
|
||||
*/
|
||||
import { chromium } from 'playwright';
|
||||
import { readFileSync, existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
|
||||
const BASE_URL = 'https://localhost:3000';
|
||||
const CASE_NAME = 'codeman-ios';
|
||||
|
||||
async function main() {
|
||||
console.log('Starting Ralph Loop via wizard on production server...\n');
|
||||
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
args: ['--no-sandbox', '--disable-setuid-sandbox', '--ignore-certificate-errors'],
|
||||
});
|
||||
|
||||
const context = await browser.newContext({ ignoreHTTPSErrors: true });
|
||||
const page = await context.newPage();
|
||||
|
||||
console.log('1. Opening Codeman web UI...');
|
||||
await page.goto(BASE_URL);
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
console.log('2. Clicking Ralph Loop button...');
|
||||
await page.waitForSelector('.btn-ralph', { timeout: 10000 });
|
||||
await page.click('.btn-ralph');
|
||||
|
||||
console.log('3. Waiting for wizard modal...');
|
||||
await page.waitForSelector('#ralphWizardModal.active', { timeout: 10000 });
|
||||
|
||||
console.log(`4. Selecting case: ${CASE_NAME}`);
|
||||
await page.selectOption('#ralphCaseSelect', CASE_NAME);
|
||||
|
||||
// Load initprompt.md
|
||||
const initPromptPath = join(homedir(), 'codeman-cases', CASE_NAME, 'initprompt.md');
|
||||
let taskDescription = 'Build an awesome iOS app for Codeman!';
|
||||
if (existsSync(initPromptPath)) {
|
||||
taskDescription = readFileSync(initPromptPath, 'utf-8').trim();
|
||||
console.log(`5. Loaded initprompt.md (${taskDescription.length} chars)`);
|
||||
} else {
|
||||
console.log('5. Using default task description');
|
||||
}
|
||||
|
||||
await page.fill('#ralphTaskDescription', taskDescription);
|
||||
|
||||
// Set completion phrase
|
||||
await page.evaluate(() => {
|
||||
const input = document.getElementById('ralphCompletionPhrase');
|
||||
if (input) input.value = 'IOS_APP_COMPLETE';
|
||||
});
|
||||
|
||||
console.log('6. Clicking Next (Step 1 -> Step 2)...');
|
||||
await page.click('#ralphNextBtn');
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
// Check for existing plan
|
||||
const existingPlan = await page.$('#existingPlanSection:not(.hidden)');
|
||||
if (existingPlan) {
|
||||
console.log('7. Existing plan detected, using it...');
|
||||
await page.evaluate(() => {
|
||||
const btns = Array.from(document.querySelectorAll('button'));
|
||||
const useBtn = btns.find(b => b.textContent?.includes('Use Existing'));
|
||||
if (useBtn) useBtn.click();
|
||||
});
|
||||
await page.waitForTimeout(500);
|
||||
} else {
|
||||
console.log('7. No existing plan, proceeding...');
|
||||
}
|
||||
|
||||
console.log('8. Clicking Next (Step 2 -> Step 3)...');
|
||||
await page.click('#ralphNextBtn');
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
console.log('9. Clicking Start Loop...');
|
||||
await page.click('#ralphStartBtn');
|
||||
|
||||
console.log('10. Waiting for session to be created...');
|
||||
await page.waitForSelector('.session-tab', { timeout: 30000 });
|
||||
|
||||
// Get session info from the API
|
||||
const sessions = await page.evaluate(async () => {
|
||||
const res = await fetch('/api/sessions');
|
||||
return res.json();
|
||||
});
|
||||
|
||||
const iosSession = sessions.find(s => s.workingDir?.includes('codeman-ios'));
|
||||
|
||||
console.log('\n========================================');
|
||||
console.log('SUCCESS! Ralph Loop started.');
|
||||
console.log('========================================');
|
||||
console.log(`Session ID: ${iosSession?.id}`);
|
||||
console.log(`Screen: codeman-${iosSession?.id?.slice(0, 8)}`);
|
||||
console.log(`Working Dir: ${iosSession?.workingDir}`);
|
||||
console.log('\nThe session is now running on your production server.');
|
||||
console.log('View it at: https://localhost:3000');
|
||||
console.log('Kill it when done via the web UI or: curl -X DELETE https://localhost:3000/api/sessions/' + iosSession?.id);
|
||||
console.log('========================================\n');
|
||||
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
main().catch(err => {
|
||||
console.error('Error:', err.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,166 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Browser test for clickable file links in Codeman terminal
|
||||
* Uses Playwright directly to ignore HTTPS errors
|
||||
*/
|
||||
|
||||
import { chromium } from 'playwright';
|
||||
|
||||
const BASE_URL = 'https://localhost:3000';
|
||||
const TEST_LOG_FILE = '/tmp/test-link-click.log';
|
||||
|
||||
async function main() {
|
||||
console.log('Starting browser test for clickable links...\n');
|
||||
|
||||
// Create test log file
|
||||
const { writeFileSync, appendFileSync } = await import('fs');
|
||||
writeFileSync(TEST_LOG_FILE, `=== Test started at ${new Date().toISOString()} ===\n`);
|
||||
for (let i = 1; i <= 10; i++) {
|
||||
appendFileSync(TEST_LOG_FILE, `Entry #${i} - ${Date.now()}\n`);
|
||||
}
|
||||
console.log(`Created test file: ${TEST_LOG_FILE}\n`);
|
||||
|
||||
// Launch browser ignoring HTTPS errors
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
args: ['--ignore-certificate-errors', '--ignore-ssl-errors']
|
||||
});
|
||||
|
||||
const context = await browser.newContext({
|
||||
ignoreHTTPSErrors: true
|
||||
});
|
||||
|
||||
const page = await context.newPage();
|
||||
|
||||
try {
|
||||
// Navigate to Codeman
|
||||
console.log('Navigating to Codeman...');
|
||||
await page.goto(BASE_URL, { waitUntil: 'networkidle', timeout: 30000 });
|
||||
console.log('Page loaded: ' + await page.title());
|
||||
|
||||
// Wait for terminal to be ready
|
||||
await page.waitForSelector('.xterm-screen', { timeout: 10000 });
|
||||
console.log('Terminal found\n');
|
||||
|
||||
// Get list of sessions
|
||||
const sessions = await page.evaluate(async () => {
|
||||
const res = await fetch('/api/sessions');
|
||||
return res.json();
|
||||
});
|
||||
console.log(`Found ${sessions.length} session(s)`);
|
||||
|
||||
if (sessions.length === 0) {
|
||||
console.log('No sessions found. Creating a shell session...');
|
||||
const newSession = await page.evaluate(async () => {
|
||||
const res = await fetch('/api/quick-start', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ caseName: 'link-test', mode: 'shell' })
|
||||
});
|
||||
return res.json();
|
||||
});
|
||||
console.log('Created session:', newSession.session?.id);
|
||||
await page.waitForTimeout(2000);
|
||||
}
|
||||
|
||||
// Get active session (use codeman session if exists)
|
||||
const codemanSession = sessions.find(s => s.workingDir?.includes('codeman'));
|
||||
const sessionId = codemanSession?.id || sessions[0]?.id;
|
||||
console.log(`Using session: ${sessionId}\n`);
|
||||
|
||||
// Send a command that outputs file paths
|
||||
console.log('Sending command with file path...');
|
||||
await page.evaluate(async (sid, logFile) => {
|
||||
await fetch(`/api/sessions/${sid}/input`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ input: `echo "Monitor: tail -f ${logFile}"\r` })
|
||||
});
|
||||
}, sessionId, TEST_LOG_FILE);
|
||||
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
// Take screenshot
|
||||
await page.screenshot({ path: '/tmp/codeman-link-test-1.png' });
|
||||
console.log('Screenshot saved: /tmp/codeman-link-test-1.png\n');
|
||||
|
||||
// Check if terminal contains our file path
|
||||
const terminalContent = await page.evaluate(() => {
|
||||
const screen = document.querySelector('.xterm-screen');
|
||||
return screen?.textContent || '';
|
||||
});
|
||||
|
||||
if (terminalContent.includes(TEST_LOG_FILE)) {
|
||||
console.log('File path appears in terminal output');
|
||||
} else {
|
||||
console.log('WARNING: File path not found in terminal. Content preview:');
|
||||
console.log(terminalContent.substring(0, 500));
|
||||
}
|
||||
|
||||
// Try to find clickable links in xterm
|
||||
const linkCount = await page.evaluate(() => {
|
||||
// xterm link detection happens on mouse move, so we need to trigger it
|
||||
const links = document.querySelectorAll('.xterm-link');
|
||||
return links.length;
|
||||
});
|
||||
console.log(`\nClickable links found: ${linkCount}`);
|
||||
|
||||
// Try hovering over the terminal to trigger link detection
|
||||
console.log('\nHovering over terminal to trigger link detection...');
|
||||
const termRect = await page.locator('.xterm-screen').boundingBox();
|
||||
if (termRect) {
|
||||
// Move mouse across the terminal
|
||||
for (let y = termRect.y + 50; y < termRect.y + termRect.height - 50; y += 20) {
|
||||
for (let x = termRect.x + 50; x < termRect.x + termRect.width - 50; x += 50) {
|
||||
await page.mouse.move(x, y);
|
||||
await page.waitForTimeout(50);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check for tooltip (shows when hovering over link)
|
||||
const tooltipVisible = await page.evaluate(() => {
|
||||
const tooltip = document.getElementById('file-link-tooltip');
|
||||
return tooltip?.style.display !== 'none' && tooltip?.style.display !== '';
|
||||
});
|
||||
console.log('Tooltip visible:', tooltipVisible);
|
||||
|
||||
// Check for log viewer windows
|
||||
const logViewerCount = await page.evaluate(() => {
|
||||
return document.querySelectorAll('.log-viewer-window').length;
|
||||
});
|
||||
console.log('Log viewer windows:', logViewerCount);
|
||||
|
||||
// Take final screenshot
|
||||
await page.screenshot({ path: '/tmp/codeman-link-test-2.png' });
|
||||
console.log('\nFinal screenshot: /tmp/codeman-link-test-2.png');
|
||||
|
||||
// Test the link provider registration
|
||||
console.log('\n--- Link Provider Debug ---');
|
||||
const debugInfo = await page.evaluate(() => {
|
||||
// Check if app has link provider registered
|
||||
const app = window.app;
|
||||
if (!app) return { error: 'No app object found' };
|
||||
|
||||
const terminal = app.terminals?.get(app.activeSessionId);
|
||||
if (!terminal) return { error: 'No active terminal', activeSessionId: app.activeSessionId };
|
||||
|
||||
return {
|
||||
hasTerminal: true,
|
||||
activeSessionId: app.activeSessionId,
|
||||
terminalBuffer: terminal.buffer?.active?.length || 0
|
||||
};
|
||||
});
|
||||
console.log('Debug info:', debugInfo);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error:', error.message);
|
||||
await page.screenshot({ path: '/tmp/codeman-link-test-error.png' });
|
||||
console.log('Error screenshot saved to /tmp/codeman-link-test-error.png');
|
||||
} finally {
|
||||
await browser.close();
|
||||
console.log('\nBrowser closed');
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -72,7 +72,7 @@ import { mkdtempSync, rmSync, readFileSync, existsSync } from 'node:fs';
|
||||
import { tmpdir, homedir } from 'node:os';
|
||||
import { join, delimiter, dirname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { enabledClis } from '../src/config/cli-registry/index.js';
|
||||
import { enabledClis } from '../src/config/cli-registry/registry.js';
|
||||
import type { CliEntry } from '../src/config/cli-registry/types.js';
|
||||
import {
|
||||
buildCustomModelInjection,
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Test script for link detection patterns
|
||||
*/
|
||||
|
||||
const patterns = {
|
||||
cmdPattern: /(tail|cat|head|less|grep|watch|multitail)\s+(?:[^\/\n]+?\s+)?(\/[^\s"'<>|;&\n\)]+)/g,
|
||||
bashPathPattern: /Bash\([^)]*?(\/(?:var|tmp|home|usr|etc|opt|log|logs)[^\s"'<>|;&\)\n]+)/g,
|
||||
generalPathPattern: /(\/(?:home|tmp|var|etc|usr|opt)[^\s"'<>|;&\n\)\]]+\.(?:log|txt|json|md|ts|js|sh|py|yaml|yml|csv|xml|html|css))/g,
|
||||
logPathPattern: /(\/var\/log\/[^\s"'<>|;&\n\)\]]+)/g,
|
||||
claudeOutputPattern: /(?:Created|Writing|Saved|File|Output|Streaming|Monitoring|Log)(?:\s+(?:file|to|at))?[:\s]+([\/~][^\s"'<>|;&\n\)]+)/gi
|
||||
};
|
||||
|
||||
const tests = [
|
||||
'tail -f /tmp/test.log',
|
||||
'tail -n 100 /var/log/syslog',
|
||||
'cat /home/user/file.txt',
|
||||
'head -n 10 /etc/passwd',
|
||||
'Bash(tail -f /tmp/test.log)',
|
||||
'Created file: /tmp/newfile.log',
|
||||
'Writing to /home/user/output.txt',
|
||||
'Monitoring file: /var/log/syslog',
|
||||
'Streaming /home/user/logs/app.log',
|
||||
'/home/arkon/project/file.log',
|
||||
'/tmp/test-output.txt',
|
||||
'echo "tail -f /tmp/test.log"',
|
||||
'The output is in /home/user/results.csv',
|
||||
'plain text without paths'
|
||||
];
|
||||
|
||||
console.log('Link Pattern Test Results\n');
|
||||
|
||||
for (const [name, pattern] of Object.entries(patterns)) {
|
||||
console.log(`\n=== ${name} ===`);
|
||||
console.log(`Pattern: ${pattern.source}\n`);
|
||||
|
||||
for (const test of tests) {
|
||||
pattern.lastIndex = 0;
|
||||
const matches = [];
|
||||
let m;
|
||||
while ((m = pattern.exec(test)) !== null) {
|
||||
// Get the captured group (varies by pattern)
|
||||
matches.push(m[1] || m[2]);
|
||||
}
|
||||
if (matches.length > 0) {
|
||||
console.log(` ✓ "${test}"`);
|
||||
console.log(` → Found: ${matches.join(', ')}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log('\n\n=== Combined Test ===');
|
||||
console.log('Testing all patterns on each input:\n');
|
||||
|
||||
for (const test of tests) {
|
||||
const allMatches = [];
|
||||
for (const [name, pattern] of Object.entries(patterns)) {
|
||||
pattern.lastIndex = 0;
|
||||
let m;
|
||||
while ((m = pattern.exec(test)) !== null) {
|
||||
const path = m[1] || m[2];
|
||||
if (path && !allMatches.includes(path)) {
|
||||
allMatches.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (allMatches.length > 0) {
|
||||
console.log(`✓ "${test}"`);
|
||||
console.log(` → ${allMatches.join(', ')}`);
|
||||
} else {
|
||||
console.log(`✗ "${test}" - no match`);
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Test script for clickable file links in Codeman terminal
|
||||
# Creates a log file and continuously writes timestamped data
|
||||
|
||||
LOGFILE="/tmp/codeman-test-$(date +%s).log"
|
||||
|
||||
echo "Created log file: $LOGFILE"
|
||||
echo ""
|
||||
echo "You can monitor this file with:"
|
||||
echo " tail -f $LOGFILE"
|
||||
echo ""
|
||||
echo "Starting to write data every 2 seconds..."
|
||||
echo ""
|
||||
|
||||
# Write initial content
|
||||
echo "=== Test Log Started at $(date) ===" > "$LOGFILE"
|
||||
|
||||
# Write data continuously
|
||||
count=0
|
||||
while true; do
|
||||
count=$((count + 1))
|
||||
echo "[$(date '+%H:%M:%S')] Entry #$count - Random: $RANDOM" >> "$LOGFILE"
|
||||
|
||||
# Print status every 5 entries
|
||||
if [ $((count % 5)) -eq 0 ]; then
|
||||
echo "Wrote $count entries to $LOGFILE"
|
||||
fi
|
||||
|
||||
sleep 2
|
||||
done
|
||||
@@ -1,179 +0,0 @@
|
||||
/**
|
||||
* Manual verification harness for the session-sidebar feature.
|
||||
*
|
||||
* Renders the real UI in headless Chromium against a testMode WebServer,
|
||||
* injects a synthetic 25-session fleet, and screenshots every layout state.
|
||||
* Not part of the automated suite — run it by hand:
|
||||
*
|
||||
* npx tsx scripts/verify-session-sidebar.mts
|
||||
*
|
||||
* SAFETY: uses the repo's own test harness (temp HOME, testMode server) on a
|
||||
* dedicated port. It never touches a real Codeman instance or tmux socket.
|
||||
*/
|
||||
import { chromium } from 'playwright';
|
||||
import { WebServer } from '../src/web/server.js';
|
||||
import { mkdirSync } from 'node:fs';
|
||||
import { mkdtempSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
|
||||
// Mirror test/setup.ts: isolate HOME before the app modules touch state.
|
||||
process.env.HOME = mkdtempSync(join(tmpdir(), 'codeman-sidebar-verify-'));
|
||||
process.env.VITEST = 'true';
|
||||
|
||||
const PORT = 3299;
|
||||
const OUT = process.env.SIDEBAR_SHOTS_DIR ?? join(tmpdir(), 'codeman-sidebar-shots');
|
||||
mkdirSync(OUT, { recursive: true });
|
||||
|
||||
// Generic on purpose: these names end up in the harness screenshots, so they
|
||||
// should not carry one contributor's project list into everyone else's review.
|
||||
// The mix of CLI modes matters (each renders a different badge); the names do not.
|
||||
const PROJECTS = [
|
||||
['api-server', 'claude'],
|
||||
['web-client', 'claude'],
|
||||
['mobile-app', 'codex'],
|
||||
['data-pipeline', 'claude'],
|
||||
['shared-lib', 'gemini'],
|
||||
['codeman', 'claude'],
|
||||
['docs-site', 'claude'],
|
||||
['batch-jobs', 'opencode'],
|
||||
['search-index', 'claude'],
|
||||
];
|
||||
const STATUSES = ['idle', 'busy', 'idle', 'busy', 'error', 'idle'];
|
||||
|
||||
function fleet(n: number) {
|
||||
const out: any[] = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
const [proj, mode] = PROJECTS[i % PROJECTS.length];
|
||||
const status = STATUSES[i % STATUSES.length];
|
||||
out.push({
|
||||
id: `sess-${String(i).padStart(4, '0')}-aaaa-bbbb-cccc-dddddddddddd`,
|
||||
pid: 10000 + i,
|
||||
status,
|
||||
workingDir: `${tmpdir()}/projects/${proj}`,
|
||||
name: `${proj}${i > 8 ? '-' + Math.floor(i / 9) : ''}`,
|
||||
mode,
|
||||
currentTaskId: null,
|
||||
createdAt: Date.now() - i * 60000,
|
||||
lastActivityAt: Date.now() - i * 1000,
|
||||
isWorking: status === 'busy',
|
||||
messageCount: i * 3,
|
||||
totalCost: 0,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
color: 'default',
|
||||
taskStats: { total: i % 4, running: i % 3 === 0 ? 2 : 0, completed: 0, failed: 0 },
|
||||
taskTree: [],
|
||||
tokens: { input: 0, output: 0, total: 0 },
|
||||
bufferStats: { terminalBufferSize: 0, textOutputSize: 0, messageCount: 0 },
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const SESSIONS = fleet(25);
|
||||
|
||||
async function main() {
|
||||
const server = new WebServer(PORT, false, true);
|
||||
await server.start();
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
const results: string[] = [];
|
||||
|
||||
async function shot(
|
||||
name: string,
|
||||
opts: { layout: 'header' | 'sidebar'; collapsed?: boolean; width: number; height: number; touch?: boolean }
|
||||
) {
|
||||
const ctx = await browser.newContext({
|
||||
viewport: { width: opts.width, height: opts.height },
|
||||
hasTouch: !!opts.touch,
|
||||
isMobile: !!opts.touch,
|
||||
deviceScaleFactor: 2,
|
||||
});
|
||||
const page = await ctx.newPage();
|
||||
const settings = JSON.stringify({ sessionListLayout: opts.layout });
|
||||
const collapsed = opts.collapsed === undefined ? null : opts.collapsed ? '1' : '0';
|
||||
await page.addInitScript(
|
||||
([s, c]) => {
|
||||
localStorage.setItem('codeman-app-settings', s as string);
|
||||
localStorage.setItem('codeman-app-settings-mobile', s as string);
|
||||
if (c !== null) localStorage.setItem('codeman-sidebar-collapsed', c as string);
|
||||
else localStorage.removeItem('codeman-sidebar-collapsed');
|
||||
},
|
||||
[settings, collapsed]
|
||||
);
|
||||
await page.goto(`http://localhost:${PORT}`, { waitUntil: 'domcontentloaded' });
|
||||
await page.waitForTimeout(1500);
|
||||
|
||||
await page.evaluate((list) => {
|
||||
const app = (window as any).app;
|
||||
if (!app) throw new Error('no window.app');
|
||||
app.sessions.clear();
|
||||
for (const s of list as any[]) app.sessions.set(s.id, s);
|
||||
// The renderer iterates sessionOrder, not the map.
|
||||
app.sessionOrder = (list as any[]).map((s) => s.id);
|
||||
app.activeSessionId = (list as any[])[3].id;
|
||||
// renderSessionTabs() is debounced; drive the immediate path directly.
|
||||
(app._fullRenderSessionTabs ?? app._renderSessionTabsImmediate)?.call(app);
|
||||
app.applySessionListLayout?.();
|
||||
}, SESSIONS as any);
|
||||
await page.waitForTimeout(600);
|
||||
|
||||
const info = await page.evaluate(() => {
|
||||
const root = document.documentElement;
|
||||
const aside = document.getElementById('sessionSidebar');
|
||||
const tabsEl = document.getElementById('sessionTabs');
|
||||
const asideBox = aside?.getBoundingClientRect();
|
||||
const cs = aside ? getComputedStyle(aside) : null;
|
||||
return {
|
||||
dataSessionList: root.dataset.sessionList ?? null,
|
||||
dataSidebar: root.dataset.sidebar ?? null,
|
||||
rows: document.querySelectorAll('.session-tab').length,
|
||||
tabsParent: tabsEl?.parentElement?.id || tabsEl?.parentElement?.className || null,
|
||||
asideWidth: asideBox ? Math.round(asideBox.width) : null,
|
||||
asideVisible: cs ? cs.display !== 'none' && cs.visibility !== 'hidden' : null,
|
||||
asideInert: aside?.hasAttribute('inert') ?? null,
|
||||
ariaHidden: aside?.getAttribute('aria-hidden') ?? null,
|
||||
toggleAriaExpanded: document.getElementById('sidebarToggleBtn')?.getAttribute('aria-expanded') ?? null,
|
||||
firstRowText:
|
||||
(document.querySelector('.session-tab') as HTMLElement | null)?.innerText
|
||||
?.trim()
|
||||
.replace(/\s+/g, ' ')
|
||||
.slice(0, 40) ?? null,
|
||||
listScrollable: (() => {
|
||||
const el = document.getElementById('sessionTabs');
|
||||
return el ? el.scrollHeight > el.clientHeight + 2 : null;
|
||||
})(),
|
||||
};
|
||||
});
|
||||
|
||||
await page.waitForTimeout(400);
|
||||
const file = join(OUT, `${name}.png`);
|
||||
await page.screenshot({ path: file });
|
||||
results.push(`${name.padEnd(28)} ${JSON.stringify(info)}`);
|
||||
await ctx.close();
|
||||
return info;
|
||||
}
|
||||
|
||||
await shot('01-header-desktop', { layout: 'header', width: 1600, height: 900 });
|
||||
await shot('02-sidebar-expanded', { layout: 'sidebar', collapsed: false, width: 1600, height: 900 });
|
||||
await shot('03-sidebar-collapsed-rail', { layout: 'sidebar', collapsed: true, width: 1600, height: 900 });
|
||||
await shot('04-sidebar-narrow-1000', { layout: 'sidebar', collapsed: true, width: 1000, height: 800 });
|
||||
await shot('05-sidebar-drawer-open-1000', { layout: 'sidebar', collapsed: false, width: 1000, height: 800 });
|
||||
await shot('06-sidebar-phone-closed', { layout: 'sidebar', collapsed: true, width: 393, height: 852, touch: true });
|
||||
await shot('07-sidebar-phone-open', { layout: 'sidebar', collapsed: false, width: 393, height: 852, touch: true });
|
||||
|
||||
console.log('\n=== RESULTS ===');
|
||||
for (const r of results) console.log(r);
|
||||
console.log(`\nScreenshots in ${OUT}`);
|
||||
|
||||
await browser.close();
|
||||
await server.stop();
|
||||
}
|
||||
|
||||
main().then(
|
||||
() => process.exit(0),
|
||||
(e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
}
|
||||
);
|
||||
@@ -190,11 +190,6 @@ export abstract class AiCheckerBase<
|
||||
*/
|
||||
protected abstract getNegativeVerdict(): V;
|
||||
|
||||
/**
|
||||
* Get the error verdict value.
|
||||
*/
|
||||
protected abstract getErrorVerdict(): V;
|
||||
|
||||
/**
|
||||
* Create an error result.
|
||||
*/
|
||||
|
||||
@@ -165,10 +165,6 @@ export class AiIdleChecker extends AiCheckerBase<AiCheckVerdict, AiIdleCheckConf
|
||||
return 'WORKING';
|
||||
}
|
||||
|
||||
protected getErrorVerdict(): AiCheckVerdict {
|
||||
return 'ERROR';
|
||||
}
|
||||
|
||||
protected createErrorResult(reasoning: string, durationMs: number): AiCheckResult {
|
||||
return { verdict: 'ERROR', reasoning, durationMs };
|
||||
}
|
||||
|
||||
@@ -139,10 +139,6 @@ export class AiPlanChecker extends AiCheckerBase<
|
||||
return 'NOT_PLAN_MODE';
|
||||
}
|
||||
|
||||
protected getErrorVerdict(): AiPlanCheckVerdict {
|
||||
return 'ERROR';
|
||||
}
|
||||
|
||||
protected createErrorResult(reasoning: string, durationMs: number): AiPlanCheckResult {
|
||||
return { verdict: 'ERROR', reasoning, durationMs };
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
* @module config/cli-registry/argv
|
||||
*/
|
||||
|
||||
import type { ArgSpec, CliEntry, CliLaunch, Cond, EngineValue, ParamSpec, QuoteStyle } from './types.js';
|
||||
import type { ArgSpec, CliLaunch, Cond, EngineValue, ParamSpec, QuoteStyle } from './types.js';
|
||||
import { matchesPattern } from './patterns.js';
|
||||
import { SAFE_BARE_TOKEN } from './patterns.js';
|
||||
|
||||
@@ -178,13 +178,3 @@ export function renderLaunch(
|
||||
|
||||
return rendered.join(' || ');
|
||||
}
|
||||
|
||||
/** Convenience: render an entry's launch command straight from a `CliEntry`. */
|
||||
export function renderCliCommand(
|
||||
entry: CliEntry,
|
||||
params: ParamValues,
|
||||
engineValues: EngineValues,
|
||||
gatesPassed?: ReadonlySet<string>
|
||||
): string {
|
||||
return renderLaunch(entry.launch, params, engineValues, gatesPassed);
|
||||
}
|
||||
@@ -3,59 +3,4 @@
|
||||
* @module config/cli-registry
|
||||
*/
|
||||
|
||||
export type {
|
||||
ArgSpec,
|
||||
CliCapabilities,
|
||||
CliCredStore,
|
||||
CliDiscovery,
|
||||
CliEntry,
|
||||
CliEnv,
|
||||
CliId,
|
||||
CliIdentityProbe,
|
||||
CliLaunch,
|
||||
CliOverlays,
|
||||
CliRegistryFile,
|
||||
CliVariant,
|
||||
CliVersionProbe,
|
||||
Cond,
|
||||
EngineValue,
|
||||
ParamSpec,
|
||||
QuoteStyle,
|
||||
} from './types.js';
|
||||
export {
|
||||
matchesPattern,
|
||||
TOKEN_PATTERNS,
|
||||
SAFE_BARE_TOKEN,
|
||||
compileVersionRegex,
|
||||
MAX_VERSION_OUTPUT,
|
||||
} from './patterns.js';
|
||||
export type { TokenPattern } from './patterns.js';
|
||||
export { renderLaunch, renderCliCommand } from './argv.js';
|
||||
export type { EngineValues, ParamValues } from './argv.js';
|
||||
export { CliEntrySchema } from './schema.js';
|
||||
export type { ValidatedCliEntry } from './schema.js';
|
||||
export { STOCK_CLIS } from './stock.js';
|
||||
export {
|
||||
asCliId,
|
||||
cliIds,
|
||||
enabledCliIds,
|
||||
enabledClis,
|
||||
getCli,
|
||||
listClis,
|
||||
loadCliRegistry,
|
||||
reloadCliRegistry,
|
||||
resolveInstallCommandForPlatform,
|
||||
resolveRegistry,
|
||||
} from './registry.js';
|
||||
export type { LoadResult } from './registry.js';
|
||||
export {
|
||||
COMPOSER_ANCHOR_KINDS,
|
||||
isKnownLauncherProfile,
|
||||
isKnownPredictProfile,
|
||||
isKnownSetenvProfile,
|
||||
LAUNCHER_PROFILE_NAMES,
|
||||
PREDICT_PROFILES,
|
||||
SETENV_PROFILE_NAMES,
|
||||
TRANSCRIPT_READER_NAMES,
|
||||
} from './profiles.js';
|
||||
export type { LauncherProfileName, SetenvProfileName } from './profiles.js';
|
||||
export { enabledCliIds, getCli } from './registry.js';
|
||||
@@ -77,16 +77,10 @@ export type LauncherProfileName = (typeof LAUNCHER_PROFILE_NAMES)[number];
|
||||
export type SetenvProfileName = (typeof SETENV_PROFILE_NAMES)[number];
|
||||
|
||||
/**
|
||||
* Transcript readers, selected via `capabilities.transcript`. Unlike the profile registries
|
||||
* above this one is closed over the schema enum itself rather than an open string, since
|
||||
* transcript format is a small, genuinely fixed set — see CliCapabilities['transcript'].
|
||||
* True when `name` is a predictive-echo profile this build actually implements.
|
||||
* Nothing calls it yet; it stays beside the registry it reads.
|
||||
* @knipignore
|
||||
*/
|
||||
export const TRANSCRIPT_READER_NAMES = ['claude-jsonl', 'codex-rollout', 'deepseek-zstd', 'none'] as const;
|
||||
|
||||
/** Composer-row finders, selected via `capabilities.echo.anchor.kind`. Also schema-closed. */
|
||||
export const COMPOSER_ANCHOR_KINDS = ['glyph', 'cursor', 'none'] as const;
|
||||
|
||||
/** True when `name` is a predictive-echo profile this build actually implements. */
|
||||
export function isKnownPredictProfile(name: string | undefined): boolean {
|
||||
return name !== undefined && Object.prototype.hasOwnProperty.call(PREDICT_PROFILES, name);
|
||||
}
|
||||
|
||||
@@ -32,18 +32,10 @@
|
||||
|
||||
import { existsSync, readFileSync, renameSync, statSync } from 'node:fs';
|
||||
import { dataPath } from '../instance.js';
|
||||
import type { CliEntry, CliId, CliRegistryFile } from './types.js';
|
||||
import type { CliEntry, CliRegistryFile } from './types.js';
|
||||
import { CliEntrySchema } from './schema.js';
|
||||
import { STOCK_CLIS } from './stock.js';
|
||||
|
||||
/** Construct a validated CliId. Throws if `raw` is not a well-formed id — call at API boundaries. */
|
||||
export function asCliId(raw: string): CliId {
|
||||
if (!/^[a-z][a-z0-9-]{0,23}$/.test(raw)) {
|
||||
throw new Error(`invalid CLI id: ${JSON.stringify(raw)}`);
|
||||
}
|
||||
return raw as CliId;
|
||||
}
|
||||
|
||||
function filePath(): string {
|
||||
return dataPath('clis.json');
|
||||
}
|
||||
@@ -227,10 +219,6 @@ export function getCli(id: string): CliEntry | undefined {
|
||||
return listClis().find((e) => (e.id as string) === id);
|
||||
}
|
||||
|
||||
export function cliIds(): string[] {
|
||||
return listClis().map((e) => e.id as string);
|
||||
}
|
||||
|
||||
/** Every enabled entry's id, in registry order. */
|
||||
export function enabledCliIds(): string[] {
|
||||
return enabledClis().map((e) => e.id as string);
|
||||
|
||||
@@ -817,5 +817,3 @@ export const CliEntrySchema = z
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export type ValidatedCliEntry = z.infer<typeof CliEntrySchema>;
|
||||
@@ -26,7 +26,8 @@
|
||||
* so a bad row fails the gate and never reaches the route.
|
||||
*
|
||||
* Where each figure of the stock rows comes from, and what was checked (2026-11-08; the two rows
|
||||
* added on 2026-11-10, `ornith:9b-q4_k_m` and `muse-glimmer:30b-q4_k_m`, were read that day).
|
||||
* added on 2026-11-10, `ornith:9b-q4_k_m` and `muse-glimmer:30b-q4_k_m`, were read that day;
|
||||
* `muse-glimmer:30b-mlx` was read and measured on 2026-11-12).
|
||||
* [V] read at the source that day, [M] measured on a Mac, [C] computed from [V] inputs:
|
||||
*
|
||||
* | Figure | Source | Checked |
|
||||
@@ -152,6 +153,26 @@
|
||||
* of many requests, in which the prefix snapshots may add up to 8 GiB. Its figures stay
|
||||
* the measured ones (with 8 GiB on top it would not be offered on the Mac it ran on),
|
||||
* and a 30-request session on it is the first thing to measure next.
|
||||
* Measured again on 2026-11-12 on the same Mac, from the runner's own log line
|
||||
* (`msg=memory peak=... held=...` after every request): 39,600 bytes per token between
|
||||
* prompts of 30,000 and 94,500 tokens, and the session this row owed, twelve separate
|
||||
* prompts of 15,000 tokens, added 0.5 GiB of prefix snapshots each (5.6 GiB after
|
||||
* twelve, still growing): the whole run ended at 33.4 GB of the 40.2 GB that Mac's
|
||||
* runtime measures. The row's figures are unchanged by it.
|
||||
* - `muse-glimmer:30b-mlx`: MEASURED the same way on that Mac (2026-11-12, runtime
|
||||
* 0.40.15). What stayed held grew by 37,900 to 45,100 bytes per token between prompts
|
||||
* of 30,000, 60,000 and 94,600 tokens. The 13 full-attention layers alone compute to
|
||||
* 13,312 in bf16 and all 52 layers at full length to 53,248, so the runner evidently
|
||||
* does not trim the 39 sliding-window layers to their window (an inference from the
|
||||
* figure, not read in its source). The row takes the upper end. It counts the whole
|
||||
* 8 GiB prefix budget, because the same run filled it: twelve separate prompts of
|
||||
* 15,000 tokens added 0.53 GiB each until the runner dropped the oldest. The process
|
||||
* (`footprint`) stood 0.2 GB above the runner's own count at the end. Its lifetime
|
||||
* peak stood 3.0 to 3.3 GB above that, which is a FLOOR for the peak of a long prompt:
|
||||
* a lifetime maximum taken at the end of the run hides a transient of up to 9 GB
|
||||
* during the earlier, longer prompts. So the row takes the first measured row's 5 GB.
|
||||
* The tag carries a draft model; its tensors are inside `bytes`, and what it holds is
|
||||
* inside these figures.
|
||||
* - every other `mlx` row: held = the K/V cache in bf16 + one recurrent snapshot per
|
||||
* 8,192 tokens, computed from the config, x 37,000 / 28,340: the ratio of what the
|
||||
* measured row really held to the same computation for it (same runner, same
|
||||
@@ -204,9 +225,15 @@
|
||||
* open, has it answer with thinking only in a long conversation at 65,536 tokens.
|
||||
* - `qwen3-coder-next` (51.7 GB): the generation before Qwen3.6. Its card shows its results
|
||||
* as pictures only, so there is no figure to rank it by against the rows listed here.
|
||||
* - `muse-glimmer:30b-mlx` and the `-dflash` tags of that model: open runtime issues 17656
|
||||
* and 18269 on the MLX build, and no rule here covers the memory of a separate draft
|
||||
* model. Its GGUF build `muse-glimmer:30b-q4_k_m` is listed.
|
||||
* - The `-dflash` tags of Muse Glimmer (`30b-q4_k_m-dflash`, `30b-nvfp4-dflash`): a separate
|
||||
* draft model whose memory no rule here covers. `muse-glimmer:30b-mlx`, which is built
|
||||
* from the second one's layers, IS listed since 2026-11-12, with measured figures. Its
|
||||
* two open runtime issues were read again that day: 17656 takes its `nvfp4` weights for
|
||||
* a build the MLX engine cannot accelerate (on the Mac it ran on the runtime logged
|
||||
* "MLX engine initialized ... device=gpu" and it wrote twice as fast as the GGUF build),
|
||||
* and 18269 reports it stuck in "Stopping..." and a restart on a 32 GB Mac, a size the
|
||||
* measured figures keep it away from (its maintainer promised a memory fix "in the next
|
||||
* release" in September; whether that predates the pinned 0.40.15 is not known).
|
||||
* - The plain tags `qwen3.5:9b`, `mimo-v2.6:9b` and `qwen3.8:27b`: a Mac pulls their MLX
|
||||
* builds, whose 8 GiB of prefix snapshots do not fit the Macs a 9B or a 27B is for. Their
|
||||
* GGUF builds are listed instead.
|
||||
@@ -407,13 +434,35 @@ const LLAMACPP_DEFAULT_DRAFT_TOKENS = 4;
|
||||
/** The prefix snapshots the MLX runner may keep: `maxPagedOutBytes`, 8 GiB. */
|
||||
const MLX_PREFIX_CACHE_BYTES = 8 * 1024 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* The memory figures measured for `muse-glimmer:30b-mlx` on the same Mac (2026-11-12, runtime
|
||||
* 0.40.15, the MLX runner), in decimal bytes: the runner's own `memory peak / held` log line
|
||||
* after every request, and the process footprint at the end. See the file header (MEMORY).
|
||||
*/
|
||||
const MUSE_MLX_MEASURED_MEMORY = {
|
||||
/** Held grew by 37,900 to 45,100 bytes per token between prompts of 30,000, 60,000 and 94,600 tokens: the upper end. */
|
||||
heldBytesPerToken: 45_000,
|
||||
/**
|
||||
* The prefix snapshots in full (the run filled them: 0.53 GiB per separate prompt of 15,000
|
||||
* tokens until the oldest was dropped), and 0.5 GB for what the process holds beside the
|
||||
* runner's own count (0.2 GB measured).
|
||||
*/
|
||||
overheadBytes: MLX_PREFIX_CACHE_BYTES + 500_000_000,
|
||||
/**
|
||||
* The first measured row's 5 GB. This run only gives a floor: the footprint's lifetime peak
|
||||
* stood 3.0 to 3.3 GB above what was held at the end, and a larger transient during the
|
||||
* earlier, longer prompts would not show in that figure.
|
||||
*/
|
||||
peakExtraBytes: 5_000_000_000,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* The catalogue that ships with Codeman. Never read directly outside this file and its test:
|
||||
* callers use `getLocalModelCatalog()`, which validates it first.
|
||||
*/
|
||||
export const STOCK_LOCAL_MODEL_CATALOG: LocalModelCatalog = {
|
||||
schema: 1,
|
||||
updated: '2026-11-10',
|
||||
updated: '2026-11-12',
|
||||
// The oldest macOS the model runtime supports.
|
||||
minMacosMajor: 14,
|
||||
// Ordered by rank. The higher rank wins among models that fit and whose speed is graded
|
||||
@@ -537,11 +586,43 @@ export const STOCK_LOCAL_MODEL_CATALOG: LocalModelCatalog = {
|
||||
figures: 'estimated',
|
||||
contexts: [131072, 65536],
|
||||
rank: 5,
|
||||
// Not measured: the 2.95 of Qwen3.8 27B, a dense model whose weights are the same size on
|
||||
// llama.cpp (16.8 GB each without the projector).
|
||||
// The 2.95 of Qwen3.8 27B, a dense model whose weights are the same size on llama.cpp
|
||||
// (16.8 GB each without the projector). Left there on purpose after the one run on a Mac
|
||||
// (M5 Pro, 2026-11-12): the runtime alone wrote 14.5 to 15.2 tokens per second, 4.8 per
|
||||
// 100 GB/s, but an OpenCode worker given one line (through the skill's `sendmark`, which
|
||||
// adds its answer-file sentence) showed no answer after 7 minutes, twice.
|
||||
speedPer100Gbps: 2.95,
|
||||
tested: [],
|
||||
},
|
||||
{
|
||||
// The same model as the MLX build: about twice as fast, because the tag carries a draft
|
||||
// model (the runtime logs "Loaded draft model", acceptance 0.34 to 0.62) and its own
|
||||
// renderer and tool parser. On the MacBook Pro (Mac17,13, M5 Pro, 48 GB, 2026-11-12) it
|
||||
// wrote 30.2 tokens per second where the GGUF build wrote 15.2 (the same 300-token
|
||||
// request), answered a tool call in under 3 seconds, and finished an OpenCode turn on
|
||||
// a one-line prompt in 45 seconds. The GGUF build above had shown nothing after 7
|
||||
// minutes on a one-line task (not the same prompt: see that row). The price is
|
||||
// memory: what the MLX runner holds grows six times as fast per token (MEMORY in the
|
||||
// file header), so this build starts at 48 GB and the 32 and 36 GB Macs keep the row
|
||||
// above. Not installed through the window yet, and no agent session beyond that turn:
|
||||
// no `tested` entry.
|
||||
id: 'muse-glimmer:30b-mlx',
|
||||
label: 'Muse Glimmer 30B (MLX)',
|
||||
license: 'Apache-2.0',
|
||||
paramsB: 29.6,
|
||||
runner: 'mlx',
|
||||
// The layers of its manifest, the draft model's included.
|
||||
bytes: 19_053_621_992,
|
||||
...MUSE_MLX_MEASURED_MEMORY,
|
||||
figures: 'measured',
|
||||
contexts: [131072, 65536],
|
||||
rank: 6,
|
||||
// Measured beside Qwen3.6 35B-A3B on MLX, same Mac, same request (a 1,500-token answer):
|
||||
// 32.6 against 101.9 tokens per second, so 0.32 of that row's 16.9. Like that row's, on
|
||||
// the low side: on 307 GB/s it computes to 16.6.
|
||||
speedPer100Gbps: 5.4,
|
||||
tested: [],
|
||||
},
|
||||
{
|
||||
// Macs of 36 GB on a slower chip: the model of the tested pair, as a GGUF build whose
|
||||
// memory does not grow after it loaded. With its multi-token-prediction layer.
|
||||
@@ -562,7 +643,7 @@ export const STOCK_LOCAL_MODEL_CATALOG: LocalModelCatalog = {
|
||||
peakExtraBytes: 0,
|
||||
figures: 'estimated',
|
||||
contexts: [262144, 131072, 65536],
|
||||
rank: 6,
|
||||
rank: 7,
|
||||
// Measured: 54.5 tokens per second on 400 GB/s (llama.cpp, without prediction).
|
||||
speedPer100Gbps: 13.6,
|
||||
tested: [],
|
||||
@@ -580,7 +661,7 @@ export const STOCK_LOCAL_MODEL_CATALOG: LocalModelCatalog = {
|
||||
...MEASURED_MEMORY,
|
||||
figures: 'measured',
|
||||
contexts: [131072, 65536],
|
||||
rank: 7,
|
||||
rank: 8,
|
||||
// Measured: 67.8 tokens per second on 400 GB/s with MLX. The one Mac we tested ran it at
|
||||
// 67.7 on 307 GB/s, so on other chips the estimate is on the low side.
|
||||
speedPer100Gbps: 16.9,
|
||||
@@ -605,7 +686,7 @@ export const STOCK_LOCAL_MODEL_CATALOG: LocalModelCatalog = {
|
||||
peakExtraBytes: 0,
|
||||
figures: 'estimated',
|
||||
contexts: [262144, 131072, 65536],
|
||||
rank: 8,
|
||||
rank: 9,
|
||||
// Not measured: the 2.95 of the row below scaled by file size.
|
||||
speedPer100Gbps: 1.7,
|
||||
tested: [],
|
||||
@@ -629,7 +710,7 @@ export const STOCK_LOCAL_MODEL_CATALOG: LocalModelCatalog = {
|
||||
peakExtraBytes: 0,
|
||||
figures: 'estimated',
|
||||
contexts: [262144, 131072, 65536],
|
||||
rank: 9,
|
||||
rank: 10,
|
||||
// Measured: 11.8 tokens per second on 400 GB/s (llama.cpp, Q4_K_M, without prediction).
|
||||
// This build predicts several tokens at a time, so it is faster than this figure says.
|
||||
speedPer100Gbps: 2.95,
|
||||
@@ -653,7 +734,7 @@ export const STOCK_LOCAL_MODEL_CATALOG: LocalModelCatalog = {
|
||||
peakExtraBytes: MEASURED_MEMORY.peakExtraBytes,
|
||||
figures: 'estimated',
|
||||
contexts: [262144, 131072],
|
||||
rank: 10,
|
||||
rank: 11,
|
||||
// Not measured: the 16.9 of Qwen3.6 35B-A3B on MLX x 3/10, its active parameters
|
||||
// against these, rounded down.
|
||||
speedPer100Gbps: 5,
|
||||
|
||||
@@ -7,8 +7,6 @@
|
||||
import type { ConcurrencyPolicy, InputMode, PromptMode, ScheduleType } from '../types/cron.js';
|
||||
import type { SessionMode } from '../types/session.js';
|
||||
|
||||
export type { CronJob, CronJobRun, CronJobRunStatus, TriggerType } from '../types/cron.js';
|
||||
|
||||
export interface CronJobInput {
|
||||
name: string;
|
||||
agentType: SessionMode;
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
* - `applyWorkspaceHooks(workspace, install?)` — the ONE install-vs-refresh decision
|
||||
* point every claude-session create path routes through (see its doc comment)
|
||||
* - `ensureCodemanHooks(casePath)` — safely installs/updates hooks for a managed case
|
||||
* - `updateCaseEnvVars(casePath, envVars)` — merges env vars into settings
|
||||
*
|
||||
* Hook events generated: `idle_prompt`, `permission_prompt`, `elicitation_dialog`,
|
||||
* `elicitation_complete`, `elicitation_response`, `stop`, `teammate_idle`,
|
||||
@@ -632,37 +631,6 @@ export async function stripCaseEnvKeys(casePath: string, keysToRemove: readonly
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates env vars in .claude/settings.local.json for the given case path.
|
||||
* Merges with existing env field; removes vars set to empty string.
|
||||
*/
|
||||
export async function updateCaseEnvVars(casePath: string, envVars: Record<string, string>): Promise<void> {
|
||||
await withSafeSettingsWrite(casePath, 'env vars', async (claudeDir, settingsPath) => {
|
||||
if (!(await pathExistsForWrite(claudeDir))) {
|
||||
await mkdir(claudeDir, { recursive: true });
|
||||
}
|
||||
|
||||
let existing: Record<string, unknown> = {};
|
||||
try {
|
||||
existing = JSON.parse(await readFile(settingsPath, 'utf-8'));
|
||||
} catch {
|
||||
existing = {};
|
||||
}
|
||||
|
||||
const currentEnv = (existing.env as Record<string, string>) || {};
|
||||
for (const [key, value] of Object.entries(envVars)) {
|
||||
if (value) {
|
||||
currentEnv[key] = value;
|
||||
} else {
|
||||
delete currentEnv[key];
|
||||
}
|
||||
}
|
||||
existing.env = currentEnv;
|
||||
|
||||
await writeFile(settingsPath, JSON.stringify(existing, null, 2) + '\n');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the `model` field in .claude/settings.local.json for the given case path.
|
||||
* Pass a non-empty string to set, or empty/null to remove.
|
||||
|
||||
@@ -112,7 +112,7 @@ export const LIMITED_BELOW_PARAMS_B = 12;
|
||||
export const DISK_HEADROOM_BYTES = 10 * GIB;
|
||||
/**
|
||||
* How many other models are listed under the pick, at most. Above what the stock catalogue
|
||||
* holds (10 models: 9 beside the pick), so a Mac is shown every model that fits it and the
|
||||
* holds (11 models: 10 beside the pick), so a Mac is shown every model that fits it and the
|
||||
* install accepts every one of them. Still a bound: test/local-model-catalog.test.ts fails for
|
||||
* a catalogue that outgrows it, so nothing drops out of the list unseen.
|
||||
*/
|
||||
|
||||
@@ -8,4 +8,4 @@
|
||||
export { RESEARCH_AGENT_PROMPT } from './research-agent.js';
|
||||
export { PLANNER_PROMPT } from './planner.js';
|
||||
export { PHASE_EXECUTION_PROMPT, TEAM_LEAD_PROMPT, REPLAN_PROMPT, SINGLE_TASK_PROMPT } from './orchestrator.js';
|
||||
export { RALPH_STATUS_CONTRACT, buildRalphLoopPrompt, type RalphLoopPromptOptions } from './ralph.js';
|
||||
export { buildRalphLoopPrompt } from './ralph.js';
|
||||
@@ -882,13 +882,6 @@ export class RalphTracker extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a phrase matches any valid completion phrase (primary or alternate).
|
||||
*/
|
||||
isValidCompletionPhrase(phrase: string): boolean {
|
||||
return this.findMatchingCompletionPhrase(phrase) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find which completion phrase (primary or alternate) matches the given phrase.
|
||||
*/
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
* - `DetectionStatus`, `ActiveTimerInfo` — status types
|
||||
*
|
||||
* Key methods: `start()`, `stop()`, `getStatus()`, `getConfig()`,
|
||||
* `getDetectionStatus()`, `getActiveTimers()`, `getAggregateMetrics()`,
|
||||
* `getDetectionStatus()`, `getActiveTimers()`,
|
||||
* `getTimingHistory()`, `getHealthScore()`
|
||||
*
|
||||
* @dependencies session (PTY output), ai-idle-checker, ai-plan-checker,
|
||||
@@ -76,14 +76,7 @@ import {
|
||||
AI_PLAN_CHECK_TIMEOUT_MS,
|
||||
AI_PLAN_CHECK_COOLDOWN_MS,
|
||||
} from './config/ai-defaults.js';
|
||||
import {
|
||||
getErrorMessage,
|
||||
type RespawnCycleMetrics,
|
||||
type RespawnAggregateMetrics,
|
||||
type RalphLoopHealthScore,
|
||||
type TimingHistory,
|
||||
type CycleOutcome,
|
||||
} from './types.js';
|
||||
import { getErrorMessage, type RalphLoopHealthScore, type TimingHistory, type CycleOutcome } from './types.js';
|
||||
|
||||
// ========== Constants ==========
|
||||
|
||||
@@ -1903,13 +1896,6 @@ export class RespawnController extends EventEmitter {
|
||||
this.emit('actionLog', action);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get recent action log entries.
|
||||
*/
|
||||
getRecentActions(): ActionLogEntry[] {
|
||||
return [...this.recentActions];
|
||||
}
|
||||
|
||||
// ========== Multi-Layer Detection Methods ==========
|
||||
// Pattern detection delegated to ./respawn-patterns.js (isCompletionMessage, hasWorkingPattern, extractTokenCount)
|
||||
|
||||
@@ -3178,23 +3164,6 @@ export class RespawnController extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get aggregate metrics for monitoring.
|
||||
* @returns Copy of aggregate metrics
|
||||
*/
|
||||
getAggregateMetrics(): RespawnAggregateMetrics {
|
||||
return this.cycleMetrics.getAggregate();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get recent cycle metrics for analysis.
|
||||
* @param limit - Maximum number of metrics to return (default: 20)
|
||||
* @returns Recent cycle metrics, newest first
|
||||
*/
|
||||
getRecentCycleMetrics(limit: number = 20): RespawnCycleMetrics[] {
|
||||
return this.cycleMetrics.getRecent(limit);
|
||||
}
|
||||
|
||||
// ========== P2-005: Health Score (delegated to respawn-health.ts) ==========
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
/**
|
||||
* @fileoverview LRU cache for task descriptions parsed from terminal output.
|
||||
*
|
||||
* Stores descriptions extracted from Claude Code's Task tool invocations
|
||||
* (e.g., "Explore(Check files)") keyed by timestamp. Used to correlate
|
||||
* with SubagentWatcher discoveries for better window titles.
|
||||
*
|
||||
* @module session-task-cache
|
||||
*/
|
||||
|
||||
import { LRUMap } from './utils/lru-map.js';
|
||||
|
||||
/** Default maximum number of task descriptions to keep */
|
||||
const DEFAULT_MAX_SIZE = 100;
|
||||
|
||||
/** Default maximum age for task descriptions (30 seconds) */
|
||||
const DEFAULT_MAX_AGE_MS = 30_000;
|
||||
|
||||
/**
|
||||
* LRU cache for task descriptions parsed from terminal output.
|
||||
*
|
||||
* Descriptions are keyed by the timestamp when they were parsed.
|
||||
* Old entries are automatically cleaned up based on maxAgeMs.
|
||||
* Size is bounded by the underlying LRUMap.
|
||||
*/
|
||||
export class SessionTaskCache {
|
||||
private readonly cache: LRUMap<number, string>;
|
||||
private readonly maxAgeMs: number;
|
||||
|
||||
constructor(maxSize: number = DEFAULT_MAX_SIZE, maxAgeMs: number = DEFAULT_MAX_AGE_MS) {
|
||||
this.cache = new LRUMap<number, string>({ maxSize });
|
||||
this.maxAgeMs = maxAgeMs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a task description at the given timestamp.
|
||||
*/
|
||||
add(timestamp: number, description: string): void {
|
||||
this.cache.set(timestamp, description);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove task descriptions older than maxAgeMs.
|
||||
* LRUMap maintains insertion order, so we can break early
|
||||
* once we find a non-expired entry.
|
||||
*/
|
||||
private cleanupOld(): void {
|
||||
const cutoff = Date.now() - this.maxAgeMs;
|
||||
for (const timestamp of this.cache.keysInOrder()) {
|
||||
if (timestamp < cutoff) {
|
||||
this.cache.delete(timestamp);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all recent task descriptions sorted by timestamp (most recent first).
|
||||
*/
|
||||
getAll(): Array<{ timestamp: number; description: string }> {
|
||||
this.cleanupOld();
|
||||
const results: Array<{ timestamp: number; description: string }> = [];
|
||||
for (const [timestamp, description] of this.cache) {
|
||||
results.push({ timestamp, description });
|
||||
}
|
||||
return results.sort((a, b) => b.timestamp - a.timestamp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a task description that was parsed close to a given timestamp.
|
||||
* Used to correlate with SubagentWatcher discoveries.
|
||||
*
|
||||
* @param subagentStartTime - The timestamp when the subagent was discovered
|
||||
* @param maxAgeMs - Maximum age difference to consider (default 10 seconds)
|
||||
* @returns The matching description or undefined
|
||||
*/
|
||||
findNear(subagentStartTime: number, maxAgeMs: number = 10000): string | undefined {
|
||||
this.cleanupOld();
|
||||
|
||||
let bestMatch: { timestamp: number; description: string } | undefined;
|
||||
let bestDiff = Infinity;
|
||||
|
||||
for (const [timestamp, description] of this.cache) {
|
||||
const diff = Math.abs(subagentStartTime - timestamp);
|
||||
if (diff < maxAgeMs && diff < bestDiff) {
|
||||
bestMatch = { timestamp, description };
|
||||
bestDiff = diff;
|
||||
}
|
||||
}
|
||||
|
||||
return bestMatch?.description;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all cached descriptions.
|
||||
*/
|
||||
clear(): void {
|
||||
this.cache.clear();
|
||||
}
|
||||
}
|
||||
+3
-127
@@ -17,7 +17,7 @@
|
||||
*
|
||||
* Key methods: `runPrompt()`, `startInteractive()`, `startShell()`,
|
||||
* `writeViaMux()`, `toState()`, `stop()`, `resize()`, `isIdle()`,
|
||||
* `setAutoCompact()`, `findTaskDescriptionNear()`, `getTerminalBuffer()`
|
||||
* `setAutoCompact()`, `getTerminalBuffer()`
|
||||
*
|
||||
* @dependencies session-cli-builder (args/env), session-auto-ops (auto-compact/clear),
|
||||
* ralph-tracker (todo/completion parsing), bash-tool-parser (tool invocation tracking),
|
||||
@@ -117,7 +117,6 @@ import {
|
||||
SPINNER_PATTERN,
|
||||
CLAUDE_WORKING_LINE_PATTERN,
|
||||
MAX_SESSION_TOKENS,
|
||||
execPattern,
|
||||
getClaudeCliVersion,
|
||||
getClaudeBinaryPath,
|
||||
spawnPtyWithHelperRepair,
|
||||
@@ -156,7 +155,6 @@ import {
|
||||
} from './session-cli-builder.js';
|
||||
import { SessionAutoOps, type ContextReport } from './session-auto-ops.js';
|
||||
import { detectUsageLimitPause } from './usage-limit-patterns.js';
|
||||
import { SessionTaskCache } from './session-task-cache.js';
|
||||
import { InteractivePtyExitBreaker } from './session-pty-exit-breaker.js';
|
||||
import { isGeneratedSessionName, SubmittedPromptTracker } from './session-auto-name.js';
|
||||
import { parseTerminalAttachmentRequests } from './attachment-magic.js';
|
||||
@@ -222,12 +220,6 @@ const MAX_CLAUDE_SESSION_CHAIN = 32;
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const FOCUS_ESCAPE_FILTER = /\x1b\[\?1004[hl]|\x1b\[[IO]/g;
|
||||
|
||||
// Pattern to match Task tool invocations in terminal output
|
||||
// Matches: "Explore(Description)", "Task(Description)", "Bash(Description)", etc.
|
||||
// The prefix characters vary (●, ·, ✶, etc.) so we don't require them
|
||||
// We look for the tool name followed by (description)
|
||||
const TASK_TOOL_PATTERN = /\b(Explore|Task|Bash|Plan|general-purpose)\(([^)]+)\)/g;
|
||||
|
||||
// Pre-compiled patterns for hot paths (avoid regex compilation per call)
|
||||
/** Pattern to strip leading ANSI escapes and whitespace from terminal buffer */
|
||||
// eslint-disable-next-line no-control-regex
|
||||
@@ -235,8 +227,6 @@ const LEADING_ANSI_WHITESPACE_PATTERN = /^(\x1b\[\??[\d;]*[A-Za-z]|[\s\r\n])+/;
|
||||
/** Pattern to match Ctrl+L (form feed) characters */
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const CTRL_L_PATTERN = /\x0c/g;
|
||||
/** Pattern to split by newlines (CR or LF) */
|
||||
const NEWLINE_SPLIT_PATTERN = /\r?\n/;
|
||||
|
||||
/**
|
||||
* True for external-CLI run modes (non-Claude) that use their own TUI and output format:
|
||||
@@ -574,9 +564,6 @@ export class Session extends EventEmitter {
|
||||
readonly createdAt: number;
|
||||
readonly mode: SessionMode;
|
||||
|
||||
// Task description cache (extracted to SessionTaskCache)
|
||||
private _taskCache = new SessionTaskCache();
|
||||
|
||||
private _name: string;
|
||||
private _nameSource: SessionNameSource;
|
||||
/** `pinCliSessionName` as of the last spawn (see {@link _refreshCliNamePin}). */
|
||||
@@ -834,10 +821,6 @@ export class Session extends EventEmitter {
|
||||
// Ralph tracking (Ralph Wiggum loops and todo lists inside Claude Code)
|
||||
private _ralphTracker: RalphTracker;
|
||||
|
||||
// Agent tree tracking
|
||||
private _parentAgentId: string | null = null;
|
||||
private _childAgentIds: string[] = [];
|
||||
|
||||
// Bounded dedup set for terminal attachment magic-links already requested.
|
||||
private _attachmentMagicSeen = new Set<string>();
|
||||
private _attachmentHistory: SessionAttachmentHistoryItem[] = [];
|
||||
@@ -961,9 +944,7 @@ export class Session extends EventEmitter {
|
||||
toolsUpdate: (tools: ActiveBashTool[]) => void;
|
||||
} | null = null;
|
||||
|
||||
// Task descriptions parsed from terminal output — delegated to SessionTaskCache
|
||||
|
||||
// Throttle expensive PTY processing (Ralph, bash parser, task descriptions)
|
||||
// Throttle expensive PTY processing (Ralph, bash parser)
|
||||
// Accumulates clean data between processing windows to avoid running regex on every chunk
|
||||
private _lastExpensiveProcessTime: number = 0;
|
||||
private _pendingCleanData: string = '';
|
||||
@@ -1999,14 +1980,6 @@ export class Session extends EventEmitter {
|
||||
return this._taskTracker;
|
||||
}
|
||||
|
||||
get runningTaskCount(): number {
|
||||
return this._taskTracker.getRunningCount();
|
||||
}
|
||||
|
||||
get taskTree(): BackgroundTask[] {
|
||||
return this._taskTracker.getTaskTree();
|
||||
}
|
||||
|
||||
get taskStats(): { total: number; running: number; completed: number; failed: number } {
|
||||
return this._taskTracker.getStats();
|
||||
}
|
||||
@@ -2028,38 +2001,10 @@ export class Session extends EventEmitter {
|
||||
return this._ralphTracker.getTodoStats();
|
||||
}
|
||||
|
||||
// Bash tool tracking getters
|
||||
get bashToolParser(): BashToolParser {
|
||||
return this._bashToolParser;
|
||||
}
|
||||
|
||||
get activeTools(): ActiveBashTool[] {
|
||||
return this._bashToolParser.activeTools;
|
||||
}
|
||||
|
||||
get parentAgentId(): string | null {
|
||||
return this._parentAgentId;
|
||||
}
|
||||
|
||||
set parentAgentId(value: string | null) {
|
||||
this._parentAgentId = value;
|
||||
}
|
||||
|
||||
get childAgentIds(): string[] {
|
||||
return [...this._childAgentIds];
|
||||
}
|
||||
|
||||
addChildAgentId(agentId: string): void {
|
||||
if (!this._childAgentIds.includes(agentId)) {
|
||||
this._childAgentIds.push(agentId);
|
||||
}
|
||||
}
|
||||
|
||||
removeChildAgentId(agentId: string): void {
|
||||
const idx = this._childAgentIds.indexOf(agentId);
|
||||
if (idx >= 0) this._childAgentIds.splice(idx, 1);
|
||||
}
|
||||
|
||||
// Nice priority config getters and setters
|
||||
get niceConfig(): NiceConfig {
|
||||
return { ...this._niceConfig };
|
||||
@@ -2519,8 +2464,6 @@ export class Session extends EventEmitter {
|
||||
ralphEnabled: this._ralphTracker.enabled,
|
||||
ralphAutoEnableDisabled: this._ralphTracker.autoEnableDisabled || undefined,
|
||||
ralphCompletionPhrase: this._ralphTracker.loopState.completionPhrase || undefined,
|
||||
parentAgentId: this._parentAgentId || undefined,
|
||||
childAgentIds: this._childAgentIds.length > 0 ? this._childAgentIds : undefined,
|
||||
niceEnabled: this._niceConfig.enabled,
|
||||
niceValue: this._niceConfig.niceValue,
|
||||
color: this._color,
|
||||
@@ -4411,7 +4354,7 @@ export class Session extends EventEmitter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Process expensive parsers (ANSI strip, Ralph, bash tool, token, CLI info, task descriptions).
|
||||
* Process expensive parsers (ANSI strip, Ralph, bash tool, token, CLI info).
|
||||
* Called on a throttled schedule (every EXPENSIVE_PROCESS_INTERVAL_MS) instead of on every
|
||||
* PTY data chunk. Receives accumulated raw data to process in one batch.
|
||||
*/
|
||||
@@ -4464,11 +4407,6 @@ export class Session extends EventEmitter {
|
||||
this.parseClaudeCodeInfo(getCleanData());
|
||||
}
|
||||
|
||||
// Parse task descriptions from terminal output (e.g., "Explore(Check files)")
|
||||
if (rawData.includes('(') && rawData.includes(')')) {
|
||||
this.parseTaskDescriptionsFromTerminalData(getCleanData());
|
||||
}
|
||||
|
||||
// Legacy gerunds, Claude-only. The status-line pattern above already ran for every
|
||||
// CLI that declares one, so this adds only the older wording. Current Claude
|
||||
// randomizes the word ("Actualizing…", "Finagling…"), so these catch a fraction of
|
||||
@@ -4970,67 +4908,10 @@ export class Session extends EventEmitter {
|
||||
} else if (trimmed) {
|
||||
this._textOutput.append(line + '\n');
|
||||
}
|
||||
|
||||
// Parse task descriptions from terminal output (e.g., "Explore(Description)")
|
||||
// This captures the short description from Claude Code's Task tool output
|
||||
// Use direct method since cleanLine is already ANSI-stripped (line 1460)
|
||||
this.parseTaskDescriptionsDirect(cleanLine);
|
||||
}
|
||||
// Note: BufferAccumulator auto-trims when max size exceeded
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse task descriptions from terminal data (may contain multiple lines).
|
||||
* Called from interactive mode's onData handler with ANSI-stripped data.
|
||||
* @param cleanData - Terminal data with ANSI codes already stripped
|
||||
*/
|
||||
private parseTaskDescriptionsFromTerminalData(cleanData: string): void {
|
||||
// Quick pre-check: skip if no parentheses present
|
||||
if (!cleanData.includes('(') || !cleanData.includes(')')) return;
|
||||
|
||||
// Split by newlines and process each line (data already ANSI-stripped)
|
||||
const lines = cleanData.split(NEWLINE_SPLIT_PATTERN);
|
||||
for (const line of lines) {
|
||||
this.parseTaskDescriptionsDirect(line);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse task descriptions from a pre-cleaned line (no ANSI codes).
|
||||
* Used by both processOutput() and parseTaskDescriptionsFromTerminalData().
|
||||
*/
|
||||
private parseTaskDescriptionsDirect(cleanLine: string): void {
|
||||
// Quick pre-check: skip expensive regex if no common tool patterns present
|
||||
if (!cleanLine.includes('(') || !cleanLine.includes(')')) return;
|
||||
|
||||
execPattern(TASK_TOOL_PATTERN, cleanLine, (match) => {
|
||||
const description = match[2].trim();
|
||||
if (description && description.length > 0) {
|
||||
this._taskCache.add(Date.now(), description);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get recent task descriptions parsed from terminal output.
|
||||
* Returns descriptions sorted by timestamp (most recent first).
|
||||
*/
|
||||
getRecentTaskDescriptions(): Array<{ timestamp: number; description: string }> {
|
||||
return this._taskCache.getAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a task description that was parsed close to a given timestamp.
|
||||
* Used to correlate with SubagentWatcher discoveries.
|
||||
*
|
||||
* @param subagentStartTime - The timestamp when the subagent was discovered
|
||||
* @param maxAgeMs - Maximum age difference to consider (default 10 seconds)
|
||||
* @returns The matching description or undefined
|
||||
*/
|
||||
findTaskDescriptionNear(subagentStartTime: number, maxAgeMs: number = 10000): string | undefined {
|
||||
return this._taskCache.findNear(subagentStartTime, maxAgeMs);
|
||||
}
|
||||
|
||||
// Parse token count from Claude's status line in interactive mode
|
||||
// Matches patterns like "123.4k tokens", "5234 tokens", "1.2M tokens"
|
||||
//
|
||||
@@ -5981,10 +5862,6 @@ export class Session extends EventEmitter {
|
||||
this._status = killMux ? 'stopped' : 'idle';
|
||||
this._currentTaskId = null;
|
||||
|
||||
// Clear task description cache and agent tree to prevent memory leak
|
||||
this._taskCache.clear();
|
||||
this._childAgentIds = [];
|
||||
|
||||
// Kill the associated mux session if requested
|
||||
if (killMux && this._mux) {
|
||||
// Try to kill mux session even if _muxSession is not set (e.g., restored sessions)
|
||||
@@ -6038,6 +5915,5 @@ export class Session extends EventEmitter {
|
||||
this._messages = [];
|
||||
this._taskTracker.clear();
|
||||
this._ralphTracker.clear();
|
||||
this._taskCache.clear();
|
||||
}
|
||||
}
|
||||
@@ -429,29 +429,6 @@ export class StateStore {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to recover state from backup file.
|
||||
* Call this if main state file is corrupt.
|
||||
*/
|
||||
recoverFromBackup(): boolean {
|
||||
const backupPath = this.filePath + '.bak';
|
||||
try {
|
||||
if (existsSync(backupPath)) {
|
||||
const backupContent = readFileSync(backupPath, 'utf-8');
|
||||
const parsed = JSON.parse(backupContent) as Partial<AppState>;
|
||||
this.state = this._mergeWithInitialState(parsed);
|
||||
console.log('[StateStore] Successfully recovered state from backup');
|
||||
// Reset circuit breaker after successful recovery
|
||||
this.circuitBreakerOpen = false;
|
||||
this.consecutiveSaveFailures = 0;
|
||||
return true;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[StateStore] Failed to recover from backup:', err);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset the circuit breaker (for manual intervention).
|
||||
*/
|
||||
|
||||
+1
-12
@@ -15,7 +15,7 @@ import { join } from 'node:path';
|
||||
|
||||
import { watch as chokidarWatch, type FSWatcher as ChokidarWatcher } from 'chokidar';
|
||||
|
||||
import type { TeamConfig, TeamMember, TeamTask, InboxMessage } from './types.js';
|
||||
import 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';
|
||||
|
||||
@@ -175,17 +175,6 @@ export class TeamWatcher extends EventEmitter {
|
||||
return activeTasks > 0;
|
||||
}
|
||||
|
||||
/** Get teammates that have real tmux panes (not in-process) */
|
||||
getTmuxPaneTeammates(teamName: string): Array<TeamMember & { tmuxPaneId: string }> {
|
||||
const team = this.teams.get(teamName);
|
||||
if (!team) return [];
|
||||
|
||||
return team.members.filter(
|
||||
(m): m is TeamMember & { tmuxPaneId: string } =>
|
||||
m.agentType !== 'team-lead' && !!m.tmuxPaneId && m.tmuxPaneId !== 'in-process'
|
||||
);
|
||||
}
|
||||
|
||||
/** Get count of active teammates for a session */
|
||||
getActiveTeammateCount(sessionId: string): number {
|
||||
const team = this.getTeamForSession(sessionId);
|
||||
|
||||
@@ -4451,21 +4451,6 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync mouse mode based on pane count: enable if split (>1 pane), disable if single.
|
||||
* Called by TeamWatcher when teammates spawn/despawn panes.
|
||||
* Uses `tmux list-panes` for bulletproof detection — counts actual panes, not config.
|
||||
*/
|
||||
async syncMouseMode(muxName: string): Promise<boolean> {
|
||||
if (IS_TEST_MODE) return true;
|
||||
const panes = await this.listPanes(muxName);
|
||||
if (panes.length > 1) {
|
||||
return this.enableMouseMode(muxName);
|
||||
} else {
|
||||
return this.disableMouseMode(muxName);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List all panes in a tmux session.
|
||||
* Returns structured info for each pane.
|
||||
@@ -4782,67 +4767,6 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start piping pane output to a file using tmux pipe-pane.
|
||||
* Only pipes output direction (-O) to avoid echoing input.
|
||||
*/
|
||||
startPipePane(muxName: string, paneTarget: string, outputFile: string): boolean {
|
||||
if (IS_TEST_MODE) return true;
|
||||
if (!isValidMuxName(muxName)) {
|
||||
console.error('[TmuxManager] Invalid session name in startPipePane:', muxName);
|
||||
return false;
|
||||
}
|
||||
if (!SAFE_PANE_TARGET_PATTERN.test(paneTarget)) {
|
||||
console.error('[TmuxManager] Invalid pane target:', paneTarget);
|
||||
return false;
|
||||
}
|
||||
if (!isValidPath(outputFile)) {
|
||||
console.error('[TmuxManager] Invalid output file path:', outputFile);
|
||||
return false;
|
||||
}
|
||||
|
||||
const target = paneTarget.startsWith('%') ? `${muxName}.${paneTarget}` : `${muxName}.%${paneTarget}`;
|
||||
|
||||
try {
|
||||
execSync(`${this.tmux()} pipe-pane -O -t ${shellescape(target)} ${shellescape('cat >> ' + outputFile)}`, {
|
||||
encoding: 'utf-8',
|
||||
timeout: EXEC_TIMEOUT_MS,
|
||||
});
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error('[TmuxManager] Failed to start pipe-pane:', err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop piping pane output (calling pipe-pane with no command stops piping).
|
||||
*/
|
||||
stopPipePane(muxName: string, paneTarget: string): boolean {
|
||||
if (IS_TEST_MODE) return true;
|
||||
if (!isValidMuxName(muxName)) {
|
||||
console.error('[TmuxManager] Invalid session name in stopPipePane:', muxName);
|
||||
return false;
|
||||
}
|
||||
if (!SAFE_PANE_TARGET_PATTERN.test(paneTarget)) {
|
||||
console.error('[TmuxManager] Invalid pane target:', paneTarget);
|
||||
return false;
|
||||
}
|
||||
|
||||
const target = paneTarget.startsWith('%') ? `${muxName}.${paneTarget}` : `${muxName}.%${paneTarget}`;
|
||||
|
||||
try {
|
||||
execSync(`${this.tmux()} pipe-pane -t ${shellescape(target)}`, {
|
||||
encoding: 'utf-8',
|
||||
timeout: EXEC_TIMEOUT_MS,
|
||||
});
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error('[TmuxManager] Failed to stop pipe-pane:', err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
getAttachCommand(): string {
|
||||
return 'tmux';
|
||||
}
|
||||
|
||||
@@ -29,20 +29,6 @@ import type { SessionMode } from './session.js';
|
||||
/** Where a foreign tmux server lives. Mirrors Codeman's own three locations. */
|
||||
export type ForeignTmuxLocationKind = 'local' | 'docker' | 'remote';
|
||||
|
||||
/**
|
||||
* A location to scan. `hostId` refers to the saved docker-host / remote-host
|
||||
* registry entry, so the transport can be rebuilt without trusting the browser.
|
||||
*/
|
||||
export interface ForeignTmuxLocation {
|
||||
kind: ForeignTmuxLocationKind;
|
||||
/** Registry id (`docker-hosts.json` / `remote-hosts.json`). Absent for local. */
|
||||
hostId?: string;
|
||||
/** Display label for the UI. Absent for local. */
|
||||
label?: string;
|
||||
/** Container to `docker exec` into (`kind === 'docker'`). */
|
||||
containerName?: string;
|
||||
}
|
||||
|
||||
/** One pane row from the probe script, after parsing. */
|
||||
export interface ForeignPaneProbe {
|
||||
socketPath: string;
|
||||
|
||||
@@ -698,9 +698,6 @@ export interface LocalModelRefusal {
|
||||
message: LocalModelInstallMessage;
|
||||
}
|
||||
|
||||
/** What every verb answers on success: the view after the verb. */
|
||||
export type LocalModelVerbAnswer = LocalModelInstallView;
|
||||
|
||||
/**
|
||||
* Why a verb was refused with 409.
|
||||
* - `job-running`: a job is running (a second install, a resume, a remove or a runtime action).
|
||||
|
||||
@@ -1103,10 +1103,6 @@ export interface SessionState {
|
||||
ralphAutoEnableDisabled?: boolean;
|
||||
/** Ralph completion phrase (if set) */
|
||||
ralphCompletionPhrase?: string;
|
||||
/** Parent agent ID if this session is a spawned agent */
|
||||
parentAgentId?: string;
|
||||
/** Child agent IDs spawned by this session */
|
||||
childAgentIds?: string[];
|
||||
/** Nice priority enabled */
|
||||
niceEnabled?: boolean;
|
||||
/** Nice value (-20 to 19) */
|
||||
|
||||
@@ -9,11 +9,7 @@
|
||||
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import {
|
||||
createCliExecutableResolver,
|
||||
formatCliNotFoundMessage,
|
||||
type CliResolverHost,
|
||||
} from './cli-executable-resolver.js';
|
||||
import { createCliExecutableResolver, type CliResolverHost } from './cli-executable-resolver.js';
|
||||
|
||||
/** Common directories where the Antigravity CLI binary may be installed */
|
||||
/**
|
||||
@@ -23,9 +19,6 @@ import {
|
||||
*/
|
||||
const ANTIGRAVITY_SEARCH_DIRS = (): string[] => (getCli('antigravity')?.discovery.searchDirs ?? []).map(expandHome);
|
||||
|
||||
const ANTIGRAVITY_NOT_FOUND =
|
||||
'Antigravity CLI not found. Install with: curl -fsSL https://antigravity.google/cli/install.sh | bash';
|
||||
|
||||
function createAntigravityResolver(host?: CliResolverHost, now?: () => number) {
|
||||
return createCliExecutableResolver({ binary: 'agy', searchDirs: ANTIGRAVITY_SEARCH_DIRS, now }, host);
|
||||
}
|
||||
@@ -53,7 +46,3 @@ export function resolveAntigravityDir(): string | null {
|
||||
export function isAntigravityAvailable(): boolean {
|
||||
return resolveAntigravityDir() !== null;
|
||||
}
|
||||
|
||||
export function getAntigravityNotFoundMessage(): string {
|
||||
return formatCliNotFoundMessage(ANTIGRAVITY_NOT_FOUND, antigravityResolver.diagnostics());
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import { execFileSync } from 'node:child_process';
|
||||
import { delimiter, join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
|
||||
import { createCliExecutableResolver, formatCliNotFoundMessage } from './cli-executable-resolver.js';
|
||||
import { createCliExecutableResolver } from './cli-executable-resolver.js';
|
||||
|
||||
/** Common directories where the Claude CLI binary may be installed */
|
||||
const CLAUDE_SEARCH_DIRS = [
|
||||
@@ -24,7 +24,6 @@ const CLAUDE_SEARCH_DIRS = [
|
||||
];
|
||||
|
||||
const claudeResolver = createCliExecutableResolver({ binary: 'claude', searchDirs: CLAUDE_SEARCH_DIRS });
|
||||
const CLAUDE_NOT_FOUND = 'Claude CLI not found. Install it with: curl -fsSL https://claude.ai/install.sh | bash';
|
||||
|
||||
/**
|
||||
* Returns true if the Claude CLI binary can be located (via `which` or one of
|
||||
@@ -46,10 +45,6 @@ export function findClaudeDir(): string | null {
|
||||
return claudeResolver.resolve()?.directory ?? null;
|
||||
}
|
||||
|
||||
export function getClaudeNotFoundMessage(): string {
|
||||
return formatCliNotFoundMessage(CLAUDE_NOT_FOUND, claudeResolver.diagnostics());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an absolute path to the `claude` binary, falling back to the bare
|
||||
* name `'claude'` when it cannot be located (so PATH resolution still gets a
|
||||
|
||||
@@ -82,26 +82,6 @@ export async function resolveCliLaunchError(mode: string, rawConfig?: Record<str
|
||||
return resolveCliBinDir(mode) === null ? missingCliMessage(mode) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is this CLI actually usable? For an ordinary CLI that is exactly "its binary resolved".
|
||||
* For a launcher it is that AND whatever its profile demands.
|
||||
*
|
||||
* ⚠️ A named-but-unimplemented profile fails CLOSED. In practice `schema.ts` rejects such an
|
||||
* entry at load time, so this is the second line of defence rather than the first — but the
|
||||
* direction matters: offering a Run that always fails is worse than reporting unavailable.
|
||||
*/
|
||||
export function isCliRunnable(id: string): boolean {
|
||||
const entry = getCli(id);
|
||||
if (!entry) return false;
|
||||
// No binary to find (`shell`): tmux-manager resolves the login shell in code.
|
||||
const resolved = entry.discovery.binaries.length === 0 ? true : resolveCliBinDir(id) !== null;
|
||||
const profileName = entry.discovery.launcherProfile;
|
||||
if (profileName === undefined) return resolved;
|
||||
const profile = LAUNCHER_PROFILES[profileName];
|
||||
if (!profile) return false;
|
||||
return resolved && profile.isRunnable();
|
||||
}
|
||||
|
||||
/**
|
||||
* The launcher's default target, for the `launcherDefaultTarget` engine value. Null for
|
||||
* every non-launcher CLI, which is what makes the corresponding launch arg drop out.
|
||||
|
||||
@@ -172,20 +172,6 @@ function createRegistryResolver(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an isolated resolver for `entry` around an injected probe, host and clock — the
|
||||
* test seam. Omitting `probe` keeps the ambient, VITEST-gated one, which is exactly what
|
||||
* the hermeticity tests exercise.
|
||||
*/
|
||||
export function createCliResolverForTest(
|
||||
entry: CliEntry,
|
||||
probe?: CliCandidateProbe,
|
||||
host?: CliResolverHost,
|
||||
now?: () => number
|
||||
): RegistryResolver {
|
||||
return createRegistryResolver(entry, probe ?? probeCliCandidate, host, now);
|
||||
}
|
||||
|
||||
/**
|
||||
* One memoized resolver per id, for the process lifetime — the same caching the per-CLI
|
||||
* modules already do for themselves, just keyed by id so generic code holding only a
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import { createCliExecutableResolver, formatCliNotFoundMessage } from './cli-executable-resolver.js';
|
||||
import { createCliExecutableResolver } from './cli-executable-resolver.js';
|
||||
import { parseCodexRateLimitsResponse, type StatusTelemetry } from '../usage-telemetry.js';
|
||||
|
||||
/**
|
||||
@@ -22,7 +22,6 @@ const CODEX_SEARCH_DIRS = (): string[] => (getCli('codex')?.discovery.searchDirs
|
||||
|
||||
const CODEX_BINARY = process.platform === 'win32' ? 'codex.exe' : 'codex';
|
||||
const codexResolver = createCliExecutableResolver({ binary: CODEX_BINARY, searchDirs: CODEX_SEARCH_DIRS });
|
||||
const CODEX_NOT_FOUND = 'Codex CLI not found. Install with: npm install -g @openai/codex';
|
||||
|
||||
/**
|
||||
* Finds the directory containing the `codex` binary.
|
||||
@@ -47,10 +46,6 @@ export function isCodexAvailable(): boolean {
|
||||
return resolveCodexDir() !== null;
|
||||
}
|
||||
|
||||
export function getCodexNotFoundMessage(): string {
|
||||
return formatCliNotFoundMessage(CODEX_NOT_FOUND, codexResolver.diagnostics());
|
||||
}
|
||||
|
||||
type CodexRateLimitsRequest = (binaryPath: string, clientVersion: string) => Promise<unknown>;
|
||||
|
||||
const APP_SERVER_TIMEOUT_MS = 10_000;
|
||||
|
||||
@@ -17,11 +17,7 @@ import { execFileSync } from 'node:child_process';
|
||||
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import {
|
||||
createCliExecutableResolver,
|
||||
formatCliNotFoundMessage,
|
||||
type CliResolverHost,
|
||||
} from './cli-executable-resolver.js';
|
||||
import { createCliExecutableResolver, type CliResolverHost } from './cli-executable-resolver.js';
|
||||
|
||||
/**
|
||||
* Directories probed after `which`, read from this CLI's registry entry so the spawn
|
||||
@@ -36,8 +32,6 @@ const COPILOT_SEARCH_DIRS = (): string[] => (getCli('copilot')?.discovery.search
|
||||
*/
|
||||
export const COPILOT_VERSION_REGEX = /GitHub Copilot CLI (\d+\.\d+\.\d+)/;
|
||||
|
||||
const COPILOT_NOT_FOUND = 'GitHub Copilot CLI not found. Install with: npm install -g @github/copilot';
|
||||
|
||||
/**
|
||||
* Run `copilot --version` on a candidate path and return the trimmed version when
|
||||
* it is the GitHub Copilot CLI. Returns null for anything else — a missing
|
||||
@@ -125,10 +119,6 @@ export function isCopilotAvailable(): boolean {
|
||||
return resolveCopilotDir() !== null;
|
||||
}
|
||||
|
||||
export function getCopilotNotFoundMessage(): string {
|
||||
return formatCliNotFoundMessage(COPILOT_NOT_FOUND, copilotResolver.diagnostics());
|
||||
}
|
||||
|
||||
/**
|
||||
* Version reported by the resolved `copilot` binary, or null when copilot is
|
||||
* unavailable. Surfaced through `GET /api/copilot/status` so a misresolution is
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
*/
|
||||
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
||||
import { readdirSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
|
||||
@@ -379,11 +379,6 @@ export function getDeepSeekCliVersion(): string | null {
|
||||
return deepSeekResolver.resolve()?.metadata ?? null;
|
||||
}
|
||||
|
||||
/** Does the named profile exist and can it drive a pane? */
|
||||
export function profileExists(name: string): boolean {
|
||||
return existsSync(join(resolveDshHome(), 'profiles', name, 'package.json'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a DeepSeek session cannot start, or null when it can.
|
||||
*
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import { createCliExecutableResolver, formatCliNotFoundMessage } from './cli-executable-resolver.js';
|
||||
import { createCliExecutableResolver } from './cli-executable-resolver.js';
|
||||
|
||||
/** Common directories where the Gemini CLI binary may be installed */
|
||||
/**
|
||||
@@ -20,7 +20,6 @@ import { createCliExecutableResolver, formatCliNotFoundMessage } from './cli-exe
|
||||
const GEMINI_SEARCH_DIRS = (): string[] => (getCli('gemini')?.discovery.searchDirs ?? []).map(expandHome);
|
||||
|
||||
const geminiResolver = createCliExecutableResolver({ binary: 'gemini', searchDirs: GEMINI_SEARCH_DIRS });
|
||||
const GEMINI_NOT_FOUND = 'Gemini CLI not found. Install with: npm install -g @google/gemini-cli';
|
||||
|
||||
/**
|
||||
* Finds the directory containing the `gemini` binary.
|
||||
@@ -38,7 +37,3 @@ export function resolveGeminiDir(): string | null {
|
||||
export function isGeminiAvailable(): boolean {
|
||||
return resolveGeminiDir() !== null;
|
||||
}
|
||||
|
||||
export function getGeminiNotFoundMessage(): string {
|
||||
return formatCliNotFoundMessage(GEMINI_NOT_FOUND, geminiResolver.diagnostics());
|
||||
}
|
||||
@@ -23,11 +23,7 @@ import { execFileSync } from 'node:child_process';
|
||||
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import {
|
||||
createCliExecutableResolver,
|
||||
formatCliNotFoundMessage,
|
||||
type CliResolverHost,
|
||||
} from './cli-executable-resolver.js';
|
||||
import { createCliExecutableResolver, type CliResolverHost } from './cli-executable-resolver.js';
|
||||
|
||||
/** Common directories where the Grok CLI binary may be installed */
|
||||
/**
|
||||
@@ -49,8 +45,6 @@ const GROK_SEARCH_DIRS = (): string[] => (getCli('grok')?.discovery.searchDirs ?
|
||||
*/
|
||||
export const GROK_VERSION_REGEX = /(?:^|\s)(\d+\.\d+\.\d+)/;
|
||||
|
||||
const GROK_NOT_FOUND = 'Grok CLI not found. Install with: curl -fsSL https://x.ai/cli/install.sh | bash';
|
||||
|
||||
/**
|
||||
* Run `grok --version` on a candidate path and return the version token when it
|
||||
* looks like the coding agent. Returns null for anything else: a missing
|
||||
@@ -137,10 +131,6 @@ export function isGrokAvailable(): boolean {
|
||||
return resolveGrokDir() !== null;
|
||||
}
|
||||
|
||||
export function getGrokNotFoundMessage(): string {
|
||||
return formatCliNotFoundMessage(GROK_NOT_FOUND, grokResolver.diagnostics());
|
||||
}
|
||||
|
||||
/**
|
||||
* Version reported by the resolved `grok` binary, or null when grok is
|
||||
* unavailable. Surfaced through `GET /api/grok/status` so a misresolution is
|
||||
|
||||
+3
-49
@@ -12,7 +12,7 @@ export { Debouncer, KeyedDebouncer } from './debouncer.js';
|
||||
export { startEventLoopMonitor } from './event-loop-monitor.js';
|
||||
export type { EventLoopMonitorHandle } from './event-loop-monitor.js';
|
||||
export { StaleExpirationMap } from './stale-expiration-map.js';
|
||||
export { isProcessRunning, waitForProcessesExit, PROCESS_EXIT_POLL_MS } from './process-exit-wait.js';
|
||||
export { waitForProcessesExit } from './process-exit-wait.js';
|
||||
export {
|
||||
ANSI_ESCAPE_PATTERN_FULL,
|
||||
ANSI_ESCAPE_PATTERN_SIMPLE,
|
||||
@@ -30,59 +30,13 @@ export { assertNever } from './type-safety.js';
|
||||
export { toSingleLine } from './single-line.js';
|
||||
export { wrapWithNice } from './nice-wrapper.js';
|
||||
export { resolveLocalShell, loginShellArgs } from './shell-resolver.js';
|
||||
export {
|
||||
findClaudeDir,
|
||||
getAugmentedPath,
|
||||
getClaudeCliVersion,
|
||||
getClaudeBinaryPath,
|
||||
getClaudeNotFoundMessage,
|
||||
} from './claude-cli-resolver.js';
|
||||
export { getAugmentedPath, getClaudeCliVersion, getClaudeBinaryPath } from './claude-cli-resolver.js';
|
||||
export { spawnPtyWithHelperRepair } from './node-pty-repair.js';
|
||||
export { resolveOpenCodeDir, getOpenCodeNotFoundMessage } from './opencode-cli-resolver.js';
|
||||
export {
|
||||
resolveCodexDir,
|
||||
resolveCodexBinaryPath,
|
||||
isCodexAvailable,
|
||||
getCodexNotFoundMessage,
|
||||
readCodexPlanUsage,
|
||||
} from './codex-cli-resolver.js';
|
||||
export { resolveGeminiDir, isGeminiAvailable, getGeminiNotFoundMessage } from './gemini-cli-resolver.js';
|
||||
export {
|
||||
resolveAntigravityDir,
|
||||
isAntigravityAvailable,
|
||||
getAntigravityNotFoundMessage,
|
||||
} from './antigravity-cli-resolver.js';
|
||||
export { resolvePiDir, isPiAvailable, getPiCliVersion, getPiNotFoundMessage } from './pi-cli-resolver.js';
|
||||
export { resolveGrokDir, isGrokAvailable, getGrokCliVersion, getGrokNotFoundMessage } from './grok-cli-resolver.js';
|
||||
export {
|
||||
resolveDeepSeekDir,
|
||||
isDeepSeekAvailable,
|
||||
isDeepSeekRunnable,
|
||||
getDeepSeekCliVersion,
|
||||
getDeepSeekNotFoundMessage,
|
||||
listDeepSeekProfiles,
|
||||
resolveDefaultDeepSeekProfile,
|
||||
isLaunchableProfile,
|
||||
resolveDshHome,
|
||||
profileExists,
|
||||
} from './deepseek-cli-resolver.js';
|
||||
export type { DeepSeekProfile, DeepSeekProfileKind } from './deepseek-cli-resolver.js';
|
||||
export { compileFileQuery, matchFileQuery } from './file-query.js';
|
||||
export type { FileQueryMatcher } from './file-query.js';
|
||||
export { resolveOmpDir, isOmpAvailable, getOmpNotFoundMessage, getOmpCliVersion } from './omp-cli-resolver.js';
|
||||
export {
|
||||
resolveCopilotDir,
|
||||
isCopilotAvailable,
|
||||
getCopilotNotFoundMessage,
|
||||
getCopilotCliVersion,
|
||||
} from './copilot-cli-resolver.js';
|
||||
export { readCopilotPlanUsage, resolveCopilotToken } from './copilot-plan-usage.js';
|
||||
export {
|
||||
boundedPathExists,
|
||||
describeUnknownPath,
|
||||
probePath,
|
||||
probePathKind,
|
||||
isNearStalledPath,
|
||||
unknownPathReason,
|
||||
} from './bounded-path-probe.js';
|
||||
export type { PathProbeState, PathProbeKind, PathProbeOptions } from './bounded-path-probe.js';
|
||||
export type { PathProbeOptions } from './bounded-path-probe.js';
|
||||
@@ -17,11 +17,7 @@ import { execFileSync } from 'node:child_process';
|
||||
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import {
|
||||
createCliExecutableResolver,
|
||||
formatCliNotFoundMessage,
|
||||
type CliResolverHost,
|
||||
} from './cli-executable-resolver.js';
|
||||
import { createCliExecutableResolver, type CliResolverHost } from './cli-executable-resolver.js';
|
||||
|
||||
/**
|
||||
* Directories probed after `which`, read from this CLI's registry entry so the spawn
|
||||
@@ -42,8 +38,6 @@ const OMP_SEARCH_DIRS = (): string[] => (getCli('omp')?.discovery.searchDirs ??
|
||||
*/
|
||||
export const OMP_VERSION_REGEX = /(?:^|\s)omp\/(\d+\.\d+\.\d+)/;
|
||||
|
||||
const OMP_NOT_FOUND = 'OMP CLI not found. Install with: curl -fsSL https://omp.sh/install | sh';
|
||||
|
||||
/**
|
||||
* Run `omp --version` on a candidate path and return the trimmed version when
|
||||
* it looks like the coding agent. Returns null for anything else — a missing
|
||||
@@ -125,10 +119,6 @@ export function isOmpAvailable(): boolean {
|
||||
return resolveOmpDir() !== null;
|
||||
}
|
||||
|
||||
export function getOmpNotFoundMessage(): string {
|
||||
return formatCliNotFoundMessage(OMP_NOT_FOUND, ompResolver.diagnostics());
|
||||
}
|
||||
|
||||
/**
|
||||
* Version reported by the resolved `omp` binary, or null when omp is
|
||||
* unavailable. Surfaced through `GET /api/omp/status` so a misresolution is
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import { createCliExecutableResolver, formatCliNotFoundMessage } from './cli-executable-resolver.js';
|
||||
import { createCliExecutableResolver } from './cli-executable-resolver.js';
|
||||
|
||||
/** Common directories where the OpenCode CLI binary may be installed */
|
||||
/**
|
||||
@@ -20,7 +20,6 @@ import { createCliExecutableResolver, formatCliNotFoundMessage } from './cli-exe
|
||||
const OPENCODE_SEARCH_DIRS = (): string[] => (getCli('opencode')?.discovery.searchDirs ?? []).map(expandHome);
|
||||
|
||||
const openCodeResolver = createCliExecutableResolver({ binary: 'opencode', searchDirs: OPENCODE_SEARCH_DIRS });
|
||||
const OPENCODE_NOT_FOUND = 'OpenCode CLI not found. Install with: curl -fsSL https://opencode.ai/install | bash';
|
||||
|
||||
/**
|
||||
* Finds the directory containing the `opencode` binary.
|
||||
@@ -39,7 +38,3 @@ export function resolveOpenCodeDir(): string | null {
|
||||
export function isOpenCodeAvailable(): boolean {
|
||||
return resolveOpenCodeDir() !== null;
|
||||
}
|
||||
|
||||
export function getOpenCodeNotFoundMessage(): string {
|
||||
return formatCliNotFoundMessage(OPENCODE_NOT_FOUND, openCodeResolver.diagnostics());
|
||||
}
|
||||
@@ -19,11 +19,7 @@ import { execFileSync } from 'node:child_process';
|
||||
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import {
|
||||
createCliExecutableResolver,
|
||||
formatCliNotFoundMessage,
|
||||
type CliResolverHost,
|
||||
} from './cli-executable-resolver.js';
|
||||
import { createCliExecutableResolver, type CliResolverHost } from './cli-executable-resolver.js';
|
||||
|
||||
/** Common directories where the Pi CLI binary may be installed */
|
||||
/**
|
||||
@@ -48,8 +44,6 @@ const PI_SEARCH_DIRS = (): string[] => (getCli('pi')?.discovery.searchDirs ?? []
|
||||
*/
|
||||
export const PI_VERSION_REGEX = /(?:^|\s)(\d+\.\d+\.\d+)/;
|
||||
|
||||
const PI_NOT_FOUND = 'Pi CLI not found. Install with: npm install -g --ignore-scripts @earendil-works/pi-coding-agent';
|
||||
|
||||
/**
|
||||
* Run `pi --version` on a candidate path and return the trimmed version when it
|
||||
* looks like the coding agent. Returns null for anything else — a missing
|
||||
@@ -132,10 +126,6 @@ export function isPiAvailable(): boolean {
|
||||
return resolvePiDir() !== null;
|
||||
}
|
||||
|
||||
export function getPiNotFoundMessage(): string {
|
||||
return formatCliNotFoundMessage(PI_NOT_FOUND, piResolver.diagnostics());
|
||||
}
|
||||
|
||||
/**
|
||||
* Version reported by the resolved `pi` binary, or null when pi is unavailable.
|
||||
* Surfaced through `GET /api/pi/status` so a misresolution is diagnosable from the UI.
|
||||
|
||||
+2
-2
@@ -62,7 +62,7 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
||||
|
||||
**Header button visibility**: most header controls are opt-in and hidden by a marker class (`btn-multimonitor--hidden`, `btn-response-viewer-header--hidden`, `btn-file-viewer--hidden`, `btn-cron--hidden`, and the desktop-gated `btn-split--hidden` / `btn-tile-grid--hidden`, which also need a `@media (max-width: 1179px)` backstop) that `applyHeaderVisibilitySettings()` (settings-ui.js) toggles after settings load; the multi-monitor button is instead stripped at render by `renderIndexHtml`. ⚠️ Hiding must go through the marker class: the base rules are `display:inline-flex !important`, so an inline style cannot override them. Current desktop default is WS/CPU/MEM + File Viewer + Tiles (1180px and wider) + gear, with the token chip and lifecycle-log button OFF. ⚠️ New header controls must not leak onto phones; `test/mobile-header-buttons-policy.test.ts` is the static guard. The one opt-in exception is File Viewer (#759): `mobile.css` no longer hides it at phone width, so it stays off a phone only through the handheld default in `getDefaultSettings()` and the `html.mobile-init` startup rule (both pinned by that test), and shows once the setting is switched on on that phone. → [architecture-invariants#header-button-visibility-multi-monitor-response-viewer-file-viewer-cron](../../docs/architecture-invariants.md#header-button-visibility-multi-monitor-response-viewer-file-viewer-cron)
|
||||
|
||||
**Terminal font weight** (`terminalFontWeight` / `terminalFontWeightBold`, per-device, default = xterm's own `normal`/`bold`): Claude Code's markdown bold is a bare `ESC[1m`, so the weight step is its only cue. `CodemanTerminalFont.resolveWeights()` (constants.js, pure) resolves each slot against **its own** xterm default. ⚠️ The `@font-face` for `fonts/jetbrains-mono-variable.woff2` must stay declared `100 800` (the browser synthesizes from the descriptor, not the file); narrowing it silently makes the setting a no-op. ⚠️ A live save must reach both echo overlays (`refreshFont()`) and open Agent Teams panes. ⚠️ Leave `_awaitTerminalFont()` untouched. Test: `test/terminal-font-weight.test.ts`. → [architecture-invariants#terminal-font-weight](../../docs/architecture-invariants.md#terminal-font-weight)
|
||||
**Terminal font weight** (`terminalFontWeight` / `terminalFontWeightBold`, per-device, default = xterm's own `normal`/`bold`): Claude Code's markdown bold is a bare `ESC[1m`, so the weight step is its only cue. `CodemanTerminalFont.resolveWeights()` (constants.js, pure) resolves each slot against **its own** xterm default. ⚠️ The `@font-face` for `fonts/jetbrains-mono-variable.woff2` must stay declared `100 800` (the browser synthesizes from the descriptor, not the file); narrowing it silently makes the setting a no-op. ⚠️ A live save must reach both echo overlays (`refreshFont()`) and every open tile and split pane (`_forEachTile`). ⚠️ Leave `_awaitTerminalFont()` untouched. Test: `test/terminal-font-weight.test.ts`. → [architecture-invariants#terminal-font-weight](../../docs/architecture-invariants.md#terminal-font-weight)
|
||||
|
||||
**Theme skins / branding / i18n**: `skin` selects a palette via `data-skin` on `<html>`, applied by an **inline pre-paint script** in `index.html` reading `localStorage['codeman:skin']` to avoid a flash of wrong theme. ⚠️ A skin is **four things that must stay in sync**, and missing any one degrades silently: the `html[data-skin="…"]` token block in `styles.css`, the xterm ANSI palette in `terminal-ui.js`, the pre-paint allowlist, and the Settings picker (both in `index.html`). `test/skin-themes.test.ts` is the static guard. Light skins additionally need `color-scheme: light` and xterm `minimumContrastRatio: 4.5`, and `applyTerminalSkin()` must call the local-echo overlay's `refreshFont()` because it caches the terminal fg/bg. `displayName` changes user-facing browser branding only and must NEVER rename npm package, CLI, API, storage, CSS, or protocol identifiers. `language` (`en`/`zh-CN`) keeps English as the canonical source so live switching stays reversible. User display names flow through `textContent`/attribute APIs and the server title's HTML escaper, never `innerHTML`. → [architecture-invariants#theme-skins](../../docs/architecture-invariants.md#theme-skins)
|
||||
|
||||
@@ -94,6 +94,6 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
||||
|
||||
**SSE staleness watchdog** (`computeSseStale()` in constants.js, `_checkSseStale()` + a 5s interval in app.js): an `EventSource` can stop delivering without erroring, so the client forces a reconnect when nothing arrives. ⚠️ The server keepalive must stay the named `sse:heartbeat` event (`cleanupDeadClients()`, sse-stream-manager.ts), never an SSE comment, which `EventSource` cannot observe; its no-op client listener must stay registered. ⚠️ Judge staleness only while `connected` and online (the loop breaker). ⚠️ The liveness stamp lives inside `addListener`. ⚠️ Clear the interval only at the top of `connectSSE()`, or intervals stack. ⚠️ The watchdog cannot see an attempt that never OPENS (no response headers: no `open`, no `error`, never `connected`), so each attempt is bounded by `SSE_CONNECT_TIMEOUT_MS` (15s, `CodemanSseStale.CONNECT_TIMEOUT_MS`) and then retried through `_handleSseConnectionFailure()`, the same backoff `onerror` uses. Its timer is cleared at the top of `connectSSE()` BEFORE the offline early return, on `open`, and in `_handleSseConnectionFailure()`; the timer and the handler both ignore an `EventSource` that has been replaced. The window `offline` handler leaves it running on purpose (`navigator.onLine` can report offline on a working network). Tests: `test/sse-connect-timeout.test.ts`. → [architecture-invariants#sse-staleness-watchdog](../../docs/architecture-invariants.md#sse-staleness-watchdog)
|
||||
|
||||
**Z-index layers** (keep new overlays consistent with this stack): local echo overlay (7; with local echo on it also draws the iOS IME composition preview, as an underlined tail after its pending text via `setComposition`), iOS IME composition preview span when local echo is off (6 inside `.xterm-helpers`, whose own z-index 5 is its EFFECTIVE layer, so it sits UNDER the overlay and must never be used while the overlay shows text), terminal touch-selection bar (900, below floating agent windows), subagent windows + split picker menu + Tiles count menu (1000), plan agents (1100), mobile/tablet fixed header (1200), modals on ≤768px (1300, must beat the fixed header), log viewers (2000), connection-loss overlay (2500), image popups (3000), response viewer (5000, backdrop 4999), folder grid (5090, above the response viewer it opens from, below the file preview its tiles open), file-preview overlay (5100, must outrank the response viewer that launches it), toasts/path picker (10000+), custom-model center-status banner (10001; its `[hidden]` must re-assert `display: none` or `dismiss()` leaves an invisible click-blocker), custom-model swap-confirm/context-warning modals (10010). → [architecture-invariants#z-index-layers](../../docs/architecture-invariants.md#z-index-layers)
|
||||
**Z-index layers** (keep new overlays consistent with this stack): local echo overlay (7; with local echo on it also draws the iOS IME composition preview, as an underlined tail after its pending text via `setComposition`), iOS IME composition preview span when local echo is off (6 inside `.xterm-helpers`, whose own z-index 5 is its EFFECTIVE layer, so it sits UNDER the overlay and must never be used while the overlay shows text), terminal touch-selection bar (900, below floating agent windows), subagent windows + split picker menu + Tiles count menu (1000), mobile/tablet fixed header (1200), modals on ≤768px (1300, must beat the fixed header), log viewers (2000), connection-loss overlay (2500), image popups (3000), response viewer (5000, backdrop 4999), folder grid (5090, above the response viewer it opens from, below the file preview its tiles open), file-preview overlay (5100, must outrank the response viewer that launches it), toasts/path picker (10000+), custom-model center-status banner (10001; its `[hidden]` must re-assert `display: none` or `dismiss()` leaves an invisible click-blocker), custom-model swap-confirm/context-warning modals (10010). → [architecture-invariants#z-index-layers](../../docs/architecture-invariants.md#z-index-layers)
|
||||
|
||||
**Keyboard shortcuts**: Escape (close), Ctrl+? (shortcut overlay), Ctrl/Cmd/Alt+K (session palette), Ctrl+Tab (next), Alt+[/] (prev/next tab), Alt+1-9 (switch tab), Ctrl+Shift+{/} (move tab left/right), Shift+Enter or Ctrl+Enter (newline), Ctrl+C (copy selection, else interrupt) / Ctrl+Shift+C (copy, never interrupts), Ctrl+L (clear), Ctrl+Shift+R (restore size), Ctrl+Shift+V (voice input), Ctrl/Cmd +/- (font), Shift+Wheel (local scrollback when mouse passthrough is active), Shift+drag (start a selection in a stripped-DECSET pane, where xterm's own Shift branch is unreachable and a Shift+drag used to select nothing; `_installShiftDragSelection`), right-click (copy the selection, the mintty/PuTTY convention, since xterm paints into a canvas and the native menu has no Copy for it; with nothing selected the native menu is left alone). Rebindable via the registry. ⚠️ **Ctrl+W is deliberately NOT bound** (owner decision): it is delete-word in every shell and agent CLI, and as Close Session it killed sessions with no confirm; `close-session` keeps `bindings: []` and stays bindable (`test/ctrl-w-never-closes.test.ts`).
|
||||
@@ -1,8 +1,6 @@
|
||||
/** @fileoverview Owner-scoped tab-layout capabilities exposed to route modules. */
|
||||
import type { TabLayoutService } from '../../tab-layout-service.js';
|
||||
|
||||
export type { LegacyOrderActor, LegacyOrderPutResult, SessionOrderProjectionChange } from '../../tab-layout-service.js';
|
||||
|
||||
export interface TabLayoutPort {
|
||||
readonly tabLayouts: TabLayoutService;
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
*
|
||||
* @mixin Extends CodemanApp.prototype via Object.assign
|
||||
* @dependency app.js (CodemanApp class must be defined)
|
||||
* @loadorder 14 of 15 — loaded after ralph-wizard.js
|
||||
* @loadorder 14 of 15 — loaded after session-ui.js
|
||||
*/
|
||||
|
||||
// Codeman — Centralized API fetch helpers for CodemanApp
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
* panels-ui.js — Subagent panel, agent teams, project insights, file browser, log viewer,
|
||||
* image popups, monitor, token stats, toast, system stats
|
||||
* session-ui.js — Quick start, session options modal, case settings, mobile case picker
|
||||
* ralph-wizard.js — Ralph Loop wizard modal
|
||||
* api-client.js — API helper methods (fetch wrappers)
|
||||
* subagent-windows.js — Floating subagent terminal windows
|
||||
*
|
||||
@@ -299,13 +298,6 @@ const _SSE_HANDLER_MAP = [
|
||||
[SSE_EVENTS.TUNNEL_QR_REGENERATED, '_onTunnelQrRegenerated'],
|
||||
[SSE_EVENTS.TUNNEL_QR_AUTH_USED, '_onTunnelQrAuthUsed'],
|
||||
|
||||
// Plan orchestration
|
||||
[SSE_EVENTS.PLAN_SUBAGENT, '_onPlanSubagent'],
|
||||
[SSE_EVENTS.PLAN_PROGRESS, '_onPlanProgress'],
|
||||
[SSE_EVENTS.PLAN_STARTED, '_onPlanStarted'],
|
||||
[SSE_EVENTS.PLAN_CANCELLED, '_onPlanCancelled'],
|
||||
[SSE_EVENTS.PLAN_COMPLETED, '_onPlanCompleted'],
|
||||
|
||||
// Orchestrator loop
|
||||
[SSE_EVENTS.ORCHESTRATOR_STATE_CHANGED, '_onOrchestratorStateChanged'],
|
||||
[SSE_EVENTS.ORCHESTRATOR_PLAN_PROGRESS, '_onOrchestratorPlanProgress'],
|
||||
@@ -863,31 +855,11 @@ class CodemanApp {
|
||||
// Once set, never recalculated. Persisted to localStorage and server.
|
||||
this.subagentParentMap = new Map();
|
||||
|
||||
// Agent Teams tracking
|
||||
this.teams = new Map(); // Map<teamName, TeamConfig>
|
||||
this.teamTasks = new Map(); // Map<teamName, TeamTask[]>
|
||||
this.teammateMap = new Map(); // Map<agentId-prefix, {name, color, teamName}> for quick lookup
|
||||
|
||||
// Teammate tmux pane terminals (Agent Teams feature)
|
||||
this.teammatePanesByName = new Map(); // Map<name, { paneTarget, sessionId, color }>
|
||||
this.teammateTerminals = new Map(); // Map<agentId, { terminal, fitAddon, paneTarget, sessionId, resizeObserver }>
|
||||
|
||||
this.terminalBufferCache = new Map(); // Map<sessionId, string> — client-side cache for instant tab re-visits (max 20)
|
||||
|
||||
this.ralphStatePanelCollapsed = true; // Default to collapsed
|
||||
this.ralphClosedSessions = new Set(); // Sessions where user explicitly closed Ralph panel
|
||||
|
||||
// Plan subagent windows (visible agents during plan generation)
|
||||
this.planSubagents = new Map(); // Map<agentId, { type, model, status, startTime, element, relativePos }>
|
||||
this.planSubagentWindowZIndex = ZINDEX_PLAN_SUBAGENT_BASE;
|
||||
this.planGenerationStopped = false; // Flag to ignore SSE events after Stop
|
||||
this.planAgentsMinimized = false; // Whether agent windows are minimized to tab
|
||||
|
||||
// Wizard dragging state
|
||||
this.wizardDragState = null; // { startX, startY, startLeft, startTop, isDragging }
|
||||
this.wizardDragListeners = null; // { move, up } for cleanup
|
||||
this.wizardPosition = null; // { left, top } - null means centered
|
||||
|
||||
// Project Insights tracking (active Bash tools with clickable file paths)
|
||||
this.projectInsights = new Map(); // Map<sessionId, ActiveBashTool[]>
|
||||
this.logViewerWindows = new Map(); // Map<windowId, { element, eventSource, filePath }>
|
||||
@@ -1819,15 +1791,6 @@ class CodemanApp {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Re-dock a session: close its window (which re-docks via its unload
|
||||
* announcement) and clear dashboard state now. */
|
||||
redockSession(id) {
|
||||
const win = this.detachedWindows.get(id);
|
||||
if (win && !win.closed) { try { win.close(); } catch {} }
|
||||
this._postWindowMessage({ type: 'close-request', id });
|
||||
this._redock(id);
|
||||
}
|
||||
|
||||
/** Clear all dashboard-side detached state/timers for a session, and take its
|
||||
* sizing back: the popup owned the pane while it was open, so the dashboard's
|
||||
* record of it is stale and the session it is showing needs re-measuring.
|
||||
@@ -4989,8 +4952,6 @@ class CodemanApp {
|
||||
this._xtermSnapshots?.clear();
|
||||
}
|
||||
this.projectInsights.clear();
|
||||
this.teams.clear();
|
||||
this.teamTasks.clear();
|
||||
// Clear all idle timers to prevent stale timers from firing
|
||||
for (const timer of this.idleTimers.values()) {
|
||||
clearTimeout(timer);
|
||||
@@ -5074,10 +5035,6 @@ class CodemanApp {
|
||||
// wrapping) clipped xterm's bottom rows behind the toolbar until a tab
|
||||
// switch or a window resize.
|
||||
// Clear any other orphaned timers
|
||||
if (this.planLoadingTimer) {
|
||||
clearInterval(this.planLoadingTimer);
|
||||
this.planLoadingTimer = null;
|
||||
}
|
||||
if (this.timerCountdownInterval) {
|
||||
clearInterval(this.timerCountdownInterval);
|
||||
this.timerCountdownInterval = null;
|
||||
@@ -11156,28 +11113,6 @@ class CodemanApp {
|
||||
this.renderRalphStatePanel();
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Ralph Loop Wizard (methods in ralph-wizard.js)
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
// Wizard state (initialized here, methods loaded from ralph-wizard.js)
|
||||
ralphWizardStep = 1;
|
||||
ralphWizardConfig = {
|
||||
taskDescription: '',
|
||||
completionPhrase: 'COMPLETE',
|
||||
maxIterations: 10,
|
||||
caseName: 'testcase',
|
||||
enableRespawn: false,
|
||||
generatedPlan: null,
|
||||
planGenerated: false,
|
||||
skipPlanGeneration: false,
|
||||
planDetailLevel: 'detailed',
|
||||
existingPlan: null,
|
||||
useExistingPlan: false,
|
||||
};
|
||||
planLoadingTimer = null;
|
||||
planLoadingStartTime = null;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Kill Sessions
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
* @dependency None (first in load order)
|
||||
* @loadorder 1 of 15 — constants.js → mobile-handlers.js → voice-input.js → notification-manager.js
|
||||
* → keyboard-accessory.js → input-cjk.js → app.js → terminal-ui.js → respawn-ui.js
|
||||
* → ralph-panel.js → settings-ui.js → panels-ui.js → session-ui.js → ralph-wizard.js
|
||||
* → ralph-panel.js → settings-ui.js → panels-ui.js → session-ui.js
|
||||
* → api-client.js → subagent-windows.js
|
||||
*/
|
||||
|
||||
@@ -112,8 +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 THROTTLE_DELAY_MS = 100; // General UI throttle delay
|
||||
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
|
||||
@@ -131,22 +130,16 @@ 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 STATS_POLLING_INTERVAL_MS = 2000; // System stats polling
|
||||
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
|
||||
const ZINDEX_SUBAGENT_BASE = 1000;
|
||||
const ZINDEX_PLAN_SUBAGENT_BASE = 1100;
|
||||
const ZINDEX_LOG_VIEWER_BASE = 2000;
|
||||
const ZINDEX_IMAGE_POPUP_BASE = 3000;
|
||||
|
||||
// Subagent/floating window layout
|
||||
const WINDOW_INITIAL_TOP_PX = 120;
|
||||
const WINDOW_CASCADE_OFFSET_PX = 30;
|
||||
const WINDOW_MIN_WIDTH_PX = 200;
|
||||
const WINDOW_MIN_HEIGHT_PX = 200;
|
||||
const WINDOW_DEFAULT_WIDTH_PX = 300;
|
||||
|
||||
// WebGL renderer auto-fallback thresholds.
|
||||
// _installWebGLLongTaskGuard() observes longtask entries and disables WebGL
|
||||
@@ -1970,7 +1963,7 @@ function getEventCoords(e) {
|
||||
return { clientX: e.clientX, clientY: e.clientY };
|
||||
}
|
||||
|
||||
// HTML escape utility (shared by NotificationManager, CodemanApp, and ralph-wizard.js)
|
||||
// HTML escape utility (shared by NotificationManager and the CodemanApp mixins)
|
||||
const _htmlEscapeMap = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
||||
const _htmlEscapePattern = /[&<>"']/g;
|
||||
function escapeHtml(text) {
|
||||
|
||||
@@ -58,7 +58,7 @@
|
||||
* @dependency app.js (tab render pipeline), subagent-windows.js (window + line hooks),
|
||||
* tile-grid.js (tile mount, reveal and still-copy hooks)
|
||||
* @dependency constants.js (escapeHtml)
|
||||
* @loadorder 12.6 of 16, after webview-tabs.js, before ralph-wizard.js
|
||||
* @loadorder 12.6 of 16, after webview-tabs.js, before api-client.js
|
||||
*/
|
||||
|
||||
/** Tab entrance styles. `key` doubles as the `data-tab-anim` value. */
|
||||
|
||||
@@ -1280,16 +1280,6 @@
|
||||
<div class="monitor-empty">No mux sessions</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="monitor-section" id="monitorPlanAgentsSection" style="display: none;">
|
||||
<div class="monitor-section-header">
|
||||
<span>Plan Wizard Agents</span>
|
||||
<span class="task-stats" id="monitorPlanAgentStats">0 active</span>
|
||||
<button class="btn-toolbar btn-sm btn-danger" onclick="app.cancelPlanFromMonitor()" title="Cancel plan generation">Cancel</button>
|
||||
</div>
|
||||
<div class="monitor-section-body" id="monitorPlanAgentsBody">
|
||||
<div class="monitor-empty">No plan agents</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="monitor-section" id="monitorSubagentsSection">
|
||||
<div class="monitor-section-header">
|
||||
<span>Background Agents</span>
|
||||
@@ -4217,189 +4207,6 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Ralph Loop Wizard Modal -->
|
||||
<div class="modal" id="ralphWizardModal">
|
||||
<div class="modal-backdrop"></div>
|
||||
<div class="modal-content modal-wizard">
|
||||
<div class="modal-header">
|
||||
<h3>Start Ralph Loop</h3>
|
||||
<div class="modal-header-actions">
|
||||
<button class="modal-close" onclick="app.closeRalphWizard()" aria-label="Close Ralph wizard">×</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Wizard Progress Steps -->
|
||||
<div class="wizard-progress">
|
||||
<div class="wizard-step active" data-step="1">
|
||||
<span class="wizard-step-number">1</span>
|
||||
<span class="wizard-step-label">Describe</span>
|
||||
</div>
|
||||
<div class="wizard-step" data-step="2">
|
||||
<span class="wizard-step-number">2</span>
|
||||
<span class="wizard-step-label">Plan</span>
|
||||
</div>
|
||||
<div class="wizard-step" data-step="3">
|
||||
<span class="wizard-step-number">3</span>
|
||||
<span class="wizard-step-label">Launch</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-body">
|
||||
<!-- Step 1: Task & Completion Setup -->
|
||||
<div class="wizard-page wizard-page-compact" id="ralphWizardStep1">
|
||||
<div class="wizard-step-intro">
|
||||
<p>Describe your task below. Claude will generate an implementation plan with testing steps.</p>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label>What do you want to build?</label>
|
||||
<div class="textarea-with-assist">
|
||||
<textarea
|
||||
id="ralphTaskDescription"
|
||||
rows="3"
|
||||
placeholder="Build a REST API for user authentication with JWT tokens, login/logout endpoints, and password reset flow."></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="wizard-inline-row">
|
||||
<div class="wizard-inline-field">
|
||||
<label>Working Directory <span id="existingPlanBadge" class="existing-plan-badge" style="display:none"></span></label>
|
||||
<div class="case-select-inline">
|
||||
<select id="ralphCaseSelect" class="form-select" onchange="app.onRalphCaseChange()"></select>
|
||||
<button class="btn-toolbar btn-sm" onclick="app.showCreateCaseModal()">+</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="wizard-inline-field wizard-inline-field-small">
|
||||
<label>Iterations</label>
|
||||
<div class="iteration-presets-compact">
|
||||
<button type="button" class="iteration-preset-btn active" data-iterations="10" onclick="app.selectIterationPreset(10)">10</button>
|
||||
<button type="button" class="iteration-preset-btn" data-iterations="25" onclick="app.selectIterationPreset(25)">25</button>
|
||||
<button type="button" class="iteration-preset-btn" data-iterations="50" onclick="app.selectIterationPreset(50)">50</button>
|
||||
<button type="button" class="iteration-preset-btn" data-iterations="0" onclick="app.selectIterationPreset(0)">∞</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Hidden completion phrase with default -->
|
||||
<input type="hidden" id="ralphCompletionPhrase" value="COMPLETE">
|
||||
</div>
|
||||
|
||||
<!-- Step 2: Plan Generation -->
|
||||
<div class="wizard-page wizard-page-compact hidden" id="ralphWizardStep2">
|
||||
<!-- Existing plan detected (shown when @fix_plan.md exists) -->
|
||||
<div id="existingPlanSection" class="plan-section hidden">
|
||||
<!-- Content populated by app.updateExistingPlanUI() -->
|
||||
</div>
|
||||
|
||||
<!-- Loading state (shown during generation) -->
|
||||
<div id="planGenerationLoading" class="plan-loading-state hidden">
|
||||
<div class="plan-loading-content">
|
||||
<div class="plan-spinner"></div>
|
||||
<div class="plan-loading-text">
|
||||
<span class="plan-loading-title" id="planLoadingTitle">Starting Opus 4.5...</span>
|
||||
<span class="plan-loading-time" id="planLoadingTime">0s</span>
|
||||
</div>
|
||||
</div>
|
||||
<p class="plan-loading-hint" id="planLoadingHint">Initializing deep reasoning model</p>
|
||||
<div class="plan-loading-actions">
|
||||
<button class="btn-toolbar btn-sm plan-cancel-btn" onclick="app.cancelPlanGeneration()">Stop</button>
|
||||
<button class="btn-toolbar btn-sm" onclick="app.regeneratePlan()">Regenerate</button>
|
||||
</div>
|
||||
<!-- Auto-start toggle visible during generation -->
|
||||
<div class="plan-autostart-toggle">
|
||||
<label class="plan-autostart-label">
|
||||
<input type="checkbox" id="ralphAutoStartStep2" onchange="app.ralphWizardConfig.autoStart = this.checked">
|
||||
<span class="plan-autostart-text">Auto-launch when plan completes</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Stopped/Error state -->
|
||||
<div id="planGenerationError" class="plan-section hidden">
|
||||
<div class="plan-stopped-indicator" id="planStoppedIndicator">
|
||||
<span class="plan-stopped-icon">■</span>
|
||||
<span class="plan-stopped-text">Stopped</span>
|
||||
</div>
|
||||
<p class="plan-error-msg" id="planErrorMsg"></p>
|
||||
<div class="plan-actions">
|
||||
<button class="btn-toolbar btn-primary" onclick="app.generatePlan()">Regenerate Plan</button>
|
||||
</div>
|
||||
<p class="plan-skip-hint">Use <strong>Back</strong> to edit your task, or <strong>Next</strong> to continue without a plan</p>
|
||||
</div>
|
||||
|
||||
<!-- Editor state -->
|
||||
<div id="planEditor" class="plan-section hidden">
|
||||
<div class="plan-editor-header">
|
||||
<span>Implementation Plan <span class="plan-stats" id="planStats"></span></span>
|
||||
<div class="plan-editor-actions">
|
||||
<div class="plan-option-group">
|
||||
<label>Detail:</label>
|
||||
<div class="plan-detail-btns">
|
||||
<button type="button" class="plan-detail-btn" data-detail="standard" onclick="app.setPlanDetail('standard')" title="Single-pass generation with Opus 4.5">Standard</button>
|
||||
<button type="button" class="plan-detail-btn active" data-detail="detailed" onclick="app.setPlanDetail('detailed')" title="Enhanced: parallel subagents + verification (slower but more thorough)">Enhanced</button>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn-toolbar btn-sm" onclick="app.regeneratePlan()">Regenerate</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="planItemsList" class="plan-items-list"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Step 3: Preview & Launch -->
|
||||
<div class="wizard-page hidden" id="ralphWizardStep3">
|
||||
<div class="ralph-preview-section">
|
||||
<label>Prompt Preview</label>
|
||||
<div class="ralph-prompt-preview" id="ralphPromptPreview"></div>
|
||||
</div>
|
||||
|
||||
<div class="ralph-config-summary">
|
||||
<div class="config-summary-row">
|
||||
<span class="config-label">Completion Phrase:</span>
|
||||
<code id="summaryPhrase">COMPLETE</code>
|
||||
</div>
|
||||
<div class="config-summary-row">
|
||||
<span class="config-label">Max Iterations:</span>
|
||||
<span id="summaryIterations">10</span>
|
||||
</div>
|
||||
<div class="config-summary-row">
|
||||
<span class="config-label">Case:</span>
|
||||
<span id="summaryCase">testcase</span>
|
||||
</div>
|
||||
<div class="config-summary-row" style="display: none;">
|
||||
<span class="config-label">Plan:</span>
|
||||
<span id="summaryPlan">-</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Advanced Options (Collapsible) -->
|
||||
<details class="advanced-options">
|
||||
<summary>Advanced Options</summary>
|
||||
<div class="advanced-options-content">
|
||||
<div class="form-row form-row-switch">
|
||||
<label>Enable Respawn</label>
|
||||
<label class="switch">
|
||||
<input type="checkbox" id="ralphEnableRespawn">
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
<span class="form-hint">Auto-restart sessions when context fills up (usually not needed)</span>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Wizard Footer -->
|
||||
<div class="wizard-footer">
|
||||
<button class="btn-toolbar" id="ralphBackBtn" onclick="app.ralphWizardBack()" style="display: none;">Back</button>
|
||||
<div class="wizard-footer-right">
|
||||
<button class="btn-toolbar" onclick="app.closeRalphWizard()">Cancel</button>
|
||||
<button class="btn-toolbar btn-primary" id="ralphNextBtn" onclick="app.ralphWizardNext()">Next</button>
|
||||
<button class="btn-toolbar btn-success" id="ralphStartBtn" onclick="app.startRalphLoop()" style="display: none;">Start Loop</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- Kill All Confirmation Modal -->
|
||||
<div class="modal" id="killAllModal">
|
||||
<div class="modal-backdrop" onclick="app.closeKillAllModal()"></div>
|
||||
@@ -4764,7 +4571,6 @@
|
||||
<script defer src="edit-history-ui.js"></script>
|
||||
<script defer src="local-model-ui.js"></script>
|
||||
<script defer src="entrance-animations.js"></script>
|
||||
<script defer src="ralph-wizard.js"></script>
|
||||
<script defer src="api-client.js"></script>
|
||||
<script defer src="subagent-windows.js"></script>
|
||||
<script defer src="ultracode-windows.js"></script>
|
||||
|
||||
@@ -26,8 +26,7 @@
|
||||
* by Link Existing and the extended mobile keyboard bar.
|
||||
*
|
||||
* - FocusTrap (class) — Traps Tab/Shift+Tab keyboard focus within a modal element.
|
||||
* Saves and restores previously focused element on deactivate. Used by Ralph wizard
|
||||
* and other modal dialogs.
|
||||
* Saves and restores previously focused element on deactivate. Used by the modal dialogs.
|
||||
*
|
||||
* @globals {object} KeyboardAccessoryBar
|
||||
* @globals {object} PathPicker
|
||||
|
||||
@@ -226,15 +226,6 @@ html.mobile-init .file-browser-panel {
|
||||
min-height: 56px;
|
||||
}
|
||||
|
||||
/* Settings grid stays 2-col on tablet but tighter */
|
||||
.settings-grid {
|
||||
gap: 0.4rem 0.75rem;
|
||||
}
|
||||
|
||||
.settings-item {
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
|
||||
/* Event type grid - slightly tighter */
|
||||
.event-type-grid {
|
||||
grid-template-columns: 1fr 40px 40px 40px;
|
||||
@@ -1774,11 +1765,6 @@ html.mobile-init .file-browser-panel {
|
||||
min-height: 0; /* Allow flex item to shrink below content size */
|
||||
}
|
||||
|
||||
/* Show CLI info bar on mobile (Claude version/model) */
|
||||
.cli-info-bar {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* Mobile terminal — JS touch handler (terminal.scrollLines()) drives
|
||||
scrollback because xterm.js DOM renderer doesn't populate xterm-viewport's
|
||||
scroll area. touch-action:none lets our JS handler own the gesture. */
|
||||
@@ -1941,30 +1927,6 @@ html.mobile-init .file-browser-panel {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
/* Ralph wizard responsive */
|
||||
.modal-wizard {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.wizard-progress {
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.wizard-step {
|
||||
padding: 0.3rem;
|
||||
}
|
||||
|
||||
.wizard-step-number {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
|
||||
.wizard-step-label {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Timer banner - includes safe area padding */
|
||||
.timer-banner {
|
||||
padding-left: calc(0.5rem + var(--safe-area-left));
|
||||
@@ -2095,27 +2057,6 @@ html.mobile-init .file-browser-panel {
|
||||
|
||||
/* ---- Session Options Modal: Respawn Tab Mobile Optimizations ---- */
|
||||
|
||||
/* Respawn header — keep horizontal, compact */
|
||||
.respawn-header {
|
||||
flex-direction: row;
|
||||
gap: 0.4rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
/* Enable/Stop buttons — compact */
|
||||
.respawn-header .respawn-actions {
|
||||
display: flex;
|
||||
gap: 0.3rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.respawn-header .respawn-actions .btn-toolbar {
|
||||
min-height: 28px !important;
|
||||
font-size: 0.7rem !important;
|
||||
padding: 0.2rem 0.5rem !important;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
/* Duration preset buttons — one compact row */
|
||||
.duration-presets {
|
||||
display: flex;
|
||||
@@ -2148,28 +2089,6 @@ html.mobile-init .file-browser-panel {
|
||||
padding: 0.1rem 0.3rem;
|
||||
}
|
||||
|
||||
/* Preset selector row — full-width dropdown, buttons below */
|
||||
.preset-selector {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.preset-selector select {
|
||||
grid-column: 1 / -1;
|
||||
min-height: 32px;
|
||||
font-size: 16px; /* Prevents iOS zoom */
|
||||
border-radius: 5px;
|
||||
padding: 0.2rem 0.4rem;
|
||||
}
|
||||
|
||||
.preset-selector .btn {
|
||||
min-height: 32px;
|
||||
font-size: 0.65rem;
|
||||
border-radius: 5px;
|
||||
padding: 0.2rem 0.4rem;
|
||||
}
|
||||
|
||||
/* Textareas — prevent iOS zoom with 16px font, compact height */
|
||||
#sessionOptionsModal textarea {
|
||||
font-size: 16px;
|
||||
@@ -2204,21 +2123,6 @@ html.mobile-init .file-browser-panel {
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
/* Respawn-loop box title matches the auto-resume title; its cycle-step
|
||||
checkboxes match the step labels */
|
||||
#sessionOptionsModal .respawn-loop-title {
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
#sessionOptionsModal .respawn-loop-box .checkbox-inline {
|
||||
font-size: 0.65rem;
|
||||
}
|
||||
|
||||
/* Respawn options row — stack if needed */
|
||||
#sessionOptionsModal .respawn-options-row {
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
/* Form section headers — compact on mobile */
|
||||
#sessionOptionsModal .form-section-header {
|
||||
margin-top: 0.75rem;
|
||||
@@ -2244,30 +2148,6 @@ html.mobile-init .file-browser-panel {
|
||||
|
||||
/* ---- Context Tab: Mobile Optimizations ---- */
|
||||
|
||||
/* Context settings cards — tighter padding */
|
||||
.context-setting {
|
||||
padding: 0.625rem;
|
||||
}
|
||||
|
||||
/* Stack context setting header vertically on narrow screens */
|
||||
.context-setting-header {
|
||||
flex-wrap: wrap;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.context-setting-header .input-suffix-sm input {
|
||||
width: 60px;
|
||||
font-size: 16px; /* Prevents iOS zoom */
|
||||
min-height: 36px;
|
||||
}
|
||||
|
||||
.context-setting input[type="text"] {
|
||||
font-size: 16px; /* Prevents iOS zoom */
|
||||
min-height: 36px;
|
||||
padding: 0.4rem 0.6rem;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
/* Color picker — larger swatches for touch */
|
||||
.color-picker {
|
||||
gap: 8px;
|
||||
@@ -2285,27 +2165,8 @@ html.mobile-init .file-browser-panel {
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
/* Number inputs in context tab — prevent iOS zoom */
|
||||
.context-settings-grid input[type="number"] {
|
||||
font-size: 16px;
|
||||
min-height: 36px;
|
||||
}
|
||||
|
||||
/* ---- Ralph Tab: Mobile Optimizations ---- */
|
||||
|
||||
/* Ralph limits grid — 2 columns on mobile */
|
||||
.ralph-limits-grid {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.ralph-limits-grid .form-col input[type="number"] {
|
||||
font-size: 16px; /* Prevents iOS zoom */
|
||||
min-height: 36px;
|
||||
padding: 0.4rem 0.5rem;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
/* Ralph phrase input — prevent iOS zoom */
|
||||
#modalRalphPhrase {
|
||||
font-size: 16px;
|
||||
@@ -2313,18 +2174,6 @@ html.mobile-init .file-browser-panel {
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
/* Save button — full width, proper touch target */
|
||||
.ralph-config-actions {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.ralph-config-actions .btn-toolbar {
|
||||
width: 100%;
|
||||
min-height: 44px;
|
||||
font-size: 0.85rem;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
/* ---- Summary Tab: Mobile Optimizations ---- */
|
||||
|
||||
/* Filter buttons — larger touch targets */
|
||||
@@ -2587,31 +2436,6 @@ html.mobile-init .file-browser-panel {
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
/* Settings grid - single column on phones */
|
||||
.settings-grid {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.settings-grid-3col {
|
||||
grid-template-columns: 1fr 1fr 1fr;
|
||||
}
|
||||
|
||||
.settings-item {
|
||||
padding: 0.35rem 0.5rem;
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
|
||||
.settings-item-label {
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
|
||||
.settings-section-header {
|
||||
font-size: 0.6rem;
|
||||
padding: 0.35rem 0 0.2rem 0;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
/* Form rows - compact on mobile */
|
||||
.form-row {
|
||||
margin-bottom: 0.5rem;
|
||||
@@ -3560,12 +3384,6 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
|
||||
transform: none;
|
||||
}
|
||||
|
||||
/* Show dropdown on tap instead of hover */
|
||||
.subagent-dropdown-trigger:active + .subagent-dropdown-menu,
|
||||
.subagent-dropdown-trigger:focus + .subagent-dropdown-menu {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* Press feedback for the touch bars. The pressed look is transform + filter,
|
||||
never a background or a shadow: the skin block (html:not([data-skin="og"]),
|
||||
specificity 0,2,1) and the per-run-mode colors own the background and its
|
||||
|
||||
@@ -255,19 +255,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
},
|
||||
|
||||
async refreshOrchestratorStatus() {
|
||||
try {
|
||||
const res = await fetch('/api/orchestrator/status');
|
||||
const data = await res.json();
|
||||
if (data.data?.ok) {
|
||||
this.orchestratorState = data.data;
|
||||
this.renderOrchestratorPanel();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[Orchestrator] Status fetch failed:', err);
|
||||
}
|
||||
},
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Rendering
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
+22
-586
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* @fileoverview Subagent panel (discovery, detail view, kill), subagent parent tracking,
|
||||
* agent teams (tasks panel, teammate badges, terminals), project insights (bash tool tracking),
|
||||
* agent teams (teammate badges), project insights (bash tool tracking),
|
||||
* file browser (directory tree, preview), log viewer (floating file streamers),
|
||||
* image popups (auto-popup for screenshots), mux sessions, monitor panel,
|
||||
* token statistics, toast notifications, and system stats.
|
||||
@@ -177,7 +177,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
this.findParentSessionForSubagent(data.agentId);
|
||||
|
||||
// Subagent windows are no longer auto-opened on discovery.
|
||||
// Users can open them manually from the monitor panel or via openAllActiveSubagentWindows().
|
||||
// Users open them from the subagents panel.
|
||||
|
||||
// Ensure connection lines are updated after window is created and DOM settles
|
||||
requestAnimationFrame(() => {
|
||||
@@ -1388,12 +1388,21 @@ Object.assign(CodemanApp.prototype, {
|
||||
},
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Monitor Panel Detach & Drag
|
||||
// Monitor and Subagents Panel Detach & Drag
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
toggleMonitorDetach() {
|
||||
const panel = document.getElementById('monitorPanel');
|
||||
const detachBtn = document.getElementById('monitorDetachBtn');
|
||||
this._togglePanelDetach('monitorPanel', 'monitorPanelHeader', 'monitorDetachBtn');
|
||||
},
|
||||
|
||||
toggleSubagentsDetach() {
|
||||
this._togglePanelDetach('subagentsPanel', 'subagentsPanelHeader', 'subagentsDetachBtn');
|
||||
},
|
||||
|
||||
/** Float a bottom panel as a draggable window, or dock it back. */
|
||||
_togglePanelDetach(panelId, headerId, detachBtnId) {
|
||||
const panel = document.getElementById(panelId);
|
||||
const detachBtn = document.getElementById(detachBtnId);
|
||||
|
||||
if (panel.classList.contains('detached')) {
|
||||
// Re-attach to bottom
|
||||
@@ -1414,111 +1423,14 @@ Object.assign(CodemanApp.prototype, {
|
||||
detachBtn.innerHTML = '⊞'; // Attach icon (squared plus - dock back)
|
||||
detachBtn.title = 'Attach panel';
|
||||
}
|
||||
// Setup drag functionality
|
||||
this.setupMonitorDrag();
|
||||
this._setupPanelDrag(panelId, headerId);
|
||||
}
|
||||
},
|
||||
|
||||
setupMonitorDrag() {
|
||||
const panel = document.getElementById('monitorPanel');
|
||||
const header = document.getElementById('monitorPanelHeader');
|
||||
|
||||
if (!panel || !header) return;
|
||||
|
||||
let isDragging = false;
|
||||
let startX, startY, startLeft, startTop;
|
||||
|
||||
const onStart = (e) => {
|
||||
// Only drag from header, not from buttons
|
||||
if (e.target.closest('button')) return;
|
||||
if (!panel.classList.contains('detached')) return;
|
||||
|
||||
isDragging = true;
|
||||
const coords = getEventCoords(e);
|
||||
startX = coords.clientX;
|
||||
startY = coords.clientY;
|
||||
const rect = panel.getBoundingClientRect();
|
||||
startLeft = rect.left;
|
||||
startTop = rect.top;
|
||||
|
||||
document.addEventListener('mousemove', onMove);
|
||||
document.addEventListener('mouseup', onEnd);
|
||||
document.addEventListener('touchmove', onMove, { passive: false });
|
||||
document.addEventListener('touchend', onEnd);
|
||||
e.preventDefault();
|
||||
};
|
||||
|
||||
const onMove = (e) => {
|
||||
if (!isDragging) return;
|
||||
|
||||
const coords = getEventCoords(e);
|
||||
const dx = coords.clientX - startX;
|
||||
const dy = coords.clientY - startY;
|
||||
|
||||
let newLeft = startLeft + dx;
|
||||
let newTop = startTop + dy;
|
||||
|
||||
// Keep within viewport bounds
|
||||
const rect = panel.getBoundingClientRect();
|
||||
newLeft = Math.max(0, Math.min(window.innerWidth - rect.width, newLeft));
|
||||
newTop = Math.max(0, Math.min(window.innerHeight - rect.height, newTop));
|
||||
|
||||
panel.style.left = newLeft + 'px';
|
||||
panel.style.top = newTop + 'px';
|
||||
};
|
||||
|
||||
const onEnd = () => {
|
||||
isDragging = false;
|
||||
document.removeEventListener('mousemove', onMove);
|
||||
document.removeEventListener('mouseup', onEnd);
|
||||
document.removeEventListener('touchmove', onMove);
|
||||
document.removeEventListener('touchend', onEnd);
|
||||
};
|
||||
|
||||
// Remove existing listeners before adding new ones
|
||||
header.removeEventListener('mousedown', header._dragHandler);
|
||||
header.removeEventListener('touchstart', header._touchDragHandler);
|
||||
header._dragHandler = onStart;
|
||||
header._touchDragHandler = onStart;
|
||||
header.addEventListener('mousedown', onStart);
|
||||
header.addEventListener('touchstart', onStart, { passive: false });
|
||||
},
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Subagents Panel Detach & Drag
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
toggleSubagentsDetach() {
|
||||
const panel = document.getElementById('subagentsPanel');
|
||||
const detachBtn = document.getElementById('subagentsDetachBtn');
|
||||
|
||||
if (panel.classList.contains('detached')) {
|
||||
// Re-attach to bottom
|
||||
panel.classList.remove('detached');
|
||||
panel.style.top = '';
|
||||
panel.style.left = '';
|
||||
panel.style.width = '';
|
||||
panel.style.height = '';
|
||||
if (detachBtn) {
|
||||
detachBtn.innerHTML = '⧉'; // Detach icon
|
||||
detachBtn.title = 'Detach panel';
|
||||
}
|
||||
} else {
|
||||
// Detach as floating window
|
||||
panel.classList.add('detached');
|
||||
panel.classList.add('open'); // Ensure it's visible
|
||||
if (detachBtn) {
|
||||
detachBtn.innerHTML = '⊞'; // Attach icon
|
||||
detachBtn.title = 'Attach panel';
|
||||
}
|
||||
// Setup drag functionality
|
||||
this.setupSubagentsDrag();
|
||||
}
|
||||
},
|
||||
|
||||
setupSubagentsDrag() {
|
||||
const panel = document.getElementById('subagentsPanel');
|
||||
const header = document.getElementById('subagentsPanelHeader');
|
||||
/** Let a detached panel be dragged by its header, kept inside the viewport. */
|
||||
_setupPanelDrag(panelId, headerId) {
|
||||
const panel = document.getElementById(panelId);
|
||||
const header = document.getElementById(headerId);
|
||||
|
||||
if (!panel || !header) return;
|
||||
|
||||
@@ -1668,11 +1580,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Subagent Panel (Claude Code Background Agents)
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
// Legacy alias
|
||||
toggleSubagentPanel() {
|
||||
this.toggleSubagentsPanel();
|
||||
},
|
||||
|
||||
updateSubagentBadge() {
|
||||
const badge = this.$('subagentCountBadge');
|
||||
const activeCount = Array.from(this.subagents.values()).filter(s => s.status === 'active' || s.status === 'idle').length;
|
||||
@@ -2228,16 +2135,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Show window (unless it was minimized by user)
|
||||
if (!windowInfo.minimized) {
|
||||
windowInfo.element.style.display = 'flex';
|
||||
// Lazily re-create teammate terminal if it was disposed when hidden
|
||||
if (windowInfo._lazyTerminal) {
|
||||
this._restoreTeammateTerminalFromLazy(agentId);
|
||||
}
|
||||
}
|
||||
windowInfo.hidden = false;
|
||||
} else {
|
||||
// Hide window (but don't close it)
|
||||
// Dispose teammate terminal to free memory while hidden on inactive tab
|
||||
this._disposeTeammateTerminalForMinimize(agentId);
|
||||
windowInfo.element.style.display = 'none';
|
||||
windowInfo.hidden = true;
|
||||
}
|
||||
@@ -2253,7 +2154,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
// If cleanupData is true, also remove activity and toolResults data to prevent memory leaks
|
||||
closeSessionSubagentWindows(sessionId, cleanupData = false) {
|
||||
const toClose = [];
|
||||
for (const [agentId, _windowData] of this.subagentWindows) {
|
||||
for (const agentId of this.subagentWindows.keys()) {
|
||||
const agent = this.subagents.get(agentId);
|
||||
// Check both subagent parentSessionId and subagentParentMap
|
||||
// (standalone pane windows use subagentParentMap, not subagents map)
|
||||
@@ -2303,36 +2204,12 @@ Object.assign(CodemanApp.prototype, {
|
||||
windowData.element.remove();
|
||||
this.subagentWindows.delete(agentId);
|
||||
}
|
||||
// Clean up teammate terminal if present
|
||||
const termData = this.teammateTerminals.get(agentId);
|
||||
if (termData) {
|
||||
if (termData.resizeObserver) {
|
||||
termData.resizeObserver.disconnect();
|
||||
}
|
||||
if (termData.terminal) {
|
||||
try { termData.terminal.dispose(); } catch {}
|
||||
}
|
||||
this.teammateTerminals.delete(agentId);
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
minimizeSubagentWindow(agentId) {
|
||||
const windowData = this.subagentWindows.get(agentId);
|
||||
if (windowData) {
|
||||
// Dispose teammate terminal on minimize to free DOM/memory (lazy re-creation on restore)
|
||||
this._disposeTeammateTerminalForMinimize(agentId);
|
||||
windowData.element.style.display = 'none';
|
||||
windowData.minimized = true;
|
||||
this.updateConnectionLines();
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
// Debounced wrapper — coalesces rapid subagent events (tool_call, progress,
|
||||
// message) into a single DOM update per 100ms per agent window.
|
||||
scheduleSubagentWindowRender(agentId) {
|
||||
// Skip DOM updates for windows with lazy (disposed) terminals — they're minimized
|
||||
// Skip DOM updates for minimized windows
|
||||
const windowData = this.subagentWindows.get(agentId);
|
||||
if (windowData?.minimized) return;
|
||||
|
||||
@@ -2347,12 +2224,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
},
|
||||
|
||||
renderSubagentWindowContent(agentId) {
|
||||
// Skip if this window has a live terminal (don't overwrite xterm with activity HTML)
|
||||
if (this.teammateTerminals.has(agentId)) return;
|
||||
// Skip if this window has a lazy (disposed) terminal — it will be re-created on restore
|
||||
const windowData = this.subagentWindows.get(agentId);
|
||||
if (windowData?._lazyTerminal) return;
|
||||
|
||||
const body = document.getElementById(`subagent-window-body-${agentId}`);
|
||||
if (!body) return;
|
||||
|
||||
@@ -2500,304 +2371,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
},
|
||||
|
||||
// Open windows for all active subagents
|
||||
openAllActiveSubagentWindows() {
|
||||
for (const [agentId, agent] of this.subagents) {
|
||||
if (agent.status === 'active' && !this.subagentWindows.has(agentId)) {
|
||||
this.openSubagentWindow(agentId);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Agent Teams
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
/** Initialize an xterm.js terminal for a teammate's tmux pane */
|
||||
initTeammateTerminal(agentId, paneInfo, windowElement) {
|
||||
const body = windowElement.querySelector('.subagent-window-body');
|
||||
if (!body) return;
|
||||
|
||||
// Clear the activity log content
|
||||
body.innerHTML = '';
|
||||
body.classList.add('teammate-terminal-body');
|
||||
windowElement.classList.add('has-terminal');
|
||||
|
||||
const sessionId = paneInfo.sessionId;
|
||||
|
||||
// Buffer incoming terminal data until xterm is ready
|
||||
const pendingData = [];
|
||||
this.teammateTerminals.set(agentId, {
|
||||
terminal: null,
|
||||
fitAddon: null,
|
||||
paneTarget: paneInfo.paneTarget,
|
||||
sessionId,
|
||||
resizeObserver: null,
|
||||
pendingData,
|
||||
});
|
||||
|
||||
// Defer terminal creation to next frame so the body element has computed dimensions
|
||||
requestAnimationFrame(() => {
|
||||
// Safety: if window was closed before we got here, bail out
|
||||
if (!document.contains(body)) {
|
||||
this.teammateTerminals.delete(agentId);
|
||||
return;
|
||||
}
|
||||
|
||||
const fontSettings = this.loadAppSettingsFromStorage?.() || {};
|
||||
const terminal = new Terminal({
|
||||
theme: { ...window.codemanCurrentXtermTheme() },
|
||||
minimumContrastRatio: window.codemanCurrentSkinIsLight() ? 4.5 : 1,
|
||||
fontFamily: window.CodemanTerminalFont.resolve(fontSettings.terminalFontFamily),
|
||||
// A pane opened after a weight change must match the main terminal;
|
||||
// one open across the change is repainted by applyTerminalFontWeights().
|
||||
...window.CodemanTerminalFont.resolveWeights(fontSettings),
|
||||
fontSize: 12,
|
||||
lineHeight: 1.2,
|
||||
cursorBlink: true,
|
||||
cursorStyle: 'block',
|
||||
scrollback: DEFAULT_SCROLLBACK,
|
||||
allowTransparency: true,
|
||||
allowProposedApi: true,
|
||||
});
|
||||
|
||||
const fitAddon = new FitAddon.FitAddon();
|
||||
terminal.loadAddon(fitAddon);
|
||||
|
||||
if (typeof Unicode11Addon !== 'undefined') {
|
||||
try {
|
||||
const unicode11Addon = new Unicode11Addon.Unicode11Addon();
|
||||
terminal.loadAddon(unicode11Addon);
|
||||
terminal.unicode.activeVersion = '11';
|
||||
} catch (_e) { /* Unicode11 addon failed */ }
|
||||
}
|
||||
|
||||
try {
|
||||
terminal.open(body);
|
||||
} catch (err) {
|
||||
console.warn('[TeammateTerminal] Failed to open terminal:', err);
|
||||
this.teammateTerminals.delete(agentId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Ctrl+Z (SIGTSTP/job-control suspend): a teammate/subagent pane is always
|
||||
// running an agent CLI (Task-tool dispatched, never a plain shell), so
|
||||
// unlike the main terminal's mode-gated trap this one is unconditional.
|
||||
// Mirrors the main terminal's guard in terminal-ui.js's
|
||||
// attachCustomKeyEventHandler — case-insensitive so Caps Lock (which
|
||||
// flips ev.key to 'Z' without setting shiftKey) can't slip a suspend past it.
|
||||
terminal.attachCustomKeyEventHandler((ev) => {
|
||||
if (
|
||||
ev.type === 'keydown' &&
|
||||
ev.key.toLowerCase() === 'z' &&
|
||||
ev.ctrlKey &&
|
||||
!ev.altKey &&
|
||||
!ev.metaKey &&
|
||||
!ev.shiftKey
|
||||
) {
|
||||
ev.preventDefault();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
// Wait for terminal renderer to fully initialize before any writes.
|
||||
// xterm.js needs a few frames after open() before write() is safe.
|
||||
setTimeout(() => {
|
||||
try { fitAddon.fit(); } catch {}
|
||||
|
||||
// Fetch initial pane buffer
|
||||
fetch(`/api/sessions/${sessionId}/teammate-pane-buffer/${encodeURIComponent(paneInfo.paneTarget)}`)
|
||||
.then(r => r.json())
|
||||
.then(resp => {
|
||||
if (resp.success && resp.data?.buffer) {
|
||||
try { terminal.write(resp.data.buffer); } catch {}
|
||||
}
|
||||
})
|
||||
.catch(err => console.error('[TeammateTerminal] Failed to fetch buffer:', err));
|
||||
|
||||
// Flush any data that arrived while terminal was initializing
|
||||
for (const chunk of pendingData) {
|
||||
try { terminal.write(chunk); } catch {}
|
||||
}
|
||||
pendingData.length = 0;
|
||||
}, 100);
|
||||
|
||||
// Forward keyboard input to the teammate's pane
|
||||
terminal.onData((data) => {
|
||||
fetch(`/api/sessions/${sessionId}/teammate-pane-input`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ paneTarget: paneInfo.paneTarget, input: data }),
|
||||
}).catch(err => console.error('[TeammateTerminal] Failed to send input:', err));
|
||||
});
|
||||
|
||||
// Resize observer to refit terminal when window is resized
|
||||
const resizeObserver = new ResizeObserver(() => {
|
||||
requestAnimationFrame(() => { try { fitAddon.fit(); } catch {} });
|
||||
});
|
||||
resizeObserver.observe(body);
|
||||
|
||||
// Update the stored entry with the real terminal
|
||||
const entry = this.teammateTerminals.get(agentId);
|
||||
if (entry) {
|
||||
entry.terminal = terminal;
|
||||
entry.fitAddon = fitAddon;
|
||||
entry.resizeObserver = resizeObserver;
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
/** Open a standalone terminal window for a tmux-pane teammate (no subagent entry needed) */
|
||||
openTeammateTerminalWindow(paneData) {
|
||||
// Only open if the session has a tab in Codeman
|
||||
if (!this.sessions.has(paneData.sessionId)) return;
|
||||
|
||||
// Use pane target as the unique ID for this window
|
||||
const windowId = `pane-${paneData.paneTarget}`;
|
||||
|
||||
// If window already exists, focus it
|
||||
if (this.subagentWindows.has(windowId)) {
|
||||
const existing = this.subagentWindows.get(windowId);
|
||||
if (existing.hidden) {
|
||||
existing.element.style.display = 'flex';
|
||||
existing.hidden = false;
|
||||
}
|
||||
existing.element.style.zIndex = ++this.subagentWindowZIndex;
|
||||
if (existing.minimized) {
|
||||
this.restoreSubagentWindow(windowId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Calculate position
|
||||
const windowCount = this.subagentWindows.size;
|
||||
const windowWidth = 550;
|
||||
const windowHeight = 400;
|
||||
const gap = 20;
|
||||
const viewportWidth = window.innerWidth;
|
||||
const viewportHeight = window.innerHeight;
|
||||
const startX = 50;
|
||||
const startY = 120;
|
||||
const maxCols = Math.floor((viewportWidth - startX - 50) / (windowWidth + gap)) || 1;
|
||||
const maxRows = Math.floor((viewportHeight - startY - 50) / (windowHeight + gap)) || 1;
|
||||
const col = windowCount % maxCols;
|
||||
const row = Math.floor(windowCount / maxCols) % maxRows;
|
||||
let finalX = startX + col * (windowWidth + gap);
|
||||
let finalY = startY + row * (windowHeight + gap);
|
||||
finalX = Math.max(10, Math.min(finalX, viewportWidth - windowWidth - 10));
|
||||
finalY = Math.max(10, Math.min(finalY, viewportHeight - windowHeight - 10));
|
||||
|
||||
// Color badge
|
||||
const colorClass = paneData.color || 'blue';
|
||||
|
||||
// Create window element
|
||||
const win = document.createElement('div');
|
||||
win.className = 'subagent-window has-terminal';
|
||||
win.id = `subagent-window-${windowId}`;
|
||||
win.style.zIndex = ++this.subagentWindowZIndex;
|
||||
win.style.left = `${finalX}px`;
|
||||
win.style.top = `${finalY}px`;
|
||||
win.style.width = `${windowWidth}px`;
|
||||
win.style.height = `${windowHeight}px`;
|
||||
win.innerHTML = `
|
||||
<div class="subagent-window-header">
|
||||
<div class="subagent-window-title" title="Teammate terminal: ${escapeHtml(paneData.teammateName)} (pane ${paneData.paneTarget})">
|
||||
<span class="icon" style="color: var(--team-color-${colorClass}, #339af0)">⬤</span>
|
||||
<span class="id">${escapeHtml(paneData.teammateName)}</span>
|
||||
<span class="status running">terminal</span>
|
||||
</div>
|
||||
<div class="subagent-window-actions">
|
||||
<button onclick="app.closeSubagentWindow(${escapeHtml(JSON.stringify(windowId))})" title="Minimize to tab">─</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="subagent-window-body teammate-terminal-body" id="subagent-window-body-${windowId}">
|
||||
</div>
|
||||
`;
|
||||
|
||||
document.body.appendChild(win);
|
||||
|
||||
// Make draggable
|
||||
const dragListeners = this.makeWindowDraggable(win, win.querySelector('.subagent-window-header'));
|
||||
|
||||
// Make resizable if method exists
|
||||
if (typeof this.makeWindowResizable === 'function') {
|
||||
this.makeWindowResizable(win);
|
||||
}
|
||||
|
||||
// Check visibility based on active session
|
||||
const settings = this.loadAppSettingsFromStorage();
|
||||
const activeTabOnly = settings.subagentActiveTabOnly ?? true;
|
||||
const shouldHide = activeTabOnly && paneData.sessionId !== this.activeSessionId;
|
||||
|
||||
// Store reference
|
||||
this.subagentWindows.set(windowId, {
|
||||
element: win,
|
||||
minimized: false,
|
||||
hidden: shouldHide,
|
||||
dragListeners,
|
||||
description: `Teammate: ${paneData.teammateName}`,
|
||||
});
|
||||
|
||||
// Also add to subagentParentMap for tab-based visibility
|
||||
this.subagentParentMap.set(windowId, paneData.sessionId);
|
||||
|
||||
if (shouldHide) {
|
||||
win.style.display = 'none';
|
||||
}
|
||||
|
||||
// Focus on click
|
||||
win.addEventListener('mousedown', () => {
|
||||
win.style.zIndex = ++this.subagentWindowZIndex;
|
||||
});
|
||||
|
||||
// Resize observer for connection lines
|
||||
const resizeObserver = new ResizeObserver(() => {
|
||||
this.updateConnectionLines();
|
||||
});
|
||||
resizeObserver.observe(win);
|
||||
this.subagentWindows.get(windowId).resizeObserver = resizeObserver;
|
||||
|
||||
// Init the xterm.js terminal (lazy if hidden)
|
||||
if (shouldHide) {
|
||||
// Window starts hidden — defer terminal creation until visible (lazy init)
|
||||
const windowEntry = this.subagentWindows.get(windowId);
|
||||
if (windowEntry) {
|
||||
windowEntry._lazyTerminal = true;
|
||||
windowEntry._lazyPaneTarget = paneData.paneTarget;
|
||||
windowEntry._lazySessionId = paneData.sessionId;
|
||||
}
|
||||
} else {
|
||||
this.initTeammateTerminal(windowId, paneData, win);
|
||||
}
|
||||
|
||||
// Animate in
|
||||
requestAnimationFrame(() => {
|
||||
win.style.transition = 'transform 0.3s ease, opacity 0.3s ease';
|
||||
win.style.transform = 'scale(1)';
|
||||
win.style.opacity = '1';
|
||||
});
|
||||
},
|
||||
|
||||
/** Rebuild the teammate lookup map from all team configs */
|
||||
rebuildTeammateMap() {
|
||||
this.teammateMap.clear();
|
||||
for (const [teamName, team] of this.teams) {
|
||||
for (const member of team.members) {
|
||||
if (member.agentType !== 'team-lead') {
|
||||
// Use name as key prefix for matching subagent descriptions
|
||||
this.teammateMap.set(member.name, {
|
||||
name: member.name,
|
||||
color: member.color || 'blue',
|
||||
teamName,
|
||||
agentId: member.agentId,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/** Check if a subagent is a teammate and return its info */
|
||||
getTeammateInfo(agent) {
|
||||
if (!agent?.description) return null;
|
||||
@@ -2807,7 +2385,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
const teammateId = match[1];
|
||||
// Extract name from teammate_id (format: name@teamName)
|
||||
const name = teammateId.split('@')[0];
|
||||
return this.teammateMap.get(name) || { name, color: 'blue', teamName: 'unknown' };
|
||||
return { name, color: 'blue', teamName: 'unknown' };
|
||||
},
|
||||
|
||||
/** Get teammate badge HTML for a subagent */
|
||||
@@ -2817,117 +2395,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
return `<span class="teammate-badge teammate-color-${info.color}" title="Team: ${escapeHtml(info.teamName)}">@${escapeHtml(info.name)}</span>`;
|
||||
},
|
||||
|
||||
/** Render the team tasks panel */
|
||||
renderTeamTasksPanel() {
|
||||
const panel = document.getElementById('teamTasksPanel');
|
||||
if (!panel) return;
|
||||
|
||||
// Find team for active session
|
||||
let activeTeam = null;
|
||||
let activeTeamName = null;
|
||||
if (this.activeSessionId) {
|
||||
for (const [name, team] of this.teams) {
|
||||
if (team.leadSessionId === this.activeSessionId) {
|
||||
activeTeam = team;
|
||||
activeTeamName = name;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!activeTeam) {
|
||||
panel.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
// Set initial position and make draggable on first show
|
||||
const wasHidden = panel.style.display === 'none';
|
||||
panel.style.display = 'flex';
|
||||
|
||||
if (wasHidden && !this.teamTasksDragListeners) {
|
||||
// Position bottom-right
|
||||
const panelWidth = 360;
|
||||
const panelHeight = 300;
|
||||
panel.style.left = `${Math.max(10, window.innerWidth - panelWidth - 20)}px`;
|
||||
panel.style.top = `${Math.max(10, window.innerHeight - panelHeight - 70)}px`;
|
||||
// Make draggable
|
||||
const header = panel.querySelector('.team-tasks-header');
|
||||
if (header) {
|
||||
this.teamTasksDragListeners = this.makeWindowDraggable(panel, header);
|
||||
}
|
||||
}
|
||||
|
||||
const tasks = this.teamTasks.get(activeTeamName) || [];
|
||||
const completed = tasks.filter(t => t.status === 'completed').length;
|
||||
const total = tasks.length;
|
||||
const pct = total > 0 ? Math.round((completed / total) * 100) : 0;
|
||||
|
||||
const headerEl = panel.querySelector('.team-tasks-header-text');
|
||||
if (headerEl) {
|
||||
const teammateCount = activeTeam.members.filter(m => m.agentType !== 'team-lead').length;
|
||||
headerEl.textContent = `Team Tasks (${teammateCount} teammates)`;
|
||||
}
|
||||
|
||||
const progressEl = panel.querySelector('.team-tasks-progress-fill');
|
||||
if (progressEl) {
|
||||
progressEl.style.width = `${pct}%`;
|
||||
}
|
||||
|
||||
const progressText = panel.querySelector('.team-tasks-progress-text');
|
||||
if (progressText) {
|
||||
progressText.textContent = `${completed}/${total}`;
|
||||
}
|
||||
|
||||
const listEl = panel.querySelector('.team-tasks-list');
|
||||
if (!listEl) return;
|
||||
|
||||
if (tasks.length === 0) {
|
||||
listEl.innerHTML = '<div class="team-task-empty">No tasks yet</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
const html = tasks.map(task => {
|
||||
const statusIcon = task.status === 'completed' ? '✓' : task.status === 'in_progress' ? '◉' : '○';
|
||||
const statusClass = task.status.replace('_', '-');
|
||||
const ownerBadge = task.owner
|
||||
? `<span class="team-task-owner teammate-color-${this.getTeammateColor(task.owner)}">${escapeHtml(task.owner)}</span>`
|
||||
: '';
|
||||
return `<div class="team-task-item ${statusClass}">
|
||||
<span class="team-task-status">${statusIcon}</span>
|
||||
<span class="team-task-subject">${escapeHtml(task.subject)}</span>
|
||||
${ownerBadge}
|
||||
</div>`;
|
||||
}).join('');
|
||||
|
||||
listEl.innerHTML = html;
|
||||
},
|
||||
|
||||
/** Hide team tasks panel and clean up drag listeners */
|
||||
hideTeamTasksPanel() {
|
||||
const panel = document.getElementById('teamTasksPanel');
|
||||
if (panel) panel.style.display = 'none';
|
||||
if (this.teamTasksDragListeners) {
|
||||
document.removeEventListener('mousemove', this.teamTasksDragListeners.move);
|
||||
document.removeEventListener('mouseup', this.teamTasksDragListeners.up);
|
||||
if (this.teamTasksDragListeners.touchMove) {
|
||||
document.removeEventListener('touchmove', this.teamTasksDragListeners.touchMove);
|
||||
document.removeEventListener('touchend', this.teamTasksDragListeners.up);
|
||||
document.removeEventListener('touchcancel', this.teamTasksDragListeners.up);
|
||||
}
|
||||
if (this.teamTasksDragListeners.handle) {
|
||||
this.teamTasksDragListeners.handle.removeEventListener('mousedown', this.teamTasksDragListeners.handleMouseDown);
|
||||
this.teamTasksDragListeners.handle.removeEventListener('touchstart', this.teamTasksDragListeners.handleTouchStart);
|
||||
}
|
||||
this.teamTasksDragListeners = null;
|
||||
}
|
||||
},
|
||||
|
||||
/** Get teammate color by name */
|
||||
getTeammateColor(name) {
|
||||
const info = this.teammateMap.get(name);
|
||||
return info?.color || 'blue';
|
||||
},
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Project Insights Panel (Bash Tools with Clickable File Paths)
|
||||
@@ -3038,37 +2505,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
return false;
|
||||
},
|
||||
|
||||
/**
|
||||
* Pick the "better" of two paths that resolve to the same file.
|
||||
* Prefers paths inside the case folder, longer/more explicit paths, and absolute paths.
|
||||
*/
|
||||
pickBetterPath(path1, path2, workingDir) {
|
||||
// Prefer paths inside the case folder (working directory)
|
||||
if (workingDir) {
|
||||
const inWorkDir1 = this.isPathInWorkingDir(path1, workingDir);
|
||||
const inWorkDir2 = this.isPathInWorkingDir(path2, workingDir);
|
||||
if (inWorkDir1 && !inWorkDir2) return path1;
|
||||
if (inWorkDir2 && !inWorkDir1) return path2;
|
||||
}
|
||||
|
||||
// Prefer absolute paths
|
||||
const abs1 = path1.startsWith('/');
|
||||
const abs2 = path2.startsWith('/');
|
||||
if (abs1 && !abs2) return path1;
|
||||
if (abs2 && !abs1) return path2;
|
||||
|
||||
// Both absolute or both relative - prefer longer (more explicit)
|
||||
if (path1.length !== path2.length) {
|
||||
return path1.length > path2.length ? path1 : path2;
|
||||
}
|
||||
|
||||
// Prefer paths without ~
|
||||
if (!path1.includes('~') && path2.includes('~')) return path1;
|
||||
if (!path2.includes('~') && path1.includes('~')) return path2;
|
||||
|
||||
return path1;
|
||||
},
|
||||
|
||||
/**
|
||||
* Deduplicate file paths across all tools, keeping the "best" version.
|
||||
* Uses smart equivalence checking:
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
/**
|
||||
* @fileoverview Ralph state panel (progress ring, status, task cards, fix_plan.md integration),
|
||||
* plan versioning (checkpoint, rollback, diff), and plan wizard agents in monitor.
|
||||
* Includes 11 SSE handlers for Ralph and plan events.
|
||||
* and plan versioning (checkpoint, rollback, diff). Includes the SSE handlers for Ralph events.
|
||||
*
|
||||
* @mixin Extends CodemanApp.prototype via Object.assign
|
||||
* @dependency app.js (CodemanApp class, this.ralphStates, this.activeSessionId)
|
||||
@@ -68,64 +67,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
this._notifySession(data.sessionId, 'warning', 'exit-gate', 'Exit Gate Met', `Loop ready to exit (indicators: ${data.completionIndicators})`);
|
||||
},
|
||||
|
||||
// Bash tools
|
||||
|
||||
// Plan orchestration
|
||||
_onPlanSubagent(data) {
|
||||
console.log('[Plan Subagent]', data);
|
||||
this.handlePlanSubagentEvent(data);
|
||||
},
|
||||
|
||||
_onPlanProgress(data) {
|
||||
console.log('[Plan Progress]', data);
|
||||
|
||||
// Update UI if we have a progress handler registered
|
||||
if (this._planProgressHandler) {
|
||||
this._planProgressHandler({ type: 'plan:progress', data });
|
||||
}
|
||||
|
||||
// Also update the loading display directly for better feedback
|
||||
const titleEl = document.getElementById('planLoadingTitle');
|
||||
const hintEl = document.getElementById('planLoadingHint');
|
||||
|
||||
if (titleEl && data.phase) {
|
||||
const phaseLabels = {
|
||||
'parallel-analysis': 'Running parallel analysis...',
|
||||
'subagent': data.detail || 'Subagent working...',
|
||||
'synthesis': 'Synthesizing results...',
|
||||
'verification': 'Running verification...',
|
||||
};
|
||||
titleEl.textContent = phaseLabels[data.phase] || data.phase;
|
||||
}
|
||||
if (hintEl && data.detail) {
|
||||
hintEl.textContent = data.detail;
|
||||
}
|
||||
},
|
||||
|
||||
_onPlanStarted(data) {
|
||||
console.log('[Plan Started]', data);
|
||||
this.activePlanOrchestratorId = data.orchestratorId;
|
||||
this.planGenerationStopped = false; // Reset flag for new generation
|
||||
this.renderMonitorPlanAgents();
|
||||
},
|
||||
|
||||
_onPlanCancelled(data) {
|
||||
console.log('[Plan Cancelled]', data);
|
||||
if (this.activePlanOrchestratorId === data.orchestratorId) {
|
||||
this.activePlanOrchestratorId = null;
|
||||
}
|
||||
this.renderMonitorPlanAgents();
|
||||
},
|
||||
|
||||
_onPlanCompleted(data) {
|
||||
console.log('[Plan Completed]', data);
|
||||
if (this.activePlanOrchestratorId === data.orchestratorId) {
|
||||
this.activePlanOrchestratorId = null;
|
||||
}
|
||||
this.renderMonitorPlanAgents();
|
||||
},
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Enhanced Ralph Wiggum Loop Panel
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
@@ -953,11 +894,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
},
|
||||
|
||||
// Legacy method for backwards compatibility
|
||||
getTodoIcon(status) {
|
||||
return this.getRalphTaskIcon(status);
|
||||
},
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Plan Versioning
|
||||
@@ -1100,91 +1036,4 @@ Object.assign(CodemanApp.prototype, {
|
||||
if (hours < 24) return `${hours}h ago`;
|
||||
return `${days}d ago`;
|
||||
},
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Plan Wizard Agents in Monitor
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
renderMonitorPlanAgents() {
|
||||
const section = document.getElementById('monitorPlanAgentsSection');
|
||||
const body = document.getElementById('monitorPlanAgentsBody');
|
||||
const stats = document.getElementById('monitorPlanAgentStats');
|
||||
if (!section || !body) return;
|
||||
|
||||
const planAgents = Array.from(this.planSubagents?.values() || []);
|
||||
const hasActiveOrchestrator = !!this.activePlanOrchestratorId;
|
||||
|
||||
// Show section only if there are plan agents or active orchestrator
|
||||
if (planAgents.length === 0 && !hasActiveOrchestrator) {
|
||||
section.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
section.style.display = '';
|
||||
|
||||
const activeCount = planAgents.filter(a => a.status === 'running').length;
|
||||
const completedCount = planAgents.filter(a => a.status === 'completed' || a.status === 'failed').length;
|
||||
|
||||
if (stats) {
|
||||
if (hasActiveOrchestrator) {
|
||||
stats.textContent = `${activeCount} running, ${completedCount} done`;
|
||||
} else {
|
||||
stats.textContent = `${planAgents.length} total`;
|
||||
}
|
||||
}
|
||||
|
||||
if (planAgents.length === 0) {
|
||||
body.innerHTML = `<div class="monitor-empty">${hasActiveOrchestrator ? 'Plan generation starting...' : 'No plan agents'}</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
let html = '';
|
||||
for (const agent of planAgents) {
|
||||
const statusClass = agent.status === 'running' ? 'active' : agent.status === 'completed' ? 'completed' : 'error';
|
||||
const agentLabel = agent.agentType || agent.agentId;
|
||||
const modelBadge = agent.model ? `<span class="model-badge opus">opus</span>` : '';
|
||||
const detail = agent.detail ? escapeHtml(agent.detail.substring(0, 50)) : '';
|
||||
const duration = agent.durationMs ? `${(agent.durationMs / 1000).toFixed(1)}s` : '';
|
||||
const itemCount = agent.itemCount ? `${agent.itemCount} items` : '';
|
||||
|
||||
html += `
|
||||
<div class="process-item">
|
||||
<span class="process-mode ${statusClass}">${agent.status || 'pending'}</span>
|
||||
<div class="process-info">
|
||||
<div class="process-name">${modelBadge} ${escapeHtml(agentLabel)}</div>
|
||||
<div class="process-meta">
|
||||
${detail ? `<span>${detail}</span>` : ''}
|
||||
${itemCount ? `<span>${itemCount}</span>` : ''}
|
||||
${duration ? `<span>${duration}</span>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
body.innerHTML = html;
|
||||
},
|
||||
|
||||
async cancelPlanFromMonitor() {
|
||||
if (!this.activePlanOrchestratorId && this.planSubagents?.size === 0) {
|
||||
this.showToast('No active plan generation', 'info');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!confirm('Cancel plan generation and close all plan agent windows?')) return;
|
||||
|
||||
// Cancel the plan generation (reuse existing method)
|
||||
await this.cancelPlanGeneration();
|
||||
|
||||
// Also force close the wizard if it's open
|
||||
const wizardModal = document.getElementById('ralphWizardModal');
|
||||
if (wizardModal?.classList.contains('active')) {
|
||||
this.closeRalphWizard();
|
||||
}
|
||||
|
||||
// Update monitor display
|
||||
this.renderMonitorPlanAgents();
|
||||
this.showToast('Plan generation cancelled', 'success');
|
||||
},
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -731,20 +731,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
this.showToast(`Saved preset: ${name}`, 'success');
|
||||
},
|
||||
|
||||
deletePreset(presetId) {
|
||||
const presets = this.loadRespawnPresets();
|
||||
const preset = presets.find(p => p.id === presetId);
|
||||
if (!preset || preset.builtIn) {
|
||||
this.showToast('Cannot delete built-in presets', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
const filtered = presets.filter(p => p.id !== presetId);
|
||||
this.saveRespawnPresets(filtered);
|
||||
this.renderPresetDropdown();
|
||||
this.showToast(`Deleted preset: ${preset.name}`, 'success');
|
||||
},
|
||||
|
||||
// Get respawn config from modal inputs
|
||||
getModalRespawnConfig() {
|
||||
const updatePrompt = document.getElementById('modalRespawnPrompt').value;
|
||||
@@ -947,13 +933,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
await this.loadRunSummary(sessionId);
|
||||
},
|
||||
|
||||
closeRunSummary() {
|
||||
this.runSummarySessionId = null;
|
||||
this.stopRunSummaryAutoRefresh();
|
||||
// Close session options modal (summary is now a tab in it)
|
||||
this.closeSessionOptions();
|
||||
},
|
||||
|
||||
async refreshRunSummary() {
|
||||
const sessionId = this.runSummarySessionId || this.editingSessionId;
|
||||
if (!sessionId) return;
|
||||
@@ -1074,7 +1053,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
renderRunSummary() {
|
||||
if (!this.runSummaryData) return;
|
||||
|
||||
const { stats, events, sessionName, startedAt, lastUpdatedAt } = this.runSummaryData;
|
||||
const { events, sessionName, startedAt, lastUpdatedAt } = this.runSummaryData;
|
||||
|
||||
// Update session info
|
||||
const duration = lastUpdatedAt - startedAt;
|
||||
@@ -1175,10 +1154,4 @@ Object.assign(CodemanApp.prototype, {
|
||||
if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
|
||||
return `${seconds}s`;
|
||||
},
|
||||
|
||||
saveSessionOptions() {
|
||||
// Session options are applied immediately via individual controls
|
||||
// This just closes the modal
|
||||
this.closeSessionOptions();
|
||||
},
|
||||
});
|
||||
@@ -8,7 +8,7 @@
|
||||
* @dependency app.js (CodemanApp class, this.sessions, this.cases, this.activeSessionId)
|
||||
* @dependency constants.js (escapeHtml)
|
||||
* @dependency mobile-handlers.js (MobileDetection)
|
||||
* @loadorder 12 of 15 — loaded after panels-ui.js, before ralph-wizard.js
|
||||
* @loadorder 12 of 15 — loaded after panels-ui.js, before api-client.js
|
||||
*/
|
||||
|
||||
/**
|
||||
@@ -21,13 +21,12 @@
|
||||
* own no-id-branching rule exists to prevent server-side.
|
||||
*
|
||||
* Deliberately a LOCAL table rather than a server-injected catalogue: several
|
||||
* unit tests exercise these run*() methods inside a bare `vm.createContext()`
|
||||
* unit tests exercise the launcher inside a bare `vm.createContext()`
|
||||
* sandbox with no `window` global at all (see test/run-mode-ui.test.ts) —
|
||||
* referencing `window` there unguarded would throw, not degrade. `buildConfig`
|
||||
* returns the CLI's top-level legacy config field for a LOCAL launch, or
|
||||
* `null` for a CLI that sends none (pi: no bypass flag exists, so there is
|
||||
* nothing to send — see runPi's own history below for why that must stay
|
||||
* true).
|
||||
* nothing to send, and that must stay true).
|
||||
*/
|
||||
const RUN_MODE_LAUNCH = {
|
||||
opencode: {
|
||||
@@ -677,10 +676,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
return this._caseSyncChain;
|
||||
},
|
||||
|
||||
async quickStart() {
|
||||
return this.run();
|
||||
},
|
||||
|
||||
/** Ensure a newly-created session is visible without waiting for the SSE event.
|
||||
* The POST response and session:created can arrive in either order, so the
|
||||
* normal idempotent SSE handler remains the single state-upsert path.
|
||||
@@ -2484,7 +2479,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
if (remoteIds[0]) {
|
||||
// Don't pre-set activeSessionId — selectSession early-returns when the
|
||||
// IDs match, skipping the buffer load, tab activation, and focus (see runCodex).
|
||||
// IDs match, skipping the buffer load, tab activation, and focus (see _runCliMode).
|
||||
await this.selectSession(remoteIds[0]);
|
||||
}
|
||||
this.terminal.focus();
|
||||
@@ -2536,7 +2531,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
|
||||
// Switch to first session. Don't pre-set activeSessionId — selectSession
|
||||
// early-returns when the IDs match, skipping the buffer load, tab
|
||||
// activation, and focus (see runCodex), which left the new shell tab
|
||||
// activation, and focus (see _runCliMode), which left the new shell tab
|
||||
// created but not shown until the user manually clicked it.
|
||||
if (sessionIds.length > 0) {
|
||||
await this.selectSession(sessionIds[0]);
|
||||
@@ -2601,10 +2596,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
* Shared launcher for every RUN_MODE_LAUNCH entry (every run mode except
|
||||
* claude/shell, which have their own flows — claude for its remote/docker
|
||||
* branching and parallel-create path, shell for needing no CLI probe at
|
||||
* all). The eight run<Mode>() methods below are thin named wrappers: their
|
||||
* names stay because index.html's welcome-screen buttons and the run-mode
|
||||
* menu call them directly by name (`app.runOpenCode()` etc.), and several
|
||||
* tests assert on that name directly too.
|
||||
* all). `run()` reaches it for every mode in the table; there is no per-CLI
|
||||
* wrapper method any more.
|
||||
*/
|
||||
async _runCliMode(mode, options = {}) {
|
||||
const catalogEntry = registryCliById(mode);
|
||||
@@ -2690,46 +2683,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
},
|
||||
|
||||
async runOpenCode() {
|
||||
return this._runCliMode('opencode');
|
||||
},
|
||||
|
||||
async runCodex() {
|
||||
return this._runCliMode('codex');
|
||||
},
|
||||
|
||||
async runGemini() {
|
||||
return this._runCliMode('gemini');
|
||||
},
|
||||
|
||||
async runAntigravity() {
|
||||
return this._runCliMode('antigravity');
|
||||
},
|
||||
|
||||
async runPi() {
|
||||
return this._runCliMode('pi');
|
||||
},
|
||||
|
||||
async runOmp() {
|
||||
return this._runCliMode('omp');
|
||||
},
|
||||
|
||||
async runGrok() {
|
||||
return this._runCliMode('grok');
|
||||
},
|
||||
|
||||
async runDeepSeek() {
|
||||
return this._runCliMode('deepseek');
|
||||
},
|
||||
|
||||
async runCopilot() {
|
||||
return this._runCliMode('copilot');
|
||||
},
|
||||
|
||||
async runJcode() {
|
||||
return this._runCliMode('jcode');
|
||||
},
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Session Options Modal
|
||||
|
||||
@@ -5455,14 +5455,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the parent session ID for an agent from the persistent map.
|
||||
* This is the ONLY source of truth for connection lines.
|
||||
*/
|
||||
getAgentParentSessionId(agentId) {
|
||||
return this.subagentParentMap.get(agentId) || null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Set and persist the parent session ID for an agent.
|
||||
* Once set, this association is PERMANENT and never recalculated.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -243,11 +243,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
const svg = document.getElementById('connectionLines');
|
||||
if (!svg) return;
|
||||
|
||||
// Check if Ralph wizard modal is open
|
||||
const wizardModal = document.getElementById('ralphWizardModal');
|
||||
const wizardOpen = wizardModal?.classList.contains('active');
|
||||
const wizardContent = wizardOpen ? wizardModal.querySelector('.modal-content') : null;
|
||||
|
||||
// Collect visible regular subagent windows
|
||||
const visibleSubagentWindows = [];
|
||||
for (const [agentId, windowInfo] of this.subagentWindows) {
|
||||
@@ -257,11 +252,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
visibleSubagentWindows.push({ agentId, windowInfo, win });
|
||||
}
|
||||
|
||||
// Get plan subagent windows as array for distribution
|
||||
const planSubagentArray = Array.from(this.planSubagents.entries())
|
||||
.filter(([, data]) => data.element)
|
||||
.map(([id, data]) => ({ id, ...data }));
|
||||
|
||||
// === PHASE 1: Batch all layout reads (getBoundingClientRect) ===
|
||||
// Reading layout properties forces the browser to calculate layout.
|
||||
// By batching all reads before any writes, we avoid repeated forced reflows.
|
||||
@@ -272,36 +262,14 @@ Object.assign(CodemanApp.prototype, {
|
||||
rects.set('sub:' + agentId, win.getBoundingClientRect());
|
||||
}
|
||||
|
||||
// Read all plan subagent rects
|
||||
for (const planAgent of planSubagentArray) {
|
||||
rects.set('plan:' + planAgent.id, planAgent.element.getBoundingClientRect());
|
||||
}
|
||||
|
||||
// Read wizard rect (if open)
|
||||
let wizardRect = null;
|
||||
if (wizardOpen && wizardContent) {
|
||||
wizardRect = wizardContent.getBoundingClientRect();
|
||||
}
|
||||
|
||||
// Read tab rects for normal mode (only tabs that are actually needed).
|
||||
// Read tab rects (only tabs that are actually needed).
|
||||
// Only a painted row is cached: a row a search or filter hid has no line
|
||||
// (_paintedSessionTab), rather than one drawn from the viewport's corner.
|
||||
if (!wizardOpen) {
|
||||
for (const { agentId } of visibleSubagentWindows) {
|
||||
const parentSessionId = this.subagentParentMap.get(agentId);
|
||||
if (!parentSessionId || rects.has('tab:' + parentSessionId)) continue;
|
||||
const tab = this._paintedSessionTab(parentSessionId);
|
||||
if (tab) rects.set('tab:' + parentSessionId, tab.getBoundingClientRect());
|
||||
}
|
||||
}
|
||||
|
||||
// Read plan window rects for wizard-to-plan lines
|
||||
if (wizardOpen && wizardContent && this.planSubagents.size > 0 && !this.planAgentsMinimized) {
|
||||
for (const [agentId, windowData] of this.planSubagents) {
|
||||
if (!windowData.element) continue;
|
||||
const key = 'planwin:' + agentId;
|
||||
if (!rects.has(key)) rects.set(key, windowData.element.getBoundingClientRect());
|
||||
}
|
||||
for (const { agentId } of visibleSubagentWindows) {
|
||||
const parentSessionId = this.subagentParentMap.get(agentId);
|
||||
if (!parentSessionId || rects.has('tab:' + parentSessionId)) continue;
|
||||
const tab = this._paintedSessionTab(parentSessionId);
|
||||
if (tab) rects.set('tab:' + parentSessionId, tab.getBoundingClientRect());
|
||||
}
|
||||
|
||||
// === PHASE 2: DOM writes using cached rects (no more layout reads) ===
|
||||
@@ -310,149 +278,34 @@ Object.assign(CodemanApp.prototype, {
|
||||
for (const { agentId } of visibleSubagentWindows) {
|
||||
const winRect = rects.get('sub:' + agentId);
|
||||
|
||||
// If wizard is open with plan subagents, connect regular subagents to plan subagent windows
|
||||
if (wizardOpen && wizardContent && planSubagentArray.length > 0) {
|
||||
// Find the nearest plan subagent window to connect to
|
||||
let nearestPlanAgent = null;
|
||||
let nearestDistance = Infinity;
|
||||
// Connect the agent window to its parent TAB.
|
||||
// Use the PERSISTENT subagentParentMap as the ONLY source of truth
|
||||
const parentSessionId = this.subagentParentMap.get(agentId);
|
||||
|
||||
for (const planAgent of planSubagentArray) {
|
||||
const planRect = rects.get('plan:' + planAgent.id);
|
||||
const planCenterX = planRect.left + planRect.width / 2;
|
||||
const planCenterY = planRect.top + planRect.height / 2;
|
||||
const winCenterX = winRect.left + winRect.width / 2;
|
||||
const winCenterY = winRect.top + winRect.height / 2;
|
||||
const distance = Math.hypot(planCenterX - winCenterX, planCenterY - winCenterY);
|
||||
|
||||
if (distance < nearestDistance) {
|
||||
nearestDistance = distance;
|
||||
nearestPlanAgent = planAgent;
|
||||
}
|
||||
}
|
||||
|
||||
if (nearestPlanAgent) {
|
||||
const planRect = rects.get('plan:' + nearestPlanAgent.id);
|
||||
|
||||
// Draw line from plan subagent window to regular subagent window
|
||||
let x1, y1, x2, y2;
|
||||
const planCenterX = planRect.left + planRect.width / 2;
|
||||
const winCenterX = winRect.left + winRect.width / 2;
|
||||
|
||||
if (winCenterX < planCenterX) {
|
||||
x1 = planRect.left;
|
||||
y1 = planRect.top + planRect.height / 2;
|
||||
x2 = winRect.right;
|
||||
y2 = winRect.top + winRect.height / 2;
|
||||
} else {
|
||||
x1 = planRect.right;
|
||||
y1 = planRect.top + planRect.height / 2;
|
||||
x2 = winRect.left;
|
||||
y2 = winRect.top + winRect.height / 2;
|
||||
}
|
||||
|
||||
const midX = (x1 + x2) / 2;
|
||||
const path = `M ${x1} ${y1} C ${midX} ${y1}, ${midX} ${y2}, ${x2} ${y2}`;
|
||||
|
||||
const line = document.createElementNS('http://www.w3.org/2000/svg', 'path');
|
||||
line.setAttribute('d', path);
|
||||
line.setAttribute('class', 'connection-line plan-to-subagent-line');
|
||||
line.setAttribute('data-agent-id', agentId);
|
||||
line.setAttribute('data-plan-agent-id', nearestPlanAgent.id);
|
||||
svg.appendChild(line);
|
||||
}
|
||||
} else if (wizardOpen && wizardContent) {
|
||||
// Wizard open but no plan subagents - connect directly to wizard
|
||||
const winCenterX = winRect.left + winRect.width / 2;
|
||||
const wizardCenterX = wizardRect.left + wizardRect.width / 2;
|
||||
|
||||
let x1, y1, x2, y2;
|
||||
|
||||
if (winCenterX < wizardCenterX) {
|
||||
x1 = wizardRect.left;
|
||||
y1 = wizardRect.top + wizardRect.height / 2;
|
||||
x2 = winRect.right;
|
||||
y2 = winRect.top + winRect.height / 2;
|
||||
} else {
|
||||
x1 = wizardRect.right;
|
||||
y1 = wizardRect.top + wizardRect.height / 2;
|
||||
x2 = winRect.left;
|
||||
y2 = winRect.top + winRect.height / 2;
|
||||
}
|
||||
|
||||
const midX = (x1 + x2) / 2;
|
||||
const path = `M ${x1} ${y1} C ${midX} ${y1}, ${midX} ${y2}, ${x2} ${y2}`;
|
||||
|
||||
const line = document.createElementNS('http://www.w3.org/2000/svg', 'path');
|
||||
line.setAttribute('d', path);
|
||||
line.setAttribute('class', 'connection-line wizard-connection');
|
||||
line.setAttribute('data-agent-id', agentId);
|
||||
svg.appendChild(line);
|
||||
} else {
|
||||
// NORMAL MODE: Connect agent window to its parent TAB
|
||||
// Use the PERSISTENT subagentParentMap as the ONLY source of truth
|
||||
const parentSessionId = this.subagentParentMap.get(agentId);
|
||||
|
||||
if (!parentSessionId) {
|
||||
// No parent known yet - skip this agent
|
||||
continue;
|
||||
}
|
||||
|
||||
const tabRect = rects.get('tab:' + parentSessionId);
|
||||
if (!tabRect) {
|
||||
// Tab not painted (session closed, collapsed group, or hidden by a search)
|
||||
continue;
|
||||
}
|
||||
|
||||
// Draw a curved line from the tab to the window. Header strip: tab
|
||||
// bottom-center → window top-center (vertical). Sidebar: tab right-edge →
|
||||
// window left-edge (horizontal), otherwise the curve loops backwards
|
||||
// underneath the sidebar. _tabAnchor/_tabConnectorPath live in app.js.
|
||||
const anchor = this._tabAnchor(tabRect);
|
||||
const path = this._tabConnectorPath(anchor, winRect);
|
||||
|
||||
const line = document.createElementNS('http://www.w3.org/2000/svg', 'path');
|
||||
line.setAttribute('d', path);
|
||||
line.setAttribute('class', 'connection-line');
|
||||
line.setAttribute('data-agent-id', agentId);
|
||||
line.setAttribute('data-parent-tab', parentSessionId);
|
||||
svg.appendChild(line);
|
||||
if (!parentSessionId) {
|
||||
// No parent known yet - skip this agent
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Draw lines from wizard to plan subagent windows (Opus agents during plan generation)
|
||||
// Skip if agents are minimized to tab
|
||||
if (wizardOpen && wizardContent && this.planSubagents.size > 0 && !this.planAgentsMinimized) {
|
||||
for (const [agentId] of this.planSubagents) {
|
||||
const winRect = rects.get('planwin:' + agentId);
|
||||
if (!winRect) continue;
|
||||
|
||||
// Determine which side of wizard the window is on
|
||||
const winCenterX = winRect.left + winRect.width / 2;
|
||||
const wizardCenterX = wizardRect.left + wizardRect.width / 2;
|
||||
|
||||
let x1, y1, x2, y2;
|
||||
|
||||
if (winCenterX < wizardCenterX) {
|
||||
x1 = wizardRect.left;
|
||||
y1 = wizardRect.top + wizardRect.height / 3 + (this.planSubagents.size > 3 ? 0 : 50);
|
||||
x2 = winRect.right;
|
||||
y2 = winRect.top + winRect.height / 2;
|
||||
} else {
|
||||
x1 = wizardRect.right;
|
||||
y1 = wizardRect.top + wizardRect.height / 3 + (this.planSubagents.size > 3 ? 0 : 50);
|
||||
x2 = winRect.left;
|
||||
y2 = winRect.top + winRect.height / 2;
|
||||
}
|
||||
|
||||
const midX = (x1 + x2) / 2;
|
||||
const path = `M ${x1} ${y1} C ${midX} ${y1}, ${midX} ${y2}, ${x2} ${y2}`;
|
||||
|
||||
const line = document.createElementNS('http://www.w3.org/2000/svg', 'path');
|
||||
line.setAttribute('d', path);
|
||||
line.setAttribute('class', 'connection-line wizard-connection plan-subagent-line');
|
||||
line.setAttribute('data-plan-agent-id', agentId);
|
||||
svg.appendChild(line);
|
||||
const tabRect = rects.get('tab:' + parentSessionId);
|
||||
if (!tabRect) {
|
||||
// Tab not painted (session closed, collapsed group, or hidden by a search)
|
||||
continue;
|
||||
}
|
||||
|
||||
// Draw a curved line from the tab to the window. Header strip: tab
|
||||
// bottom-center → window top-center (vertical). Sidebar: tab right-edge →
|
||||
// window left-edge (horizontal), otherwise the curve loops backwards
|
||||
// underneath the sidebar. _tabAnchor/_tabConnectorPath live in app.js.
|
||||
const anchor = this._tabAnchor(tabRect);
|
||||
const path = this._tabConnectorPath(anchor, winRect);
|
||||
|
||||
const line = document.createElementNS('http://www.w3.org/2000/svg', 'path');
|
||||
line.setAttribute('d', path);
|
||||
line.setAttribute('class', 'connection-line');
|
||||
line.setAttribute('data-agent-id', agentId);
|
||||
line.setAttribute('data-parent-tab', parentSessionId);
|
||||
svg.appendChild(line);
|
||||
}
|
||||
|
||||
// Ultracode floating run windows → parent tab (additional layer, ultracode-windows.js).
|
||||
@@ -475,83 +328,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
this._applyLineEntrances?.(svg);
|
||||
},
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Lazy Terminal Lifecycle
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
//
|
||||
// Teammate terminal windows use xterm.js Terminal instances that consume
|
||||
// ~75KB of DOM memory each. With 50 agents minimized, that's ~3.75MB of
|
||||
// invisible terminals. To avoid this, we dispose the Terminal when a
|
||||
// window is minimized and lazily re-create it when restored.
|
||||
//
|
||||
// Flow:
|
||||
// minimize → _disposeTeammateTerminalForMinimize() → sets _lazyTerminal flag
|
||||
// restore → _restoreTeammateTerminalFromLazy() → re-creates Terminal
|
||||
// create (hidden/minimized) → skip initTeammateTerminal, set _lazyTerminal
|
||||
//
|
||||
// The tmux pane buffer is re-fetched from the API on restore. Regular
|
||||
// (non-teammate) subagent windows use activity HTML and are unaffected
|
||||
// by this optimization.
|
||||
|
||||
/**
|
||||
* Dispose a teammate terminal when its window is minimized.
|
||||
* Saves pane metadata so the terminal can be re-created on restore.
|
||||
* No-op if the window has no teammate terminal.
|
||||
*/
|
||||
_disposeTeammateTerminalForMinimize(agentId) {
|
||||
const termData = this.teammateTerminals.get(agentId);
|
||||
if (!termData) return; // Not a teammate terminal window
|
||||
|
||||
const windowData = this.subagentWindows.get(agentId);
|
||||
|
||||
// Save pane metadata needed to re-create the terminal on restore
|
||||
if (windowData) {
|
||||
windowData._lazyTerminal = true;
|
||||
windowData._lazyPaneTarget = termData.paneTarget;
|
||||
windowData._lazySessionId = termData.sessionId;
|
||||
}
|
||||
|
||||
// Dispose the resize observer
|
||||
if (termData.resizeObserver) {
|
||||
termData.resizeObserver.disconnect();
|
||||
}
|
||||
|
||||
// Dispose the xterm.js Terminal instance (frees DOM nodes and internal buffers)
|
||||
if (termData.terminal) {
|
||||
try {
|
||||
termData.terminal.dispose();
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Remove from teammateTerminals map so renderSubagentWindowContent won't skip this window
|
||||
// (the activity HTML can serve as a lightweight placeholder while minimized)
|
||||
this.teammateTerminals.delete(agentId);
|
||||
},
|
||||
|
||||
/**
|
||||
* Re-create a teammate terminal when its window is restored from minimized state.
|
||||
* Fetches the current pane buffer from the API (tmux is the source of truth).
|
||||
* No-op if the window doesn't have the _lazyTerminal flag.
|
||||
*/
|
||||
_restoreTeammateTerminalFromLazy(agentId) {
|
||||
const windowData = this.subagentWindows.get(agentId);
|
||||
if (!windowData || !windowData._lazyTerminal) return;
|
||||
|
||||
const paneTarget = windowData._lazyPaneTarget;
|
||||
const sessionId = windowData._lazySessionId;
|
||||
|
||||
// Clear lazy state
|
||||
windowData._lazyTerminal = false;
|
||||
windowData._lazyPaneTarget = null;
|
||||
windowData._lazySessionId = null;
|
||||
|
||||
if (!paneTarget || !sessionId) return;
|
||||
|
||||
// Re-create the terminal using the same initTeammateTerminal flow
|
||||
const paneInfo = { paneTarget, sessionId };
|
||||
this.initTeammateTerminal(agentId, paneInfo, windowData.element);
|
||||
},
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Subagent Floating Windows
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
@@ -627,43 +403,9 @@ Object.assign(CodemanApp.prototype, {
|
||||
finalY = topStart + visibleCount * (mobileCardHeight + mobileCardGap);
|
||||
}
|
||||
} else {
|
||||
// Check if Ralph wizard modal is open - if so, position windows on the sides
|
||||
const wizardModal = document.getElementById('ralphWizardModal');
|
||||
const wizardOpen = wizardModal?.classList.contains('active');
|
||||
|
||||
let startX, startY, maxCols;
|
||||
|
||||
if (wizardOpen) {
|
||||
// Wizard is ~720px wide, centered. Position windows on left/right sides
|
||||
const wizardWidth = 720;
|
||||
const centerX = viewportWidth / 2;
|
||||
const wizardLeft = centerX - wizardWidth / 2;
|
||||
const wizardRight = centerX + wizardWidth / 2;
|
||||
|
||||
// Alternate between left and right sides of the wizard
|
||||
const leftSideSpace = wizardLeft - 20;
|
||||
const rightSideSpace = viewportWidth - wizardRight - 20;
|
||||
|
||||
if (windowCount % 2 === 0 && rightSideSpace >= windowWidth) {
|
||||
// Even windows go to the right
|
||||
startX = wizardRight + 20;
|
||||
maxCols = Math.floor(rightSideSpace / (windowWidth + gap)) || 1;
|
||||
} else if (leftSideSpace >= windowWidth) {
|
||||
// Odd windows go to the left
|
||||
startX = Math.max(10, wizardLeft - windowWidth - 20);
|
||||
maxCols = 1; // Usually only room for 1 column on left
|
||||
} else {
|
||||
// Not enough side space, use right side
|
||||
startX = wizardRight + 20;
|
||||
maxCols = 1;
|
||||
}
|
||||
startY = 80; // Start higher when wizard is open
|
||||
} else {
|
||||
// Normal positioning
|
||||
startX = 50;
|
||||
startY = WINDOW_INITIAL_TOP_PX;
|
||||
maxCols = Math.floor((viewportWidth - startX - 50) / (windowWidth + gap)) || 1;
|
||||
}
|
||||
const startX = 50;
|
||||
const startY = WINDOW_INITIAL_TOP_PX;
|
||||
const maxCols = Math.floor((viewportWidth - startX - 50) / (windowWidth + gap)) || 1;
|
||||
|
||||
const maxRows = Math.floor((viewportHeight - startY - 50) / (windowHeight + gap)) || 1;
|
||||
const col = windowCount % maxCols;
|
||||
@@ -793,24 +535,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
win.style.display = 'none';
|
||||
}
|
||||
|
||||
// Render content — check if this teammate has a tmux pane
|
||||
const paneInfo = teammateInfo ? this.teammatePanesByName.get(teammateInfo.name) : null;
|
||||
if (paneInfo) {
|
||||
if (shouldHide) {
|
||||
// Window starts hidden — defer terminal creation until visible (lazy init).
|
||||
// Saves ~75KB of DOM memory per hidden teammate terminal window.
|
||||
const windowEntry = this.subagentWindows.get(agentId);
|
||||
if (windowEntry) {
|
||||
windowEntry._lazyTerminal = true;
|
||||
windowEntry._lazyPaneTarget = paneInfo.paneTarget;
|
||||
windowEntry._lazySessionId = paneInfo.sessionId;
|
||||
}
|
||||
} else {
|
||||
this.initTeammateTerminal(agentId, paneInfo, win);
|
||||
}
|
||||
} else {
|
||||
this.renderSubagentWindowContent(agentId);
|
||||
}
|
||||
this.renderSubagentWindowContent(agentId);
|
||||
|
||||
// Focus on click
|
||||
win.addEventListener('mousedown', () => {
|
||||
@@ -882,10 +607,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
this.setAgentParentSessionId(agentId, parentSessionId);
|
||||
}
|
||||
|
||||
// Dispose teammate terminal on minimize to free DOM/memory (~75KB per instance).
|
||||
// The terminal will be lazily re-created on restore via initTeammateTerminal().
|
||||
this._disposeTeammateTerminalForMinimize(agentId);
|
||||
|
||||
// Always minimize to tab
|
||||
windowData.element.style.display = 'none';
|
||||
windowData.minimized = true;
|
||||
@@ -939,7 +660,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Clean up ALL floating windows (called during handleInit to prevent memory leaks on reconnect)
|
||||
cleanupAllFloatingWindows() {
|
||||
// Clean up all subagent windows with their ResizeObservers and drag listeners
|
||||
for (const [agentId, windowData] of this.subagentWindows) {
|
||||
for (const windowData of this.subagentWindows.values()) {
|
||||
if (windowData.resizeObserver) {
|
||||
windowData.resizeObserver.disconnect();
|
||||
}
|
||||
@@ -956,20 +677,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
this.subagentWindows.clear();
|
||||
|
||||
// Clean up all teammate terminals
|
||||
for (const [, termData] of this.teammateTerminals) {
|
||||
if (termData.resizeObserver) termData.resizeObserver.disconnect();
|
||||
if (termData.terminal) {
|
||||
try {
|
||||
termData.terminal.dispose();
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
this.teammateTerminals.clear();
|
||||
this.teammatePanesByName.clear();
|
||||
|
||||
// Clean up all log viewer windows with their EventSources and drag listeners
|
||||
for (const [windowId, data] of this.logViewerWindows) {
|
||||
for (const data of this.logViewerWindows.values()) {
|
||||
if (data.eventSource) {
|
||||
data.eventSource.close();
|
||||
}
|
||||
@@ -986,22 +695,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
this.logViewerWindows.clear();
|
||||
|
||||
// Clean up plan subagent windows (wizard agents)
|
||||
if (this.planSubagents) {
|
||||
for (const [agentId, windowData] of this.planSubagents) {
|
||||
if (windowData.dragListeners) {
|
||||
document.removeEventListener('mousemove', windowData.dragListeners.move);
|
||||
document.removeEventListener('mouseup', windowData.dragListeners.up);
|
||||
}
|
||||
if (windowData.element) {
|
||||
windowData.element.remove();
|
||||
}
|
||||
}
|
||||
this.planSubagents.clear();
|
||||
}
|
||||
|
||||
// Clean up all image popup windows with their drag listeners
|
||||
for (const [imageId, popupData] of this.imagePopups) {
|
||||
for (const popupData of this.imagePopups.values()) {
|
||||
if (popupData.dragListeners) {
|
||||
document.removeEventListener('mousemove', popupData.dragListeners.move);
|
||||
document.removeEventListener('mouseup', popupData.dragListeners.up);
|
||||
@@ -1018,48 +713,15 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Clean up ultracode floating run windows (re-seeded from data.workflowRuns on reconnect)
|
||||
if (typeof this.removeAllUltracodeWindows === 'function') this.removeAllUltracodeWindows();
|
||||
|
||||
// Clear orphaned plan generation state
|
||||
this.activePlanOrchestratorId = null;
|
||||
this._planProgressHandler = null;
|
||||
this.planGenerationStopped = true;
|
||||
if (this.planGenerationAbortController) {
|
||||
this.planGenerationAbortController.abort();
|
||||
this.planGenerationAbortController = null;
|
||||
}
|
||||
|
||||
// Clean up wizard-specific timers (leak fix: not cleared on SSE reconnect)
|
||||
if (this.wizardMinimizedTimer) {
|
||||
clearInterval(this.wizardMinimizedTimer);
|
||||
this.wizardMinimizedTimer = null;
|
||||
}
|
||||
|
||||
// Clean up wizard drag listeners (leak fix: document-level handlers)
|
||||
if (typeof this.cleanupWizardDragging === 'function') this.cleanupWizardDragging();
|
||||
|
||||
// Deactivate focus trap if wizard was open (leak fix: keydown listener)
|
||||
// Deactivate a focus trap a modal left active (leak fix: keydown listener)
|
||||
if (this.activeFocusTrap) {
|
||||
this.activeFocusTrap.deactivate();
|
||||
this.activeFocusTrap = null;
|
||||
}
|
||||
|
||||
// Clean up team tasks panel drag listeners
|
||||
if (this.teamTasksDragListeners) {
|
||||
document.removeEventListener('mousemove', this.teamTasksDragListeners.move);
|
||||
document.removeEventListener('mouseup', this.teamTasksDragListeners.up);
|
||||
if (this.teamTasksDragListeners.touchMove) {
|
||||
document.removeEventListener('touchmove', this.teamTasksDragListeners.touchMove);
|
||||
document.removeEventListener('touchend', this.teamTasksDragListeners.up);
|
||||
document.removeEventListener('touchcancel', this.teamTasksDragListeners.up);
|
||||
}
|
||||
this.teamTasksDragListeners = null;
|
||||
}
|
||||
|
||||
// Clear minimized agents tracking
|
||||
this.minimizedSubagents.clear();
|
||||
|
||||
// Update monitor panel
|
||||
this.renderMonitorPlanAgents();
|
||||
|
||||
// Update connection lines (should be empty now)
|
||||
this.updateConnectionLines();
|
||||
},
|
||||
@@ -1096,12 +758,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
windowData.minimized = false;
|
||||
|
||||
// Lazily re-create teammate terminal if it was disposed on minimize.
|
||||
// Only re-create when the window is actually becoming visible.
|
||||
if (shouldShow && windowData._lazyTerminal) {
|
||||
this._restoreTeammateTerminalFromLazy(agentId);
|
||||
}
|
||||
|
||||
this.updateConnectionLines();
|
||||
// Restack all visible mobile windows so restored ones don't overlap
|
||||
this.relayoutMobileSubagentWindows();
|
||||
|
||||
@@ -428,8 +428,8 @@
|
||||
|
||||
// Per-skin xterm.js palettes. The 'daylight-blue' object equals the legacy hardcoded
|
||||
// theme, so default behavior is unchanged. Shared at module scope and exported on the
|
||||
// global so both terminal-ui.js (main terminal) and panels-ui.js (teammate terminals,
|
||||
// a separate IIFE) can read the current skin's palette.
|
||||
// global so the main terminal and every other module that builds a terminal (tiles,
|
||||
// the split pane) can read the current skin's palette.
|
||||
//
|
||||
// ⚠️ The selection key is `selectionBackground`, xterm's name for it since v5 (#360).
|
||||
// An ITheme is a plain object handed straight to xterm, so an unknown key is not an
|
||||
@@ -1256,7 +1256,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
let touchLastX = 0;
|
||||
let touchLastY = 0;
|
||||
let velocity = 0;
|
||||
let lastTime = 0;
|
||||
let scrollFrame = null;
|
||||
let isTouching = false;
|
||||
// One id per touch contact (touchstart), carried by its touchmoves AND its
|
||||
@@ -1264,10 +1263,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
// gesture however slowly the finger moves (pageKeysForGesture).
|
||||
let touchContactId = 0;
|
||||
|
||||
const scrollLoop = (timestamp) => {
|
||||
const dt = lastTime ? (timestamp - lastTime) / 16.67 : 1;
|
||||
lastTime = timestamp;
|
||||
|
||||
const scrollLoop = () => {
|
||||
if (!isTouching && Math.abs(velocity) > 0.3) {
|
||||
// Momentum phase — convert pixel velocity to lines
|
||||
const lines = Math.round(velocity / cellHeight());
|
||||
@@ -1389,7 +1385,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
longPressTimer = null;
|
||||
this._beginTouchSelection(longPressStartX, longPressStartY);
|
||||
}, window.CodemanTerminalInput.TOUCH_SELECT_LONG_PRESS_MS);
|
||||
lastTime = 0;
|
||||
if (scrollFrame) {
|
||||
cancelAnimationFrame(scrollFrame);
|
||||
scrollFrame = null;
|
||||
@@ -6590,16 +6585,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
this._refitAfterCellSizeChange();
|
||||
this._localEchoOverlay?.refreshFont();
|
||||
this._predictiveEcho?.refreshFont();
|
||||
for (const [, entry] of this.teammateTerminals || []) {
|
||||
if (!entry?.terminal) continue;
|
||||
entry.terminal.options.fontWeight = fontWeight;
|
||||
entry.terminal.options.fontWeightBold = fontWeightBold;
|
||||
try {
|
||||
entry.fitAddon?.fit();
|
||||
} catch {
|
||||
/* pane not laid out yet — its own resize observer refits it */
|
||||
}
|
||||
}
|
||||
this._forEachTile?.((tile) => {
|
||||
tile.terminal.options.fontWeight = fontWeight;
|
||||
tile.terminal.options.fontWeightBold = fontWeightBold;
|
||||
@@ -7163,7 +7148,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
}, 100);
|
||||
},
|
||||
|
||||
// Re-theme all live xterm terminals (main + teammate) to the given skin's palette.
|
||||
// Re-theme all live xterm terminals (main pane and tiles) to the given skin's palette.
|
||||
// Uses the xterm v5+ live setter (full object assignment triggers a repaint for both
|
||||
// DOM and WebGL renderers) plus a belt-and-suspenders refresh().
|
||||
applyTerminalSkin(skin) {
|
||||
@@ -7181,17 +7166,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
this.terminal.refresh(0, this.terminal.rows - 1);
|
||||
} catch {}
|
||||
}
|
||||
if (this.teammateTerminals) {
|
||||
for (const [, entry] of this.teammateTerminals) {
|
||||
if (entry && entry.terminal) {
|
||||
entry.terminal.options.minimumContrastRatio = minimumContrastRatio;
|
||||
entry.terminal.options.theme = { ...theme };
|
||||
try {
|
||||
entry.terminal.refresh(0, entry.terminal.rows - 1);
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
this._forEachTile?.((tile) => {
|
||||
tile.terminal.options.minimumContrastRatio = minimumContrastRatio;
|
||||
tile.terminal.options.theme = { ...theme };
|
||||
|
||||
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user