diff --git a/.changeset/run-menu-custom-model-picker.md b/.changeset/run-menu-custom-model-picker.md new file mode 100644 index 000000000..bedbdd8ca --- /dev/null +++ b/.changeset/run-menu-custom-model-picker.md @@ -0,0 +1,17 @@ +--- +"aicodeman": minor +--- + +**Custom model endpoints: Run-menu picker, and hardening from real llama-swap validation** (#430, follow-up to #393's HTTP-API-only cut). With **Custom model endpoints** on (App Settings → Models) and at least one saved endpoint carrying a discovered model, the Run dropdown grows a **Custom Endpoints** section generated live off the CLI registry's own `capabilities.customModelInjection` — one entry per (harness that can redirect to a custom endpoint, saved endpoint). Picking one launches that harness and applies the endpoint to it; with two or more discovered models a small, scrollable dialog asks which one first, the endpoint's `defaultModelId` marked but never auto-chosen. Endpoints also now re-discover themselves automatically every 5 minutes in the background, one unreachable endpoint never blocking the others. + +Everything below was found and fixed against a **real llama-swap server**, not just unit tests: + +- **Session-busy false refusal.** A freshly launched CLI reports itself `busy` for its own startup (spinner, workspace-trust check) well before the apply call would reach it, and the apply route correctly refuses to restart a session mid-turn — indistinguishable from a fresh boot. The picker now waits for the new session to go idle (bounded at 20s, never an error on timeout) before applying. +- **Errors and confirmations you can actually read.** Toasts now default to sticky with a close button (errors always were meant to stay, but a fixed 3s timer silently hid them); a failed apply's real server-side reason (not a generic message) reaches the toast. +- **"Both claude.ai and ANTHROPIC_API_KEY set" warning.** A custom-model Claude session now runs with an isolated `CLAUDE_CONFIG_DIR` (empty, no real credentials in it) so the injected API key never coexists with a stored OAuth login — `projects` is symlinked back to the real config dir so the response viewer/subagent windows/Read My Mind keep working. That isolated, otherwise-empty directory has none of a real profile's prior "Detected a custom API key — use it?" approvals either, which would otherwise re-ask on *every* launch with nobody at a TTY to answer (and silently refuse the key on its own default); the apply step now pre-seeds that exact approval field the same way answering the prompt once by hand would. +- **Context-window overflow.** Claude Code assumes a large default context window for a model id it doesn't recognize and never compacts, so a real local model's much smaller context silently overflowed (confirmed live: a stock ~33.7K-token system prompt against a 16384-token model). Discovery now also learns each model's real context length from llama.cpp/llama-swap's `GET /props?model=`, but **only** for a model llama-swap's own `/v1/models` response already reports loaded — never an unloaded one, since asking about one risks triggering an actual, slow, GPU-swapping load as a side effect of read-only discovery — and applies it as `CLAUDE_CODE_MAX_CONTEXT_TOKENS`. +- **The real root cause of "it still says opus, not my model."** llama.cpp runs exactly one model at a time; llama-swap unloads and reloads it on demand, which can take anywhere from a few seconds to well over a minute — long enough that a session mid-swap is indistinguishable from one that never left the native backend. Applying a selection now checks llama-swap's own `GET /running` first (feature-detected; a plain llama.cpp/OpenAI-compatible server has no such endpoint and is never checked); if switching would unload a model **another live session is actively using**, the apply is refused with a warning naming that session instead of silently switching, and a confirmation retry proceeds anyway. Either way, a sticky "loading model…" toast now covers the actual swap window until llama-swap reports the target model ready, so a prompt sent mid-swap reads as "loading," never as silence or an answer from whatever was loaded a moment before. + +Remote (SSH) and Docker sessions are refused for now (400) — their restart reattaches the durable remote/in-container tmux rather than relaunching the agent. + +**One more, from watching it launch live: opencode, Codex, Gemini, Pi, Grok, DeepSeek and OMP now launch directly on the endpoint, with no restart at all.** Picking one of these seven from the Run-menu picker used to launch natively first, wait for it to settle, then restart it in place with the endpoint applied — a deliberate two-step design, but visibly a native boot immediately followed by a second one, worst on a CLI whose TUI fully reinitializes on a restart (confirmed live on Codex). `POST /api/quick-start` now accepts a `customModel` field and computes the same injection *before* the session exists, launching straight onto the endpoint the first time — no visible relaunch, and it also runs the same llama-swap conflict check (warns before unloading a model another live session is using) at create time. Claude still uses the original launch-then-restart path for now (its own `--resume`-based restart is far less jarring, and `runClaude()`'s multi-tab and docker-config-drift-retry logic make folding it into the one-shot path separate work). diff --git a/CLAUDE.md b/CLAUDE.md index 4ef118e5f..cc6ac628b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -227,7 +227,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph **DeepSeek web UI** (`POST`/`GET`/`DELETE /api/deepseek/web`, `deepseek-web-server.ts`): the Run menu's "DeepSeek web UI..." entry supervises ONE background `dsh web` child process, deliberately **NOT a shell session**. The session version worked and was still wrong in use: it put a terminal tab on screen next to the web tab the user actually asked for, every single time, and nothing about a long-lived HTTP server needs to be a tab. ⚠️ What a session gave for free now has to be paid for explicitly, and every piece is load-bearing: **exactly one** server (a second click REUSES it rather than racing it for a port, which two sessions structurally could not do), **restarted when the browser authority changes** (`--trusted-host` fences dsh's `/api` against the browser authority, and a Codeman reachable at both loopback and a tailnet name has two, so whoever asks last wins: the asker is by definition the origin about to load the page), **killed on shutdown** (`stopDeepSeekWeb()` in the server teardown, because the child is detached so its whole plugin tree can be signalled at once, which also means it would OUTLIVE Codeman and hold its port against the next start), and **failures returned to the caller**, since with no tab there is nowhere for a stack trace to land. ⚠️ The port search starts at dsh's own default 3080 and walks 40, never fixed: that default is precisely the port most likely to be taken already by the user's own `dsh web`, and hardcoding it killed this feature with EADDRINUSE once. Free-port detection BINDS rather than connects (a connect probe cannot tell "free" from "listening but not answering yet"), so it is racy by nature and the caller still waits for the server to really answer before reporting success. ⚠️ Both `POST` and `DELETE` sit at the **same privilege bar as the profile installer** (`canUsernameRunPrivilegedCommands`) even though the action reads as "open a page": booting a dsh profile executes the plugin code in it, and the server is a single shared instance, so stopping it in multi-user mode takes it out from under other users' tabs. -**Custom Model Endpoint Profiles** (opt-in, `customModelEndpointsEnabled`, SYNCED, default OFF; `docs/custom-model-endpoints.md`, design doc `docs/custom-model-endpoints-plan.md`; backend + HTTP API only until the Run-menu picker lands, and the setting is read by nothing yet): points a session at a user-configured custom OpenAI-compatible endpoint — local (llama.cpp, DGX Spark, Strix Halo) or cloud (Azure AI Foundry, OpenRouter) — instead of its harness's native cloud backend. Endpoints are a read/write-array store (`custom-model-hosts.ts`, `~/.codeman/custom-model-hosts.json`) discovered via `GET /v1/models`; `CustomModelHost.authStyle` is `'bearer'` (default, `Authorization: Bearer`) or `'api-key'` (Azure's convention) — **never both**, live-tested against a real server: sending both headers on one request reliably hangs it indefinitely, reproduced 3×. ⚠️ The actual per-CLI redirect is `capabilities.customModelInjection` on the CLI registry (four kinds: `env` for claude/gemini/deepseek, `configContentEnv` reusing opencode's existing `OPENCODE_CONFIG_CONTENT`, `configDir` for codex/pi/grok/omp — writes an isolated per-session config file, NEVER the user's real `~/.codex`/`~/.pi`/`~/.omp`/grok config — and `unsupported` for antigravity, which has no known mechanism), computed by the pure `custom-model-injection.ts` (mirrors `session-cli-builder.ts`'s no-IO discipline). ⚠️ `PI_CONFIG_DIR` does NOTHING for pi or omp (grepped pi's entire bundled JS source — the string appears nowhere); both hardcode `~/.pi/agent/models.json` / `~/.omp/agent/models.yml` with no dedicated override, so the real redirect for both is the child process's own **`HOME`**, and both need `models` as an ARRAY of `{id}` objects (an object keyed by id silently loads zero models). Grok's real mechanism turned out to be a `config.toml` `[model.]` block redirected via `GROK_HOME` — its original env-var-based recipe was flat-out wrong (produced "Not signed in" against a real binary), not just unverified. ⚠️ Applying a selection **restarts the session's CLI process in place** via `Session.restartCli()` — a de-restricted `reattachRemote()` reusing the same `respawn-pane -k` primitive local/remote respawns already share — because every one of these harnesses reads its endpoint config at process start, never per-turn, so there is no live hot-swap; `Session.setCustomModel()` undoes the PREVIOUS selection's env keys (and deletes its old `configDir`) before merging the new ones in, so switching endpoints or clearing back to native cloud never leaves a stale key behind. ⚠️ Deleting a key from `_envOverrides` is NOT enough on its own: `tmux setenv` persists at the tmux-session level and is inherited by `respawn-pane` (measured: `setenv FOO bar` survived two successive `respawn-pane -k`), so the retired keys are queued (`_pendingEnvUnsets`) and ride `RespawnPaneOptions.unsetEnvKeys` into `applyEnvOverrides()`, which `setenv -u`s them BEFORE re-applying the live overrides. ⚠️ `restartCli()` kills a WORKING pane, so a CLI whose launch declares a `fallback` chain (claude) gets the live conversation id pinned as `resumeSessionId` for that one respawn: `--session-id ` refuses an id that already has a transcript (`Session ID ... is already in use`), and without the `--resume || --session-id ` shape the docker/remote pane commands already use, applying a model killed the pane and lost the session. ⚠️ pi, omp and grok need the config file AND a `model` launch param (`custom/` for pi/omp, grok's `[model.codeman-custom]` block name): that is the registry's `customModelInjection.launchModel` template, applied onto the respawn options through `legacyConfigField` by `_withCustomModelLaunchModel()`, never by id, and a model id the CLI's `model` token pattern cannot carry is refused with a 400 rather than silently dropped by the argv engine. ⚠️ Remote (SSH) and Docker sessions are REFUSED (400): their `restartCli()` reattaches a durable tmux rather than restarting the agent and the env lands on the local pane, so they used to report `restarted:true` and change nothing. The selection survives a Codeman restart as the disk-only `__customModel` (bookkeeping: env KEYS, config dir, launch model; never the values, which carry the API key and are re-derived from the endpoint store on recovery), the config dir is removed with the session, and every secret-bearing file (`custom-model-hosts.json`, the per-session config dir) is written 0600. ⚠️ **Security**: every env var this feature can redirect (`ANTHROPIC_BASE_URL`, `GOOGLE_GEMINI_BASE_URL`, `CODEX_HOME`, `GROK_HOME`, `HOME` for pi/omp, `OPENCODE_CONFIG_CONTENT`, etc.) is in that CLI's `privilegedEnvKeys` — several of these were reachable via the generic `envOverrides` field's prefix allowlist BEFORE this feature existed (the env allowlist is global and prefix-based, not per-CLI-scoped), so building this surfaced and closed a pre-existing gap rather than opening a new one. `ANTHROPIC_*` is deliberately NOT in claude's `allowedPrefixes` at all — Anthropic-traffic redirection can only happen through this feature's own admin-configured, SSRF-guarded route, never a plain client-supplied `envOverrides`. **Confidence, verified end-to-end against a real llama-swap server via the DYNAMIC `scripts/test-local-llm-harnesses.ts`** (reads the live CLI registry, so a registry change needs zero script edits): claude/opencode/pi/grok/omp **PASS**; codex config structure is correct but codex only speaks the Responses API since Feb 2026, which llama.cpp/llama-swap don't implement — a confirmed protocol gap, not a bug; gemini fails with `Invalid auth method selected` (an undocumented `GATEWAY` AuthType gemini-cli selects once `GOOGLE_GEMINI_BASE_URL` is set — unresolved after real investigation); deepseek reaches the server but gets a consistent `HTTP_404` (root cause not identified); antigravity has no known mechanism at all. See the confidence table in `docs/custom-model-endpoints-plan.md` for the full detail on each. +**Custom Model Endpoint Profiles** (opt-in, `customModelEndpointsEnabled`, SYNCED, default OFF; `docs/custom-model-endpoints.md`, design doc `docs/custom-model-endpoints-plan.md`; full stack — settings-panel CRUD + the Run-menu picker, on top of the backend below): points a session at a user-configured custom OpenAI-compatible endpoint — local (llama.cpp, DGX Spark, Strix Halo) or cloud (Azure AI Foundry, OpenRouter) — instead of its harness's native cloud backend. Endpoints are a read/write-array store (`custom-model-hosts.ts`, `~/.codeman/custom-model-hosts.json`) discovered via `GET /v1/models`; `CustomModelHost.authStyle` is `'bearer'` (default, `Authorization: Bearer`) or `'api-key'` (Azure's convention) — **never both**, live-tested against a real server: sending both headers on one request reliably hangs it indefinitely, reproduced 3×. ⚠️ The actual per-CLI redirect is `capabilities.customModelInjection` on the CLI registry (four kinds: `env` for claude/gemini/deepseek, `configContentEnv` reusing opencode's existing `OPENCODE_CONFIG_CONTENT`, `configDir` for codex/pi/grok/omp — writes an isolated per-session config file, NEVER the user's real `~/.codex`/`~/.pi`/`~/.omp`/grok config — and `unsupported` for antigravity, which has no known mechanism), computed by the pure `custom-model-injection.ts` (mirrors `session-cli-builder.ts`'s no-IO discipline). ⚠️ `PI_CONFIG_DIR` does NOTHING for pi or omp (grepped pi's entire bundled JS source — the string appears nowhere); both hardcode `~/.pi/agent/models.json` / `~/.omp/agent/models.yml` with no dedicated override, so the real redirect for both is the child process's own **`HOME`**, and both need `models` as an ARRAY of `{id}` objects (an object keyed by id silently loads zero models). Grok's real mechanism turned out to be a `config.toml` `[model.]` block redirected via `GROK_HOME` — its original env-var-based recipe was flat-out wrong (produced "Not signed in" against a real binary), not just unverified. ⚠️ Applying a selection **restarts the session's CLI process in place** via `Session.restartCli()` — a de-restricted `reattachRemote()` reusing the same `respawn-pane -k` primitive local/remote respawns already share — because every one of these harnesses reads its endpoint config at process start, never per-turn, so there is no live hot-swap; `Session.setCustomModel()` undoes the PREVIOUS selection's env keys (and deletes its old `configDir`) before merging the new ones in, so switching endpoints or clearing back to native cloud never leaves a stale key behind. ⚠️ Deleting a key from `_envOverrides` is NOT enough on its own: `tmux setenv` persists at the tmux-session level and is inherited by `respawn-pane` (measured: `setenv FOO bar` survived two successive `respawn-pane -k`), so the retired keys are queued (`_pendingEnvUnsets`) and ride `RespawnPaneOptions.unsetEnvKeys` into `applyEnvOverrides()`, which `setenv -u`s them BEFORE re-applying the live overrides. ⚠️ `restartCli()` kills a WORKING pane, so a CLI whose launch declares a `fallback` chain (claude) gets the live conversation id pinned as `resumeSessionId` for that one respawn: `--session-id ` refuses an id that already has a transcript (`Session ID ... is already in use`), and without the `--resume || --session-id ` shape the docker/remote pane commands already use, applying a model killed the pane and lost the session. ⚠️ pi, omp and grok need the config file AND a `model` launch param (`custom/` for pi/omp, grok's `[model.codeman-custom]` block name): that is the registry's `customModelInjection.launchModel` template, applied onto the respawn options through `legacyConfigField` by `_withCustomModelLaunchModel()`, never by id, and a model id the CLI's `model` token pattern cannot carry is refused with a 400 rather than silently dropped by the argv engine. ⚠️ Remote (SSH) and Docker sessions are REFUSED (400): their `restartCli()` reattaches a durable tmux rather than restarting the agent and the env lands on the local pane, so they used to report `restarted:true` and change nothing. The selection survives a Codeman restart as the disk-only `__customModel` (bookkeeping: env KEYS, config dir, launch model; never the values, which carry the API key and are re-derived from the endpoint store on recovery), the config dir is removed with the session, and every secret-bearing file (`custom-model-hosts.json`, the per-session config dir) is written 0600. ⚠️ **Security**: every env var this feature can redirect (`ANTHROPIC_BASE_URL`, `GOOGLE_GEMINI_BASE_URL`, `CODEX_HOME`, `GROK_HOME`, `HOME` for pi/omp, `OPENCODE_CONFIG_CONTENT`, etc.) is in that CLI's `privilegedEnvKeys` — several of these were reachable via the generic `envOverrides` field's prefix allowlist BEFORE this feature existed (the env allowlist is global and prefix-based, not per-CLI-scoped), so building this surfaced and closed a pre-existing gap rather than opening a new one. `ANTHROPIC_*` is deliberately NOT in claude's `allowedPrefixes` at all — Anthropic-traffic redirection can only happen through this feature's own admin-configured, SSRF-guarded route, never a plain client-supplied `envOverrides`. **Confidence, verified end-to-end against a real llama-swap server via the DYNAMIC `scripts/test-local-llm-harnesses.ts`** (reads the live CLI registry, so a registry change needs zero script edits): claude/opencode/pi/grok/omp **PASS**; codex config structure is correct but codex only speaks the Responses API since Feb 2026, which llama.cpp/llama-swap don't implement — a confirmed protocol gap, not a bug; gemini fails with `Invalid auth method selected` (an undocumented `GATEWAY` AuthType gemini-cli selects once `GOOGLE_GEMINI_BASE_URL` is set — unresolved after real investigation); deepseek reaches the server but gets a consistent `HTTP_404` (root cause not identified); antigravity has no known mechanism at all. See the confidence table in `docs/custom-model-endpoints-plan.md` for the full detail on each. ⚠️ **The Run-menu picker generates entries from `window.__codemanCustomModelClis`** (`server.ts`, injected at page render from `enabledClis().filter(kind==='agent' && customModelInjection.kind!=='unsupported')`, JSON-escaped against a literal `` via the exported `escapeScriptJson()` since `label` is a user-`clis.json`-settable string unlike the neighbouring booleans-only `__codemanCliAvailable`), never a hardcoded per-CLI id list in the frontend — the same "no branching on CLI id outside stock.ts" discipline the registry itself enforces. One entry per (capable, INSTALLED CLI, saved endpoint) pair, e.g. "Claude Code (llama.cpp)", filtered through `isCliAvailable()` like the stock entries. Clicking one calls `selectCustomModelEntry(mode, endpointId)` (`session-ui.js`), which re-fetches the endpoint (never trusts anything cached from the dropdown's render — the 5-minute sweep below or a settings edit may have changed it since) and decides the model: exactly one discovered model launches straight away, two or more open `#customModelPickModal` to ask, with `defaultModelId` marked but never auto-chosen (asking exists so ONE launch can deliberately differ from the saved default). Either way the actual launch (`runCustomModelEntry`) routes through `run()` itself via a temporary `_runMode` swap — never `setRunMode()`, which would persist it as the user's new default — rather than a parallel dispatch table, which is what gives a custom-model launch the same `_runInFlight` lock every other Run click gets and means a CLI whose injection recipe lands later needs no update here. It then GETs `/api/sessions/:id/wait?until=idle&timeout=20000` on that session BEFORE applying — measured live, a freshly launched CLI reports itself `busy` for its own startup (boot spinner, workspace-trust check) well before the apply call would otherwise reach it, and the apply route's `isBusy()` guard correctly can't tell that apart from a real turn in progress, so every fresh launch failed with `SESSION_BUSY` until this wait was added. A timeout there is a normal 200 per the wait endpoint's own contract, never an error, so a session still busy after 20s just reaches the apply call anyway and gets that route's own honest error. It then calls `POST /api/sessions/:id/custom-model` on the session `run()` produced, guarded by snapshotting `activeSessionId` before the call and requiring it to have actually changed after — every `run*()` handles its own failure internally and returns normally rather than throwing, so a declined/failed launch must not silently re-point and restart whatever session was already open. ⚠️ The apply call reads the response body itself (`_api()`) rather than `_apiJson()`, which unwraps success but silently discards a failure body — losing the one thing (`error`) that distinguishes "still busy", "not a discovered model", "remote/Docker session" and everything else the route can report; the resulting toast is `type: 'error'`, which `showToast()` now defaults to STICKY (no auto-dismiss, an explicit close button) precisely so a message worth diagnosing survives long enough to be read — a 3s default hid the real reason behind every one of these failures until it was fixed. Entries are hidden for a remote/docker active case (the apply route refuses both) and for an endpoint with no discovered models at all (nothing to launch with). ⚠️ **Every saved endpoint's models also re-discover themselves automatically**, a `this.cleanup.setInterval` in `server.ts` (`CUSTOM_MODEL_REDISCOVER_INTERVAL_MS`, 5 minutes, off under `testMode` like the Codex plan-usage poll beside it) calling the exported `refreshAllCustomModelHosts()` (`custom-model-routes.ts`) — one endpoint unreachable on a cycle never blocks the others, and a read-modify-write PER HOST (re-reading the store before each splice, keyed by id) means an admin's concurrent edit or delete wins over a sweep that started before it, never the reverse. **Run launch synchronization**: the Run entrypoint holds an in-flight lock and disables `#runBtn` for the whole launch (≥500ms), so a double click cannot create duplicate sessions with the same `w-` name. `_ensureCreatedSessionVisible()` runs before `selectSession()`, and `_onSessionCreated()` stays an idempotent upsert, so POST-first and SSE-first ordering both produce exactly one rendered tab. ⚠️ **Closing has the mirror-image race and one owner**: `closeSession()` reads `wasActive` BEFORE its `await` and announces the delete via `_closingSessions`, while `_onSessionDeleted` skips the active-session handoff for an id in that set. Both used to read `activeSessionId` after the fact, so the `session_deleted` broadcast for your own delete could null it first and closing the tab you were on landed on the welcome screen instead of the next session, on the same build, depending on timing. The fallback also picks the first order entry that is still in `sessions` (a dead id can linger in `sessionOrder`, same reason Alt+N indexes a live-filtered list). A delete from ANOTHER client still shows the welcome screen, which is the honest answer when what you were looking at was taken away. Tests: `test/session-close-fallback.test.ts`. → [architecture-invariants#run-launch-synchronization](docs/architecture-invariants.md#run-launch-synchronization) diff --git a/docs/api-reference.md b/docs/api-reference.md index dcd0d631a..9e274cb6f 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -516,6 +516,57 @@ All four enforce session ownership in multi-user mode; a foreign session id answers `404 NOT_FOUND` (no existence leak), and profiles of two owners of the same directory are distinct by construction. +## Custom Model Endpoints + +Points a session's harness at a user-configured OpenAI-compatible endpoint — +local (llama.cpp, vLLM, DGX Spark) or cloud (Azure AI Foundry, OpenRouter) — +instead of its native cloud backend, gated by the opt-in +`customModelEndpointsEnabled` setting (default OFF). Endpoints are +machine-level infra, like remote/docker hosts: writes are admin-only in +multi-user mode. Design: [`custom-model-endpoints-plan.md`](custom-model-endpoints-plan.md); +user guide: [`custom-model-endpoints.md`](custom-model-endpoints.md). + +- `GET /api/v1/model-endpoints` -> `CustomModelHost[]`, an unwrapped bare + array like every other list route (still riding the standard `{success, + data}` envelope on the wire — unwrap it the same way). Answers `[]` for a + non-admin in multi-user mode. `apiKey` is never returned; `apiKeySet: + boolean` reports whether one is stored, so a client can render "unchanged + if left blank" without ever holding the real value. +- `POST /api/v1/model-endpoints` with `{ id, label, baseUrl, apiKey?, + authStyle?, defaultModelId? }` creates one. `id` must match + `^[a-zA-Z0-9_-]+$`; `authStyle` is `bearer` (default) or `api-key`, never + both (a real server hung indefinitely when sent both headers on one + request); `baseUrl` must be `http(s)`, carry no embedded credentials, and + is refused if it points at (or resolves to) a link-local or + cloud-metadata address. `409 ALREADY_EXISTS` on a duplicate id. +- `PUT /api/v1/model-endpoints/:id` updates one. An **absent** `apiKey` + keeps the stored one rather than clearing it — the client never receives + the real value to resend deliberately unchanged, so omission is the only + way to say "leave it alone"; there is no way to clear a key back to unset + this way. `defaultModelId`, when set, must be one of that endpoint's own + `models` (`400 INVALID_INPUT` otherwise). +- `DELETE /api/v1/model-endpoints/:id` removes one. +- `POST /api/v1/model-endpoints/:id/discover-models` fetches the endpoint's + own `GET /v1/models` and stores the result as `models`, updating + `lastDiscoveredAt`. A `defaultModelId` that no longer appears in the fresh + list is dropped rather than carried forward invalid. Failures answer + `502 OPERATION_FAILED` with the underlying connection error, or a named + egress refusal if the resolved address turned out to be blocked. The same + refresh also runs automatically for every saved endpoint every 5 minutes + in the background (`refreshAllCustomModelHosts()`, `custom-model-routes.ts`, + started from `server.ts`), so there is no route for triggering "refresh + all" — one endpoint being unreachable on a cycle never blocks the others. +- `POST /api/v1/sessions/:id/custom-model` with `{ endpointId, modelId } | + { clear: true }` applies (or clears) the session's selection and + **restarts the session's CLI process in place** — every supported harness + reads its endpoint config at process start, never per turn, so there is + no live hot-swap. A Claude session resumes its existing conversation + across the restart; pi/omp/grok additionally get a forced `--model`/`-m` + value, since for those three the config file alone does not select it. + `400 INVALID_INPUT` for a remote (SSH) or Docker session — both restart + their agent differently under the hood, and applying to one would report + success while changing nothing. + ## Voice dictation Browser dictation transcribed through this server's Claude Code login, i.e. the diff --git a/docs/custom-model-endpoints-plan.md b/docs/custom-model-endpoints-plan.md index 85407adf7..2bf5db578 100644 --- a/docs/custom-model-endpoints-plan.md +++ b/docs/custom-model-endpoints-plan.md @@ -208,6 +208,14 @@ extra per-model configuration on Codeman's side at all. ### 4. Toolbar UI +> **Superseded.** This section describes the toolbar-button design as originally +> planned. What actually shipped is a Run-menu picker instead: one generated entry +> per (capable harness, saved endpoint) pair directly in the existing `#runModeMenu` +> dropdown, rather than a separate `#customModelBtn`/`#customModelMenu` surface. See +> [`docs/custom-model-endpoints.md`](custom-model-endpoints.md#the-run-menu-picker) +> for the current design; the sections below (session-restart mechanics, security) +> remain accurate regardless of which UI calls the underlying route. + - New header/toolbar button (e.g. `#customModelBtn`, `btn-toolbar btn-custom-model`), marker-hidden by default (`btn-custom-model--hidden`) and revealed by `applyHeaderVisibilitySettings()` only when diff --git a/docs/custom-model-endpoints.md b/docs/custom-model-endpoints.md index 975965ef8..e3db6016d 100644 --- a/docs/custom-model-endpoints.md +++ b/docs/custom-model-endpoints.md @@ -11,20 +11,21 @@ company gateway) — anything answering `GET /v1/models` and recipe confidence table, and security reasoning: [`custom-model-endpoints-plan.md`](custom-model-endpoints-plan.md). -> **Status**: backend is implemented and tested (registry capability, the -> injection engine, the endpoint store + discovery route, the session -> restart route). The toolbar picker / settings UI described below as the -> intended surface is **not yet built** — until it lands, use the HTTP API -> directly (examples below). Antigravity has no known custom-endpoint -> mechanism and is not supported. +> **Status**: fully wired end to end — registry capability, the injection +> engine, the endpoint store + discovery route, the session restart route, +> a settings-panel CRUD surface, and the Run-menu picker described below. +> Antigravity has no known custom-endpoint mechanism and is not supported. +> The HTTP API (examples below) still works directly and is what the picker +> itself calls under the hood. ## Turning it on -App Settings → Agents & CLIs → **Custom Model Endpoints** (synced setting -`customModelEndpointsEnabled`, default **OFF**). Until the toolbar picker -lands, nothing reads this setting: the HTTP routes below work whether it is -on or off, and it exists now only so the picker has a switch to hang off -when it ships. The API equivalent: +App Settings → Models → **Custom model endpoints** (synced setting +`customModelEndpointsEnabled`, default **OFF**). Turning it on does two +things: it reveals the endpoint list/add/edit/discover panel in that same +settings section, and it makes the Run menu offer a generated entry per +(harness, endpoint) pair — see "The Run-menu picker" below. The API +equivalent: ```bash curl -sk -X PUT https://localhost:3000/api/settings \ @@ -34,6 +35,9 @@ curl -sk -X PUT https://localhost:3000/api/settings \ ## Adding an endpoint +Via App Settings → Models → Custom model endpoints → **+ Add endpoint**, or +directly: + ```bash curl -sk -X POST https://localhost:3000/api/model-endpoints \ -H 'Content-Type: application/json' \ @@ -62,7 +66,149 @@ configured, `PUT`/`DELETE /api/model-endpoints/:id` update or remove one. Endpoint management is admin-only in multi-user mode, same as remote/docker hosts — these are machine-level infra, not per-user settings. -## Applying a model to a session +**Context length is discovered too, opportunistically and safely.** The plain +`GET /v1/models` response has no context-window field. Discovery only ever +looks for one for a model llama-swap's own response already reports +`status.value === "loaded"` for — never for an unloaded one, because +llama-swap treats `?model=` as a routing hint and asking about a model that +isn't loaded risks triggering an actual (slow, GPU-swapping) load as a side +effect of what should be read-only discovery. A server with no `status` field +on any entry at all (not llama-swap) gets no context-length enrichment, +rather than guessing. A model's previously-learned context length survives a +later cycle where it wasn't the loaded one; it's dropped only once the model +disappears from the endpoint's list entirely. Stored per model in +`modelContextLengths` and applied automatically (see "Applying a model to a +session" below) so a CLI that would otherwise assume a large default context +window for an unrecognized model id stops silently overflowing a much +smaller real one. + +**Where that number actually comes from matters, and got this wrong once +already.** The first cut read it from llama.cpp's own +`GET /props?model=` (`n_ctx`) — plausible, and it worked in testing, but +confirmed live to be actively WRONG for a `--fit-ctx`-launched llama-swap +backend: `/props` reported `n_ctx: 154112` for a model llama-swap itself had +launched with `--fit-ctx 16384`, and the real server then refused a request +right at that real 16384-token limit — `/props`'s `n_ctx` appears to report +the model's theoretical/trained maximum there, not the runtime-configured +one. Discovery now parses the REAL configured size straight out of +llama-swap's own launch command instead (`GET /running`'s `cmd` field — +`--fit-ctx ` first, then the plain llama.cpp `-c`/`--ctx-size` a +hand-written command might use), and only falls back to the `/props` probe +when `cmd` states no recognizable flag at all. + +**File size is discovered too, when the server states one.** llama-swap +writes a GB figure into an auto-discovered model's own `description` +(`"Auto-discovered 16.35 GB - parameters auto-fitted by llama.cpp"`), parsed +into `modelSizesGB` — unlike context length, this needs no `/props` probe +(the figure is right there in the `/v1/models` response) and so is populated +for every model regardless of loaded state. A hand-configured profile's own +description has no such figure and correctly gets no entry, never a guess. +Used only to label the Run-menu picker's "loading model" banner with a +rough, UNMEASURED expected-time estimate (`_estimateModelLoad()` in +session-ui.js, based on typical local NVMe/SSD throughput — not benchmarked +against any real endpoint's actual hardware/storage) and to scale that same +banner's own give-up timeout for a very large model; never anything a +server-side check relies on. + +**The loading banner shows a live countdown against that same timeout, and +treats a real timeout as a failure, not a shrug.** It checks llama-swap's +own `/running` every second (`GET /api/model-endpoints/:id/running-status`) +and counts down against the size-scaled (or flat 5-minute) timeout live; if +the countdown reaches zero with the target model still not ready, the +banner turns into a sticky error naming the llama-swap server's own logs as +where to look, and the session the load was for is closed automatically — +a console left open and pointed at a model that never finished loading is +worse than no console at all. + +`defaultModelId` names which discovered model the picker pre-marks for that +endpoint — the settings panel's Edit form exposes it as a select populated +from the endpoint's own discovered `models`, and the route refuses a value +that isn't one of them. It is applied automatically only when the endpoint +has exactly one discovered model (nothing to choose); with two or more it +is a pre-selection in the model-picker dialog below, never a silent default. +Re-discovering drops a default that no longer appears in the fresh list +rather than carrying an invalid one forward. + +**Model lists refresh themselves.** A background sweep (`server.ts`, +`CUSTOM_MODEL_REDISCOVER_INTERVAL_MS`, every 5 minutes) re-discovers every +saved endpoint the same way the manual `POST .../discover-models` route +does, best-effort per endpoint — one being unreachable on a given cycle +never blocks the others. Off under `npm test`, same reasoning as the Codex +plan-usage poll it sits beside: no real network to hit, no server instance +to keep the timer alive for. + +## The Run-menu picker + +With the setting on and at least one endpoint carrying a discovered model, +the toolbar's Run dropdown grows a **Custom Endpoints** section: one entry +per (harness that can redirect to a custom endpoint, saved endpoint) pair, +e.g. "Claude Code (llama.cpp)". The harness list is read off the CLI +registry's own `capabilities.customModelInjection` at page render +(`window.__codemanCustomModelClis`, `server.ts`) — never a hardcoded id list +in the frontend — so a CLI whose injection recipe lands later shows up with +no frontend change, and Antigravity (`unsupported`) never does. + +Picking an entry re-fetches the endpoint (`selectCustomModelEntry()`, +`session-ui.js`) rather than trusting anything cached from the dropdown's +own render — the model list can have changed via the 5-minute sweep above +or a settings-panel edit since the menu opened. With exactly one discovered +model it runs straight away; with two or more, a small modal +(`#customModelPickModal`) lists them and asks which one to use for this +launch, with the endpoint's `defaultModelId` marked but not auto-chosen — +the point of asking is letting one launch deliberately differ from the +saved default, not just confirming it. + +**How the launch itself applies the endpoint depends on the harness.** For +opencode, Codex, Gemini, Pi, Grok, DeepSeek and OMP (`runCustomModelEntry` → +`_runCustomModelEntryOneShot`), the endpoint/model is folded into the SAME +`POST /api/quick-start` call that creates the session (`customModel` field), +so the session launches directly on the endpoint — no restart, no visible +relaunch. Claude (`_runCustomModelEntryViaRestart`) still uses the original +two-step design: the launch runs a single native session exactly the way its +own Run-menu entry would, then **waits for the new session to go idle** +(`GET .../wait?until=idle`, bounded at 20s — a normal 200 either way, never +an error, per the wait endpoint's own contract) before applying the endpoint +via the restart route below. That wait exists because a freshly launched CLI +reports itself as `busy` for its own startup (a boot spinner, a +workspace-trust check) well before the apply call would otherwise reach it, +and the apply route correctly refuses to restart a session mid-turn — a +fresh boot looks exactly like one from the outside. A session still busy +after the wait reaches the apply call anyway and gets that route's own +honest `SESSION_BUSY` error, now visible as a sticky toast with a close +button rather than a generic message that vanished in three seconds. Claude +stays on this path because its own restart (`--resume`-based, keeping the +conversation) is far less jarring than the other seven's, and `runClaude()`'s +multi-tab launch and docker-config-drift confirm/retry loop make folding it +into the one-shot path separate work. It is a +one-off "try this endpoint" action, not a sticky mode: the plain Run button +still means "this harness, native cloud" afterward. Entries are hidden +entirely for a remote or Docker active case, since the apply route refuses +both (see the next section). + +## Launching directly on an endpoint (no restart) + +```bash +curl -sk -X POST https://localhost:3000/api/quick-start \ + -H 'Content-Type: application/json' \ + -d '{"caseName": "myapp", "mode": "codex", "customModel": {"endpointId": "llama-box", "modelId": "qwen3"}}' +``` + +`POST /api/quick-start`'s `customModel` field (`{endpointId, modelId, +confirmed?}`) computes the same injection the restart route below does, but +BEFORE the session exists — the session is minted its own id up front +(`crypto.randomUUID()`), the injection (env vars, and for a `configDir`-kind +CLI, the written config file) targets that real id, and the session launches +already pointed at the endpoint. No restart, because there was never a +native-backend launch to restart away from. Runs the same llama-swap +conflict check as the restart route (below) — a `409`-shaped +`{requiresConfirmation, currentlyLoadedModel, affectedSessions}` response +with no session created, resolved by retrying with `confirmed: true` — and +is refused the same way for a remote or Docker case. This is what the +Run-menu picker uses for opencode, Codex, Gemini, Pi, Grok, DeepSeek and OMP; +Claude still uses the restart route below (see "The Run-menu picker" above +for why). + +## Applying a model to an ALREADY-RUNNING session ```bash curl -sk -X POST https://localhost:3000/api/sessions//custom-model \ @@ -84,6 +230,81 @@ since for those three the config file alone does not switch the model. reattaches the durable remote/in-container tmux rather than relaunching the agent, so the selection would report success and change nothing. +**Claude gets two more env vars when known/applicable, both declared on its +registry entry (`contextLengthVar`/`configDirVar`), not hardcoded here:** + +- `CLAUDE_CODE_MAX_CONTEXT_TOKENS` is set to `modelId`'s discovered context + length (see the discovery section above) whenever one is known. Without + it, Claude Code assumes a large (200k) window for any unrecognized custom + model id and never compacts, which reliably overflows a much smaller real + local context — confirmed live: a stock ~33.7K-token system prompt against + a 16384-token llama-swap model failed with `exceeds the available context + size`. No entry for the model in `modelContextLengths` means the var is + simply omitted, never a guess. +- `CLAUDE_CONFIG_DIR` is pointed at the same isolated per-session directory + the `configDir`-kind CLIs use (empty, no files written into it), so the + injected `ANTHROPIC_API_KEY` never shares a directory with a stored + claude.ai OAuth login. Claude Code still prints "Both claude.ai and + ANTHROPIC_API_KEY set" when the two coexist in the same config directory — + cosmetic (confirmed live: the API key wins for actual requests either way, + visible in the terminal's own `API Usage Billing` line) but worth + eliminating rather than living with. The directory's `projects` + subdirectory is symlinked (a junction on Windows) back to the real + `~/.claude/projects` so the response viewer, subagent windows and Read My + Mind keep working for that session — the same trade-off and fix documented + for a manually-set `CLAUDE_CONFIG_DIR` in + [`docs/wiki/Agent-CLIs.md`](wiki/Agent-CLIs.md), just applied + automatically here. Best-effort: a platform that refuses the symlink keeps + the pre-existing blind-response-viewer side effect rather than failing the + whole custom-model apply over it. + +**That isolated directory needed one more fix to actually be usable +non-interactively.** An otherwise-empty `CLAUDE_CONFIG_DIR` has none of a +real profile's prior "Detected a custom API key — use it?" approvals, so +without more, Claude Code stops and asks that on *every single launch* — +confirmed live, and with nobody at a TTY to answer, its own default answer +("No") silently refuses the very key this feature just injected, which +looks like the endpoint being ignored entirely. `customModelInjection`'s +`apiKeyTrustFile` (`{ relPath: '.claude.json', shape: +'claude-api-key-responses' }` on claude's entry) pre-seeds that exact +approval: the apply step merges `customApiKeyResponses.approved: [apiKey]` +into `/.claude.json`, the same field a real answered prompt +itself writes to (confirmed against a real file after answering by hand +once) — this answers the prompt in advance rather than bypassing it. The +merge preserves whatever else the CLI already wrote into that file on an +earlier launch in the same isolated directory (`userID`, `numStartups`, +earlier approved keys), and a missing or corrupt file is treated as empty +rather than failing the apply. + +**llama-swap gets two more fixes on top of the context-length/config-dir +ones above, both from watching a real switch live.** llama.cpp only ever +runs one model at a time; llama-swap swaps the backing process on demand, +which can take anywhere from a few seconds to well over a minute: + +- **The conflict check.** Both apply routes (the restart one here and the + one-shot `POST /api/quick-start` above) call llama-swap's own + `GET /running` first — feature-detected, so a plain llama.cpp/OpenAI- + compatible server (no such endpoint) is simply never checked. If a + *different* model is currently loaded and ready, and another **live + session's own selection** is using it, the apply returns + `{requiresConfirmation: true, currentlyLoadedModel, affectedSessions}` + instead of silently switching — nothing is applied or created yet. + Retrying with `confirmed: true` skips the check. Switching with nothing + else affected proceeds immediately; this is a warning about disrupting + another session, never a gate on the switch itself. +- **Actually starting the load.** llama-swap has no "switch model" admin + call — the only thing that starts a swap is a real inference request + naming the model, and confirmed live: applying a selection alone never + reached llama-swap at all (nothing in its own server logs), since nothing + had actually asked it to load anything yet. Both apply routes now also + send the smallest real request that will — `POST /v1/chat/ + completions` with `max_tokens: 1` and one throwaway message — whenever the + target model isn't already the one loaded and ready, fire-and-forget (its + response is never read; `GET /api/model-endpoints/:id/running-status`, + polled client-side, is what actually confirms readiness). The response + also carries `modelSwapInProgress: true` in that case, which is what + drives the Run-menu picker's own "loading model" status banner. + Clear back to the harness's native cloud default with: ```bash diff --git a/docs/wiki/Agent-CLIs.md b/docs/wiki/Agent-CLIs.md index eb013b29a..d7ad4b22a 100644 --- a/docs/wiki/Agent-CLIs.md +++ b/docs/wiki/Agent-CLIs.md @@ -273,9 +273,16 @@ into the case's `.claude/settings.local.json` so that `/model` keeps working. - **Shell** for the times you want a terminal on your phone with no agent at all. It is a genuinely useful mode, not a fallback. +## Pointing one at your own server + +Most of these harnesses can also run against a custom OpenAI-compatible endpoint instead of +their native cloud backend, for one session at a time, an opt-in feature covered in full on +[Custom Model Endpoints](Custom-Model-Endpoints). + ## Read next - [Core Concepts](Core-Concepts) - run modes versus location overlays. +- [Custom Model Endpoints](Custom-Model-Endpoints) - run a harness against your own server. - [Settings Reference](Settings-Reference) - model, effort, and permission-mode settings. - [Keeping Agents Running](Keeping-Agents-Running) - what idle detection does per mode. - [Security](Security) - what skipping permission prompts actually means. diff --git a/docs/wiki/Custom-Model-Endpoints.md b/docs/wiki/Custom-Model-Endpoints.md new file mode 100644 index 000000000..a6eed35f9 --- /dev/null +++ b/docs/wiki/Custom-Model-Endpoints.md @@ -0,0 +1,143 @@ +# Custom Model Endpoints + +Point a harness at your own OpenAI-compatible server instead of its native cloud backend, for +one session at a time. "Custom endpoint" covers **local** hardware (llama.cpp, Ollama, vLLM, +a home GPU rig, DGX Spark, Strix Halo) and **cloud** services (Azure AI Foundry's +OpenAI-compatible endpoint, OpenRouter, a company gateway) alike, anything answering +`GET /v1/models` and `POST /v1/chat/completions` in the standard shape. + +**Off by default.** Turn it on in App Settings → Models → **Custom model endpoints**. + +## Adding an endpoint + +Still in App Settings → Models → Custom model endpoints: + +1. **+ Add endpoint** — give it an id, a label, and the base URL (`http://192.168.1.50:8080`, + say). An API key is optional; most local servers don't check one. +2. **Discover** — fetches the endpoint's own model list over `GET /v1/models` and stores it. +3. Pick a **default model** from what was discovered. This is the model the Run-menu entry + applies directly when only one model is discovered; with two or more, it's just the one + pre-marked in the picker dialog described below, not a silent default. + +Endpoint management is admin-only in multi-user mode, the same as remote hosts and Docker +hosts — these are machine-level infra, not a per-user setting. + +**Model lists refresh themselves.** Every saved endpoint is re-discovered automatically every +5 minutes in the background, so a model the server starts serving later — or stops serving — +shows up without another manual click of **Discover**. One endpoint being unreachable on a +given cycle (powered off, wrong network) never blocks the others from refreshing. + +**Context length is picked up automatically where it can be, safely.** Against a +llama.cpp/llama-swap server, discovery also learns each *currently loaded* model's real +context window and applies it to the launched session (Claude Code today — see below), so +the harness stops assuming a large default window for a model name it doesn't recognise and +overflowing a much smaller real one. It's deliberately never probed for a model that isn't +already loaded, since asking a llama-swap server about an unloaded model can trigger an +actual, slow model swap as a side effect — a model just not currently loaded keeps whatever +context length an earlier cycle already learned for it instead. + +## Running a session against one + +With the setting on and at least one endpoint carrying a discovered model, the **Run** +dropdown grows a **Custom Endpoints** section: one entry per harness that can redirect to a +custom endpoint, per saved endpoint, e.g. "Claude Code (llama.cpp)". Picking one starts a +session on that harness exactly the way its own entry would. It is a one-off "try this +endpoint" action, not a sticky mode — the plain **Run** button still means "this harness, +native cloud" afterward, and a fresh session never inherits whatever the last one was +pointed at. + +**Which model it uses depends on how many the endpoint has discovered.** With exactly one, +the session launches straight away on that model — nothing to choose. With two or more, a +small dialog asks which one to use for this launch before starting the session; the +endpoint's default model, if set, is marked but not auto-picked, so a launch can deliberately +use a different one without changing the saved default. + +**For opencode, Codex, Gemini, Pi, Grok, DeepSeek and OMP, picking an entry launches +straight onto the endpoint** — no restart, because the endpoint is applied before the +session's process ever starts. **Claude still restarts the harness's process in place** — +same tab, same conversation (`--resume`) — after a normal native launch, since that restart +is far less jarring for Claude than for the other seven, whose own TUI can fully +reinitialize on a restart. Either way, every supported harness reads its endpoint config at +process start, never per turn, so there is no live hot-swap while a turn is running. + +Picking an entry that launches a **brand-new** Claude session waits (up to 20 seconds) for it to +finish its own startup before applying — a freshly started CLI reports itself as busy for its +boot sequence, and applying to a genuinely busy session is refused so a real, in-progress +turn is never interrupted out from under you. A session that is still busy after that wait +(a very slow-starting CLI, or one you started typing into right away) surfaces that refusal +as an ordinary error, which now stays on screen with a close button instead of vanishing +after a few seconds — read it, it names the actual reason rather than a generic failure. + +Entries are hidden entirely for a session in a **remote (SSH) or Docker case** — support for +redirecting those hasn't landed yet, see below. The picker also only appears in the desktop +**Run** dropdown; the phone home screen builds its own run picker separately and does not +currently offer these entries. + +**Against llama-swap, applying a selection also starts the actual model load, rather than +waiting on your first prompt to do it.** llama-swap has no "switch model" button of its own +— the only thing that starts a swap is a real request naming the model, and confirmed live: +just applying a selection never reached llama-swap's own logs at all until something asked +it to load. Picking an entry now also sends the smallest real request that will trigger +that load, in the background, the moment the target model isn't already loaded and ready. + +**The centred loading banner shows a live countdown, and a real timeout is an error, not a +shrug.** When it knows the model's discovered file size (its GB figure, when llama-swap +states one), it shows both a rough expected-time estimate and a live countdown against it — +e.g. "Loading qwen3.8-27b (16.4 GB, typically ~1–3 min) on llama-swap — 47s remaining". If +the countdown reaches zero and the model still isn't ready, the banner turns into a sticky +error telling you to check the llama-swap server's own logs, and **the session that load was +for is closed automatically** — a console left open and pointed at a model that never +finished loading would just be confusing to leave sitting there. + +**Claude Code specifically gets two extra fixes applied automatically:** + +- Its discovered context length (see above) is passed through as + `CLAUDE_CODE_MAX_CONTEXT_TOKENS`, so it doesn't send a full-size prompt against a much + smaller real local context and overflow it. +- Its session runs with an isolated `CLAUDE_CONFIG_DIR`, so the injected API key never sits + in the same directory as a stored claude.ai login — that combination is harmless for actual + requests (the API key wins) but the CLI still prints a "both claude.ai and + ANTHROPIC_API_KEY set" warning about it, which this avoids entirely. The isolated directory + keeps a link back to your real session history so the response viewer and similar features + still work for that session. That isolated directory starts with no prior approvals of its + own, so Codeman also pre-approves the injected key the same way answering Claude Code's own + "Detected a custom API key" prompt once would — without it, that prompt would otherwise + reappear on every single launch with nobody there to answer it. + +## Which harnesses actually work + +| Harness | Status | +| ------- | ------ | +| **Claude Code, opencode, Pi, Grok, OMP** | Verified end-to-end against a real local server. | +| **Codex** | Config is correct, but Codex only speaks the Responses API, which llama.cpp-style servers don't implement. A protocol gap, not a Codeman bug. | +| **Gemini** | Fails with an auth error gemini-cli raises once redirected. Unresolved; don't rely on it yet. | +| **DeepSeek** | Reaches the server but gets a consistent 404. Root cause not identified. | +| **Antigravity** | No known custom-endpoint mechanism at all. Not offered. | + +Which harnesses show up in the Run-menu picker is read live off Codeman's own CLI registry, +not a fixed list here, so this table can go stale before this page does — a greyed-out or +missing entry is the more current answer. + +## What it does not do + +- **No remote or Docker sessions yet.** Both restart their agent differently under the hood + (reattaching a durable tmux session rather than relaunching the process), so redirecting + them needs its own plumbing that hasn't been built. +- **No live hot-swap mid-conversation.** Applying a selection always restarts the process. +- **No button to un-point a session from the UI yet.** Clearing back to native cloud is an + HTTP call (`POST .../custom-model {"clear": true}`) or deleting the session; the settings + panel manages saved endpoints, not what a running session is currently pointed at. +- **Nothing is shared with your real cloud credentials.** The endpoint's own key, if any, + never touches your Anthropic/OpenAI/Google login — a custom endpoint is a separate, + explicit choice per session. + +## Security + +An endpoint's base URL can't point at a link-local or cloud-metadata address (both at save +time and against the address it actually resolves to), the same guard Web Tabs uses for +saved dashboards. Endpoint records and any per-session config files a harness needs are +written with owner-only permissions. See +[custom-model-endpoints-plan.md](https://github.com/Ark0N/Codeman/blob/master/docs/custom-model-endpoints-plan.md) +in the repository for the full design reasoning, including why this feature closed a +pre-existing gap in how session environment overrides were guarded rather than opening a new +one. diff --git a/docs/wiki/Settings-Reference.md b/docs/wiki/Settings-Reference.md index 3255f56fb..14b04056e 100644 --- a/docs/wiki/Settings-Reference.md +++ b/docs/wiki/Settings-Reference.md @@ -92,6 +92,10 @@ Model and effort are both **soft defaults**: the model is written into the case' `.claude/settings.local.json` and effort is passed at start, so `/model` and `/effort` inside a session override them at any time. +**Custom model endpoints** (off by default) adds a saved-endpoint list plus a matching +section to the Run dropdown, for pointing a harness at your own OpenAI-compatible server +instead of its native cloud backend. See [Custom Model Endpoints](Custom-Model-Endpoints). + ### Agents & CLIs | Setting | Notes | diff --git a/docs/wiki/_Sidebar.md b/docs/wiki/_Sidebar.md index af84a756e..2e6d54b51 100644 --- a/docs/wiki/_Sidebar.md +++ b/docs/wiki/_Sidebar.md @@ -12,6 +12,7 @@ - [The Dashboard](The-Dashboard) - [Agent CLIs](Agent-CLIs) +- [Custom Model Endpoints](Custom-Model-Endpoints) - [Working With Files](Working-With-Files) - [Input And Voice](Input-And-Voice) - [Mobile Guide](Mobile-Guide) diff --git a/src/config/cli-registry/schema.ts b/src/config/cli-registry/schema.ts index 52cdfbd20..d4c9443a8 100644 --- a/src/config/cli-registry/schema.ts +++ b/src/config/cli-registry/schema.ts @@ -340,6 +340,24 @@ const capabilitiesSchema = z // an env var, so it declares baseUrl/apiKey injection with no model var at all. modelVars: z.array(envName).max(8), launchModel: launchModelTemplate, + // Optional: the env var to carry a discovered per-model context-window size + // (claude's CLAUDE_CODE_MAX_CONTEXT_TOKENS), and/or the env var that isolates + // this session's config/credential directory from the user's real one (claude's + // CLAUDE_CONFIG_DIR) so an injected API key never collides with a stored OAuth + // session. See the customModelInjection doc comment in cli-registry/types.ts. + contextLengthVar: envName.optional(), + configDirVar: envName.optional(), + // Relative path, WITHIN the isolated configDirVar directory, of a trust-dialog + // seed file the CLI itself owns the shape of — claude's `.claude.json` + // `customApiKeyResponses.approved` list, the same field an interactive "Detected + // a custom API key — use it?" prompt writes to on a real terminal. Only makes + // sense alongside configDirVar (an isolated, otherwise-empty directory has none + // of a real profile's prior approvals), and only implemented for the + // 'claude-api-key-responses' shape today — see custom-model-injection-apply.ts. + apiKeyTrustFile: z + .object({ relPath: z.string().min(1).max(80), shape: z.literal('claude-api-key-responses') }) + .strict() + .optional(), }) .strict(), z diff --git a/src/config/cli-registry/stock.ts b/src/config/cli-registry/stock.ts index eb0540829..73978f440 100644 --- a/src/config/cli-registry/stock.ts +++ b/src/config/cli-registry/stock.ts @@ -237,6 +237,12 @@ const CLAUDE: CliEntry = { 'ANTHROPIC_DEFAULT_SONNET_MODEL', 'ANTHROPIC_DEFAULT_HAIKU_MODEL', 'ANTHROPIC_DEFAULT_OPUS_MODEL', + // CLAUDE_CODE_MAX_CONTEXT_TOKENS already matches the CLAUDE_CODE_* allowedPrefix, and + // CLAUDE_CONFIG_DIR is already an allowed exact key (docs/wiki/Agent-CLIs.md), so both + // were already reachable via plain envOverrides before this pair existed — listed here + // only so the custom-model route clamps them the same way as every other injected var. + 'CLAUDE_CODE_MAX_CONTEXT_TOKENS', + 'CLAUDE_CONFIG_DIR', ], gates: { nameFlag: { minVersion: '2.1.224', failClosed: true } }, // Custom Model Endpoint Profiles (docs/custom-model-endpoints-plan.md) — verified by hand against a real @@ -247,6 +253,24 @@ const CLAUDE: CliEntry = { baseUrlVar: 'ANTHROPIC_BASE_URL', apiKeyVar: 'ANTHROPIC_API_KEY', modelVars: ['ANTHROPIC_DEFAULT_SONNET_MODEL', 'ANTHROPIC_DEFAULT_HAIKU_MODEL', 'ANTHROPIC_DEFAULT_OPUS_MODEL'], + // Verified via Claude Code's own docs: CLAUDE_CODE_MAX_CONTEXT_TOKENS overrides the + // assumed context window and applies directly for a model name Claude Code doesn't + // recognize as one of its own — exactly the custom-model case. Without it, Claude Code + // assumes a large (200k) window for any unrecognized model id and never compacts, + // eventually overflowing a much smaller real local context (see plan doc reasoning + // above the interface for the confirmed failure). + contextLengthVar: 'CLAUDE_CODE_MAX_CONTEXT_TOKENS', + // Isolates this session's config/credential directory so an injected ANTHROPIC_API_KEY + // never shares a directory with a stored claude.ai OAuth login — see the doc comment on + // customModelInjection in cli-registry/types.ts for the traded-off side effect. + configDirVar: 'CLAUDE_CONFIG_DIR', + // ⚠️ Required alongside configDirVar, not optional in practice: verified live that an + // isolated, otherwise-empty config directory makes claude stop at an interactive + // "Detected a custom API key — use it?" prompt on EVERY launch, defaulting to "No" with + // no one at the TTY to answer — silently refusing the very key this feature injected. + // Pre-seeding this file's customApiKeyResponses.approved list (verified against a real + // ~/.claude.json after answering the prompt once by hand) answers it in advance instead. + apiKeyTrustFile: { relPath: '.claude.json', shape: 'claude-api-key-responses' }, }, }, overlays: { diff --git a/src/config/cli-registry/types.ts b/src/config/cli-registry/types.ts index 1ba07cb02..1b5269553 100644 --- a/src/config/cli-registry/types.ts +++ b/src/config/cli-registry/types.ts @@ -496,9 +496,44 @@ export interface CliCapabilities { * declares). Absent = the config alone selects the model (claude's env vars, * opencode's blob, codex's top-level `model` key). Applied by the session's * respawn options through the entry's `legacyConfigField`, never by id. + * + * `contextLengthVar` (env kind only): the env var a discovered per-model context-window + * size is written to when known (claude's `CLAUDE_CODE_MAX_CONTEXT_TOKENS`) — without it, + * a CLI that assumes a large default window for an unrecognized model name keeps sending + * full-size prompts against a much smaller local server and eventually overflows its real + * context (verified: a 33.7K-token system prompt against a 16384-token llama-swap model). + * Absent when the CLI has no such override, or the value is unknown for this model. + * + * `configDirVar` (env kind only): the env var that redirects this session's config/ + * credential directory to an isolated, per-session one (claude's `CLAUDE_CONFIG_DIR`), so + * an injected API key never coexists with a stored claude.ai OAuth session in the same + * directory — the CLI still warns "both claude.ai and ANTHROPIC_API_KEY set" when they + * share a directory even though the API key wins for actual requests. Isolating it trades + * that cosmetic warning for a documented side effect: a relocated config directory writes + * transcripts outside `~/.claude/projects`, blinding the response viewer, subagent + * windows, and Read My Mind for that session (see docs/wiki/Agent-CLIs.md). + * + * `apiKeyTrustFile` (env kind only, alongside configDirVar): an isolated config directory + * has none of a real profile's prior "detected a custom API key, use it?" approvals, so + * without this the CLI stops and asks interactively on every single launch — with no one + * at a TTY to answer, that's a hang, not a warning (confirmed live: claude's own default + * answer, "No", would silently refuse to use the very key this feature just injected). + * `relPath`/`shape` name the file (claude's `.claude.json`) and its + * `customApiKeyResponses.approved` field this pre-seeds — the exact field a real answered + * prompt itself writes to, so this isn't bypassing the check, just answering it the same + * way a one-off prior approval on a shared profile already would. */ customModelInjection: - | { kind: 'env'; baseUrlVar: string; apiKeyVar: string; modelVars: string[]; launchModel?: string } + | { + kind: 'env'; + baseUrlVar: string; + apiKeyVar: string; + modelVars: string[]; + launchModel?: string; + contextLengthVar?: string; + apiKeyTrustFile?: { relPath: string; shape: 'claude-api-key-responses' }; + configDirVar?: string; + } | { kind: 'configContentEnv'; envVar: string; template: 'opencode-json'; launchModel?: string } | { kind: 'configDir'; diff --git a/src/custom-model-hosts.ts b/src/custom-model-hosts.ts index 0cde1039a..61ef75f78 100644 --- a/src/custom-model-hosts.ts +++ b/src/custom-model-hosts.ts @@ -40,6 +40,38 @@ export interface CustomModelHost { authStyle?: CustomModelAuthStyle; models?: string[]; lastDiscoveredAt?: string; + /** + * The model the Run-menu picker (docs/custom-model-endpoints-plan.md) applies when + * this endpoint is picked with no further choice — one generated menu entry per + * (CLI, endpoint) pair, not per (CLI, endpoint, model), so it needs a single answer. + * Must be a member of `models` when set; the picker falls back to `models[0]` when + * this is unset, and disables the entry entirely when `models` is empty (nothing to + * default to). Never auto-set on discovery — the previous default staying valid + * after a re-discover is a property worth keeping even if the model list changes. + */ + defaultModelId?: string; + /** + * Discovered context-window size (tokens) per model id, keyed by the same strings as + * `models`. Populated opportunistically during discovery (`custom-model-routes.ts`) from + * llama.cpp/llama-swap's `GET /props?model=` — the plain OpenAI-shaped `/v1/models` + * response has no such field. Only ever probed for a model the server already reports as + * loaded (llama-swap's `status.value === 'loaded'`); an unloaded one is deliberately never + * probed, since llama-swap treats `/props?model=` as a routing hint that can trigger an + * actual (slow, GPU-swapping) model load as a side effect of merely asking. A model this + * has no entry for simply gets no context-length env override applied — never a guess. + */ + modelContextLengths?: Record; + /** + * Discovered file size (GB) per model id, keyed by the same strings as `models`. + * Populated during discovery by parsing llama-swap's own `description` field for an + * auto-discovered model ("Auto-discovered 16.35 GB - parameters auto-fitted by + * llama.cpp") — a hand-configured profile's own description has no such figure and + * correctly gets no entry, never a guess. Used only to label the Run-menu picker's + * "loading model" banner with a rough, unmeasured expected-time estimate + * (`estimateModelLoad()` in session-ui.js) — never a guarantee, and never anything a + * server-side check relies on. + */ + modelSizesGB?: Record; } export function customModelHostsPath(configDir: string): string { diff --git a/src/custom-model-injection-apply.ts b/src/custom-model-injection-apply.ts index 2df6f57d2..f5edea895 100644 --- a/src/custom-model-injection-apply.ts +++ b/src/custom-model-injection-apply.ts @@ -10,7 +10,8 @@ * cli-registry changes" requirement it was written against. */ -import { chmodSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'; +import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync, rmSync, symlinkSync } from 'node:fs'; +import { homedir, platform } from 'node:os'; import { join, dirname } from 'node:path'; import { dataPath } from './config/instance.js'; import type { CliEntry } from './config/cli-registry/types.js'; @@ -48,6 +49,75 @@ export function applyConfigDirInjection(baseDir: string, injection: ConfigDirInj return { [injection.dirEnvVar]: baseDir, ...injection.extraEnv }; } +/** + * Real, shared Claude config directory Codeman's own host process runs under — honors + * `CLAUDE_CONFIG_DIR` the same way `claude-credentials.ts`'s `claudeCredentialsPath()` + * does, so the symlink below points at wherever `~/.claude/projects` actually lives + * rather than assuming the plain default. + */ +function realClaudeConfigDir(): string { + const configured = typeof process.env.CLAUDE_CONFIG_DIR === 'string' && process.env.CLAUDE_CONFIG_DIR.trim(); + return configured || join(homedir(), '.claude'); +} + +/** + * Symlinks `/projects` back to the real, shared `~/.claude/projects`, so an + * isolated `CLAUDE_CONFIG_DIR` (used to keep an injected API key away from a stored OAuth + * session — see `configDirVar` on customModelInjection) doesn't also blind the response + * viewer, subagent windows, and Read My Mind for that session (docs/wiki/Agent-CLIs.md). + * Best-effort: a platform that refuses symlinks (unprivileged Windows without a junction + * fallback working, e.g.) just keeps the pre-existing documented side effect instead of + * failing the whole custom-model apply over a nice-to-have. + */ +function linkSharedProjectsDir(isolatedDir: string): void { + const link = join(isolatedDir, 'projects'); + if (existsSync(link)) return; // already linked (idempotent re-apply) or real dir wrote one + try { + symlinkSync(join(realClaudeConfigDir(), 'projects'), link, platform() === 'win32' ? 'junction' : 'dir'); + } catch { + // best-effort only — response viewer/subagent windows go blind for this session instead + } +} + +/** + * Pre-approves the injected API key in an isolated config directory's trust-dialog state + * (`customModelInjection.apiKeyTrustFile`), so an otherwise-empty directory doesn't make the + * CLI stop at an interactive "Detected a custom API key — use it?" prompt on every single + * launch. Confirmed live: with nobody at the TTY to answer, that prompt's own default + * ("No") silently refuses the very key this feature just injected — this isn't bypassing + * the check, it's answering it the same field a real answered prompt itself writes to + * (verified against a real `~/.claude.json` after answering by hand once). + * + * Merges rather than overwrites: the file may already carry fields the CLI itself wrote on + * an earlier launch in this same isolated directory (machineID, userID, other approved + * keys), and a corrupt or partially-written file (a crash mid-write) is treated as absent + * rather than failing the whole apply over a nice-to-have. + */ +function seedApiKeyTrustFile( + configDir: string, + trustFile: { relPath: string; shape: 'claude-api-key-responses' }, + apiKey: string +): void { + const filePath = join(configDir, trustFile.relPath); + let existing: Record = {}; + try { + existing = JSON.parse(readFileSync(filePath, 'utf8')) as Record; + } catch { + existing = {}; + } + const responses = (existing.customApiKeyResponses ?? {}) as { approved?: unknown; rejected?: unknown }; + const approved = new Set(Array.isArray(responses.approved) ? (responses.approved as string[]) : []); + approved.add(apiKey); + const rejected = Array.isArray(responses.rejected) ? responses.rejected : []; + existing.customApiKeyResponses = { approved: [...approved], rejected }; + try { + writeFileSync(filePath, JSON.stringify(existing, null, 2), { encoding: 'utf8', mode: 0o600 }); + chmodSync(filePath, 0o600); + } catch { + // best-effort only — the interactive prompt returns instead of a hard failure here + } +} + /** Best-effort recursive removal of a previously-written configDir. Never throws. */ export function removeConfigDir(dir: string | undefined): void { if (!dir) return; @@ -79,14 +149,33 @@ export function applyCustomModelInjection( entry: Pick, endpoint: CustomModelEndpoint, modelId: string, - sessionId: string + sessionId: string, + /** Discovered context-window size for `modelId`, if known — see `contextLengthVar`. */ + contextLength?: number ): AppliedCustomModel | undefined { - const injection = buildCustomModelInjection(entry, endpoint, modelId); + const injection = buildCustomModelInjection(entry, endpoint, modelId, contextLength); if (injection.kind === 'unsupported') return undefined; if (injection.kind === 'env') { + // `configDirVar` (claude's CLAUDE_CONFIG_DIR): point it at the same isolated, + // per-session directory the `configDir` kind uses, but write no files into it — an + // empty directory has no stored OAuth credential to conflict with the injected API + // key, which is the whole point. Reusing the same path keyed by sessionId keeps this + // idempotent across a boot-recovery re-apply, same as the configDir kind below. + let envOverrides = injection.envOverrides; + let configDir: string | undefined; + if (injection.configDirVar) { + configDir = customModelConfigDir(sessionId); + mkdirSync(configDir, { recursive: true, mode: 0o700 }); + linkSharedProjectsDir(configDir); + if (injection.apiKeyTrustFile && injection.apiKey) { + seedApiKeyTrustFile(configDir, injection.apiKeyTrustFile, injection.apiKey); + } + envOverrides = { ...envOverrides, [injection.configDirVar]: configDir }; + } return { - envOverrides: injection.envOverrides, - envKeys: Object.keys(injection.envOverrides), + envOverrides, + envKeys: Object.keys(envOverrides), + configDir, launchModel: injection.launchModel, }; } diff --git a/src/custom-model-injection.ts b/src/custom-model-injection.ts index 5f46001c7..1a5ce7821 100644 --- a/src/custom-model-injection.ts +++ b/src/custom-model-injection.ts @@ -44,6 +44,18 @@ export interface EnvInjection { envOverrides: Record; /** See {@link ConfigDirInjection.launchModel}. */ launchModel?: string; + /** + * Name of the env var the caller should point at an isolated, credential-free config + * directory for this session (claude's `CLAUDE_CONFIG_DIR`), from the registry entry's + * `customModelInjection.configDirVar`. The actual directory value isn't computed here — + * this module is pure and has no sessionId to derive one from — the IO wrapper + * (`custom-model-injection-apply.ts`) creates it and adds it to `envOverrides`. + */ + configDirVar?: string; + /** See `customModelInjection.apiKeyTrustFile` — carried through so the IO wrapper can seed it. */ + apiKeyTrustFile?: { relPath: string; shape: 'claude-api-key-responses' }; + /** The literal API key value this injection used, for `apiKeyTrustFile` to pre-approve. */ + apiKey?: string; } export interface ConfigDirInjection { @@ -90,7 +102,9 @@ function quoted(value: string): string { export function buildCustomModelInjection( entry: Pick, endpoint: CustomModelEndpoint, - modelId: string + modelId: string, + /** Discovered context-window size for `modelId`, if known — see `contextLengthVar`. */ + contextLength?: number ): CustomModelInjectionResult { const cap = entry.capabilities.customModelInjection; const apiKey = endpoint.apiKey?.trim() || DEFAULT_API_KEY; @@ -102,7 +116,13 @@ export function buildCustomModelInjection( [cap.apiKeyVar]: apiKey, }; for (const modelVar of cap.modelVars) envOverrides[modelVar] = modelId; - return withLaunchModel({ kind: 'env', envOverrides }, cap.launchModel, modelId); + if (cap.contextLengthVar && contextLength !== undefined && Number.isFinite(contextLength)) { + envOverrides[cap.contextLengthVar] = String(Math.trunc(contextLength)); + } + let result: EnvInjection = withLaunchModel({ kind: 'env', envOverrides }, cap.launchModel, modelId); + if (cap.configDirVar) result = { ...result, configDirVar: cap.configDirVar }; + if (cap.apiKeyTrustFile) result = { ...result, apiKeyTrustFile: cap.apiKeyTrustFile, apiKey }; + return result; } case 'configContentEnv': { diff --git a/src/web/public/i18n.js b/src/web/public/i18n.js index bee8fcab7..3a0fbc5b9 100644 --- a/src/web/public/i18n.js +++ b/src/web/public/i18n.js @@ -286,6 +286,34 @@ 'Prompt sent': '提示已发送', 'Inserted, press Enter in the terminal to send': '已插入,在终端中按 Enter 发送', 'Could not reach the session': '无法连接到会话', + 'Custom model endpoints': '自定义模型端点', + 'Point a harness at your own OpenAI-compatible server (llama.cpp, vLLM, DGX Spark, Azure AI Foundry, OpenRouter) instead of its native cloud backend. When on, the Run menu offers an extra entry per harness that supports it, per saved endpoint.': + '让工具指向您自己的兼容 OpenAI 服务器(llama.cpp、vLLM、DGX Spark、Azure AI Foundry、OpenRouter),而非其原生云端后端。开启后,"运行"菜单会为每个支持此功能的工具、每个已保存的端点新增一个条目。', + 'Enable custom model endpoints': '启用自定义模型端点', + 'Adds a per-endpoint entry to the Run menu for every harness that can redirect to one.': + '为每个可重定向到端点的工具,在"运行"菜单中添加对应条目。', + 'No endpoints yet. Add one below to point a harness at a local or cloud OpenAI-compatible server.': + '暂无端点。请在下方添加一个,以便将工具指向本地或云端的兼容 OpenAI 服务器。', + Discover: '发现模型', + '+ Add endpoint': '+ 添加端点', + 'Add endpoint': '添加端点', + Id: 'ID', + 'Short, stable — used in URLs, never shown to the CLI.': '简短且固定 — 用于 URL,不会展示给 CLI。', + Label: '标签', + 'Base URL': '基础 URL', + 'API key': 'API 密钥', + 'Optional. Left blank on edit keeps the existing key.': '可选。编辑时留空将保留现有密钥。', + 'Auth header': '认证请求头', + 'Never send both — some servers hang indefinitely.': '切勿同时发送两者 — 部分服务器会因此无限期挂起。', + 'Authorization: Bearer (default)': 'Authorization: Bearer(默认)', + 'api-key header (Azure)': 'api-key 请求头(Azure)', + 'Default model': '默认模型', + 'What the Run-menu picker applies for this endpoint. Discover models first.': + '运行菜单选择器会为此端点应用该模型。请先发现可用模型。', + 'Custom Endpoints': '自定义端点', + 'Choose a model': '选择模型', + 'That endpoint no longer exists': '该端点已不存在', + 'No models discovered for this endpoint yet': '此端点尚未发现任何模型', 'Subagent Options': '子智能体选项', 'Enable Tracking': '启用跟踪', 'Active Tab Only': '仅活动标签页', diff --git a/src/web/public/index.html b/src/web/public/index.html index 2ba80243c..9d2e0dc79 100644 --- a/src/web/public/index.html +++ b/src/web/public/index.html @@ -650,6 +650,14 @@

Resume Conversation

+ + + +
+ + + + + + + + + +
+

Custom model endpoints

synced
+

Point a harness at your own OpenAI-compatible server (llama.cpp, vLLM, DGX Spark, Azure AI Foundry, OpenRouter) instead of its native cloud backend. When on, the Run menu offers an extra entry per harness that supports it, per saved endpoint.

+
+
+
+ Enable custom model endpoints + Adds a per-endpoint entry to the Run menu for every harness that can redirect to one. +
+ +
+ + +
+
diff --git a/src/web/public/panels-ui.js b/src/web/public/panels-ui.js index 80e6ce838..5fc16d215 100644 --- a/src/web/public/panels-ui.js +++ b/src/web/public/panels-ui.js @@ -5484,12 +5484,25 @@ Object.assign(CodemanApp.prototype, { return this.showToast(message, type); }, + /** + * `duration` defaults to 0 (sticky, no auto-dismiss) for `error` toasts and + * 3000ms for everything else — an error worth a distinct visual style is + * also worth reading before it vanishes, which a fixed 3s auto-dismiss + * does not guarantee: "Session started on the native backend — could not + * apply the custom endpoint: " is exactly the kind of + * message that needs a moment to read, not a glance. Every toast gets an + * explicit close button regardless of duration, since a sticky one with no + * way to dismiss it would just pile up. A caller can still override either + * default via `opts.duration` (e.g. a deliberately brief success toast, or + * a non-error one that should also stay put). + */ showToast(message, type = 'info', opts = {}) { - const { duration = 3000, action } = opts; + const { duration = type === 'error' ? 0 : 3000, action } = opts; const toast = document.createElement('div'); toast.className = `toast toast-${type}`; const msgSpan = document.createElement('span'); + msgSpan.className = 'toast-message'; msgSpan.textContent = message; toast.appendChild(msgSpan); @@ -5501,6 +5514,20 @@ Object.assign(CodemanApp.prototype, { toast.appendChild(btn); } + let dismissTimer = null; + const dismiss = () => { + if (dismissTimer) clearTimeout(dismissTimer); + toast.classList.remove('show'); + setTimeout(() => toast.remove(), 200); + }; + + const closeBtn = document.createElement('button'); + closeBtn.className = 'toast-close'; + closeBtn.textContent = '×'; + closeBtn.setAttribute('aria-label', 'Dismiss'); + closeBtn.onclick = (e) => { e.stopPropagation(); dismiss(); }; + toast.appendChild(closeBtn); + // Cache toast container reference if (!this._toastContainer) { this._toastContainer = document.querySelector('.toast-container'); @@ -5514,10 +5541,79 @@ Object.assign(CodemanApp.prototype, { requestAnimationFrame(() => toast.classList.add('show')); - setTimeout(() => { - toast.classList.remove('show'); - setTimeout(() => toast.remove(), 200); - }, duration); + if (duration > 0) { + dismissTimer = setTimeout(dismiss, duration); + } + + // Most callers ignore this — a handle exists for a long-running toast a caller needs + // to update or dismiss itself once its own condition resolves (e.g. a "loading model" + // toast a poll loop dismisses once the model reports ready). + return { dismiss, setMessage: (text) => { msgSpan.textContent = text; } }; + }, + + /** + * A prominent, screen-centred status banner — for the small set of messages that are + * genuinely worth interrupting the eye for rather than living in the corner with every + * other toast (currently: a custom-model session's "switching backends" and "loading + * model" states, both of which can sit on screen for well over a minute and are easy to + * mistake for nothing happening). Non-blocking (`pointer-events: none` on the wrapper, + * restored only on the card) — an info banner is never a gate the user has to dismiss to + * keep working. Only one is ever shown at a time (the DOM node is created once and + * reused), which matches every current caller: each hands off to the next rather than + * stacking. + * + * `opts.type` — `'info'` (default, spinner, no close button — a caller ends it itself via + * `dismiss()`) or `'error'` (no spinner — nothing is in progress once this shows — with a + * close button, since a sticky error the user cannot dismiss would just sit there). The + * DOM is rebuilt fresh each call rather than patched, since which children exist differs + * by type; `setMessage` still only ever touches the text node afterwards. + */ + _showCenterStatus(message, opts = {}) { + const { type = 'info' } = opts; + let el = document.getElementById('customModelCenterStatus'); + if (!el) { + el = document.createElement('div'); + el.id = 'customModelCenterStatus'; + document.body.appendChild(el); + } + el.className = `center-status-banner center-status-${type}`; + el.innerHTML = ''; + const dismiss = () => { + el.classList.remove('show'); + setTimeout(() => { + el.hidden = true; + }, 200); + }; + if (type !== 'error') { + const spinner = document.createElement('span'); + spinner.className = 'center-status-spinner'; + spinner.setAttribute('aria-hidden', 'true'); + el.appendChild(spinner); + } + const text = document.createElement('span'); + text.className = 'center-status-text'; + text.textContent = message; + el.appendChild(text); + if (type === 'error') { + const closeBtn = document.createElement('button'); + closeBtn.className = 'center-status-close'; + closeBtn.textContent = '×'; + closeBtn.setAttribute('aria-label', 'Dismiss'); + closeBtn.onclick = (e) => { + e.stopPropagation(); + dismiss(); + }; + el.appendChild(closeBtn); + } + el.hidden = false; + requestAnimationFrame(() => el.classList.add('show')); + return { + dismiss, + setMessage: (next) => { + const t = el.querySelector('.center-status-text'); + if (t) t.textContent = next; + }, + }; }, diff --git a/src/web/public/session-ui.js b/src/web/public/session-ui.js index 67cbfad4c..753618cc6 100644 --- a/src/web/public/session-ui.js +++ b/src/web/public/session-ui.js @@ -461,6 +461,7 @@ Object.assign(CodemanApp.prototype, { if (menu.classList.contains('active')) { this._loadRunModeHistory(); this._refreshRunModeAvailability(menu); + this._refreshCustomModelRunOptions(menu); const close = (ev) => { if (!menu.contains(ev.target)) { menu.classList.remove('active'); @@ -534,6 +535,524 @@ Object.assign(CodemanApp.prototype, { if (dsWeb) dsWeb.style.display = avail.deepseekBinary ? 'flex' : 'none'; }, + /** + * Generates the Run menu's Custom Model Endpoint entries + * (docs/custom-model-endpoints-plan.md): one button per (capable harness, saved + * endpoint) pair, e.g. "Claude Code (llama.cpp)". Hidden entirely when the + * feature is off, no endpoint has a usable default model, or the active case is + * remote/docker (the apply route refuses both — see session-routes.ts). + * + * `window.__codemanCustomModelClis` is server-injected at render time from the + * CLI registry's own `capabilities.customModelInjection` (never a hardcoded id + * list here), so a CLI gaining or losing the capability shows up with no + * frontend change. + */ + async _refreshCustomModelRunOptions(menu) { + const sep = menu.querySelector('#runModeCustomModelSep'); + const header = menu.querySelector('#runModeCustomModelHeader'); + const container = menu.querySelector('#runModeCustomModels'); + if (!container) return; + const hide = () => { + if (sep) sep.style.display = 'none'; + if (header) header.style.display = 'none'; + container.innerHTML = ''; + }; + + const settings = this.loadAppSettingsFromStorage(); + // Matches _refreshRunModeAvailability's own gate: a stock entry for an + // uninstalled CLI is hidden, so a generated one must be too, or a box with + // no codex still offers "Codex (llama.cpp)" and fails at launch. + const capableClis = (window.__codemanCustomModelClis || []).filter((cli) => this.isCliAvailable(cli.id)); + if (!settings.customModelEndpointsEnabled || capableClis.length === 0) return hide(); + + const caseName = document.getElementById('quickStartCase')?.value; + const activeCase = caseName ? (this.cases || []).find((c) => c.name === caseName) : null; + if (activeCase?.location === 'remote' || activeCase?.location === 'docker') return hide(); + + // GET /api/model-endpoints wraps its body in the { success, data } envelope + // like every other /api route (server.ts's preSerialization hook applies to + // arrays too) — _apiJson() unwraps it. A raw fetch().json() here would + // silently see the envelope object instead of the array and hide this + // section unconditionally. + const hosts = await this._apiJson('/api/model-endpoints'); + if (!Array.isArray(hosts) || hosts.length === 0) return hide(); + + const rows = []; + for (const host of hosts) { + const models = host.models || []; + if (models.length === 0) continue; // nothing discovered yet — the settings panel explains why + const modelId = host.defaultModelId || models[0]; + for (const cli of capableClis) { + // escapeHtml(JSON.stringify(...)) on EVERY arg, not just the untrusted + // one: JSON.stringify's own double quotes would otherwise terminate this + // double-quoted attribute at the first one, and everything after parses + // as raw tag content rather than a quoted string — which is what turns + // modelId (server-controlled, from the endpoint's own /v1/models reply, + // not this box's) into markup instead of inert data. Same idiom as + // deleteCase's onclick a few hundred lines down. + const args = [cli.id, host.id].map((v) => escapeHtml(JSON.stringify(v))).join(', '); + rows.push(` + `); + } + } + if (rows.length === 0) return hide(); + if (sep) sep.style.display = ''; + if (header) header.style.display = ''; + container.innerHTML = rows.join(''); + }, + + /** + * Decides whether picking a Run-menu Custom Endpoint entry can launch + * straight away or needs to ask which model first. Re-fetches the endpoint + * rather than trusting anything cached from the menu render: the models + * list (or the default) could have changed — a re-discovery cycle running + * every 5 minutes in the background, or an edit in the settings panel — + * between opening the dropdown and clicking a row. + */ + async selectCustomModelEntry(mode, endpointId) { + document.getElementById('runModeMenu')?.classList.remove('active'); + const hosts = await this._apiJson('/api/model-endpoints'); + const host = (hosts || []).find((h) => h.id === endpointId); + if (!host) { + this.showToast('That endpoint no longer exists', 'error'); + return; + } + const models = host.models || []; + if (models.length === 0) { + this.showToast('No models discovered for this endpoint yet', 'warning'); + return; + } + // Exactly one model: nothing to choose, so asking would just be an extra + // click for the same answer every time. Two or more: always ask, even + // with a defaultModelId set — the point of asking is letting THIS launch + // differ from the default, not just confirming it. + if (models.length === 1) { + return this.runCustomModelEntry(mode, endpointId, models[0]); + } + this._openCustomModelPickModal(mode, host); + }, + + /** Renders the "which model" picker for a (harness, endpoint) pair with more than one discovered model. */ + _openCustomModelPickModal(mode, host) { + const modal = document.getElementById('customModelPickModal'); + const list = document.getElementById('customModelPickList'); + if (!modal || !list) return; + this._pendingCustomModelPick = { mode, endpointId: host.id }; + const cliLabel = (window.__codemanCustomModelClis || []).find((c) => c.id === mode)?.label || mode; + // A static title (translatable by i18n.js's exact-string walker) plus a + // dynamic hint carrying the specifics — same split webviewModalTitle uses, + // since the walker cannot i18n a string a variable is already spliced into. + document.getElementById('customModelPickTitle').textContent = 'Choose a model'; + document.getElementById('customModelPickHint').textContent = + `${cliLabel} → ${host.label} — ${(host.models || []).length} models discovered.`; + list.innerHTML = (host.models || []) + .map((m) => { + const isDefault = m === host.defaultModelId; + const arg = escapeHtml(JSON.stringify(m)); + return ` + `; + }) + .join(''); + modal.classList.add('active'); + }, + + closeCustomModelPickModal() { + document.getElementById('customModelPickModal')?.classList.remove('active'); + this._pendingCustomModelPick = null; + }, + + /** + * In-app replacement for a native `confirm()` popup, used specifically for the + * llama-swap "this will unload it for session X" warning (both launch paths below) — + * a browser-chrome dialog there looked out of place next to the rest of the app's own + * modals. Resolves true/false the same way `confirm()` would; `_resolveModelSwapConfirm` + * (the modal's own Cancel/Switch-anyway buttons, and its backdrop click) is what settles + * the returned promise. + */ + _confirmModelSwap(message) { + const modal = document.getElementById('customModelSwapConfirmModal'); + const messageEl = document.getElementById('customModelSwapConfirmMessage'); + if (messageEl) messageEl.textContent = message; + modal?.classList.add('active'); + return new Promise((resolve) => { + this._resolveModelSwapConfirmPromise = resolve; + }); + }, + + /** Called by the modal's Cancel/Switch-anyway buttons and its backdrop click. */ + _resolveModelSwapConfirm(proceed) { + document.getElementById('customModelSwapConfirmModal')?.classList.remove('active'); + const resolve = this._resolveModelSwapConfirmPromise; + this._resolveModelSwapConfirmPromise = null; + resolve?.(proceed); + }, + + /** A model row in the picker modal was clicked: close it and launch with that choice. */ + chooseCustomModelAndRun(modelId) { + const pending = this._pendingCustomModelPick; + this.closeCustomModelPickModal(); + if (!pending) return; // modal reopened/closed from elsewhere between render and click + void this.runCustomModelEntry(pending.mode, pending.endpointId, modelId); + }, + + /** + * Runs a session on `mode` and immediately applies `endpointId`/`modelId` to it + * via POST /api/sessions/:id/custom-model (see session-routes.ts) — the same + * restart-in-place apply path the (not-yet-built) endpoint-management surface + * would use for an already-running session. A custom-model run is a one-off + * "try this endpoint" action, not a sticky mode. + * + * Routes through run() itself, via a temporary `_runMode` swap, rather than a + * parallel dispatch table: that is what gives this the same in-flight lock + * every other Run click gets (CLAUDE.md, Run launch synchronization — the lock + * exists so a double click cannot create duplicate sessions with the same + * `w-` name, and it guards the OTHER direction too: without it, the + * main Run button could start a second concurrent launch while this one was + * still resolving), and it means a CLI whose customModelInjection recipe + * lands later needs no update here, only in run()'s own dispatch. The swap + * never persists — setRunMode() would sync it to the server as the user's new + * default, which a one-off endpoint run must not do — and is restored in + * `finally` even if run() throws. + */ + /** + * Dispatches to the ONE-SHOT launch path (below) for every custom-model-eligible CLI + * except claude, which still goes through the restart-after-native-boot path + * (`_runCustomModelEntryViaRestart`): claude's own `runClaude()` carries multi-tab + * launch and a docker-config-drift confirm/retry loop neither of the other seven + * functions has, and folding those into the one-shot flow is unstarted, separate work. + * The other seven (opencode/codex/gemini/pi/grok/deepseek/omp) are each a single, + * simple launch, so they get the one-shot path — the one visibly worth it, since a + * native-boot-then-restart is far more jarring on a CLI whose TUI fully reinitializes + * (Codex, confirmed live) than on claude's own `--resume`-based restart. + */ + async runCustomModelEntry(mode, endpointId, modelId) { + if (mode === 'claude') { + return this._runCustomModelEntryViaRestart(mode, endpointId, modelId); + } + return this._runCustomModelEntryOneShot(mode, endpointId, modelId); + }, + + /** + * Launches directly on the endpoint — no restart, so no visible relaunch. Stashes the + * pick on `_pendingCustomModelForLaunch` for the targeted run() function to read + * and fold into its own /api/quick-start body (see `_quickStartWithCustomModelConfirm`); + * cleared in `finally` the same way `_runMode`'s temporary swap is, even if run() throws. + */ + async _runCustomModelEntryOneShot(mode, endpointId, modelId) { + document.getElementById('runModeMenu')?.classList.remove('active'); + const previousRunMode = this._runMode; + const tabCountEl = document.getElementById('tabCount'); + const prevTabCount = tabCountEl?.value; + this._runMode = mode; + this._pendingCustomModelForLaunch = { endpointId, modelId }; + if (tabCountEl) tabCountEl.value = '1'; + try { + await this.run(); + } finally { + this._runMode = previousRunMode; + this._pendingCustomModelForLaunch = undefined; + if (tabCountEl && prevTabCount !== undefined) tabCountEl.value = prevTabCount; + } + + // run() (via _quickStartWithCustomModelConfirm) reports its own launch error or + // cancellation via toast and leaves this unset — nothing more to do here then. + const result = this._lastCustomModelLaunchResult; + this._lastCustomModelLaunchResult = undefined; + if (result?.modelSwapInProgress) { + void this._watchLlamaSwapLoading(endpointId, modelId, result.sessionId); + } + }, + + /** + * POSTs a /api/quick-start body already carrying `customModel` (see the run() + * call sites below), showing the same llama-swap "this will unload it for session X" + * warning the restart path's `_applyCustomModelToSession` shows when the route asks + * for confirmation, and retrying with `confirmed: true` on accept. Stashes the final + * response's payload on `_lastCustomModelLaunchResult` for + * `_runCustomModelEntryOneShot` to read `modelSwapInProgress` off afterward — run()'s + * eleven per-mode dispatch targets have no shared return-value contract of their own, + * so a side channel here is simpler than threading one through every one of them. + */ + async _quickStartWithCustomModelConfirm(bodyObj) { + const post = async (body) => { + const res = await fetch('/api/quick-start', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }); + return res.json(); + }; + let data = await post(bodyObj); + if (data?.data?.requiresConfirmation) { + const { currentlyLoadedModel, affectedSessions } = data.data; + const names = affectedSessions.map((s) => s.name || s.id).join(', '); + const proceed = await this._confirmModelSwap( + `${names} ${affectedSessions.length === 1 ? 'is' : 'are'} currently using ` + + `${currentlyLoadedModel} on this endpoint. Switching will unload it for ` + + `${affectedSessions.length === 1 ? 'that session' : 'those sessions'} too. Continue?` + ); + if (!proceed) { + this._lastCustomModelLaunchResult = undefined; + return { success: false, error: 'Model switch cancelled' }; + } + data = await post({ ...bodyObj, customModel: { ...bodyObj.customModel, confirmed: true } }); + } + this._lastCustomModelLaunchResult = data?.success !== false ? data?.data : undefined; + return data; + }, + + /** The restart-after-native-boot path — see `runCustomModelEntry`'s own comment for + * which CLIs still use this one. */ + async _runCustomModelEntryViaRestart(mode, endpointId, modelId) { + document.getElementById('runModeMenu')?.classList.remove('active'); + + const previousRunMode = this._runMode; + const before = this.activeSessionId; + const tabCountEl = document.getElementById('tabCount'); + const prevTabCount = tabCountEl?.value; + this._runMode = mode; + if (tabCountEl) tabCountEl.value = '1'; + try { + await this.run(); + } finally { + this._runMode = previousRunMode; + if (tabCountEl && prevTabCount !== undefined) tabCountEl.value = prevTabCount; + } + + // run() reports its own errors via toast. Every run*() function handles its + // own failure internally and returns normally rather than throwing or + // leaving activeSessionId null, so a declined/failed launch (missing CLI, a + // caught exception, isBusy on the session the launch would have targeted) + // falls through to here with the PREVIOUSLY active session still active. + // Requiring the id to have actually changed — not just to be non-null — is + // what stops that case from silently re-pointing and restarting whatever + // session the user was already looking at. + const sessionId = this.activeSessionId; + if (!sessionId || sessionId === before) return; + + // Claude just launched on the NATIVE backend and is about to be restarted onto + // the endpoint — without something saying so, that native boot (which can talk + // to Opus for a moment) reads as "the endpoint didn't apply" rather than "the + // switch hasn't happened yet". Prominent and screen-centred (not a corner toast) + // since this can sit on screen for a while; sticky until the apply below settles + // one way or the other, or hands off to _watchLlamaSwapLoading's own banner. + const switchingToast = this._showCenterStatus(`Claude started — switching to ${endpointId}…`); + + // A freshly launched CLI reports its OWN startup as 'busy' (spinner, the + // workspace-trust check, whatever else it does before its first prompt) — + // measured landing well before this line reliably reaches it — and the + // apply route's isBusy() guard correctly refuses to restart a session + // mid-turn, "mid-turn" included, which this fresh boot looks exactly + // like from the outside. Give it a bounded chance to settle first rather + // than raising a false "Session is busy" on every single launch. Per the + // wait contract a timeout here is a normal 200, never an error — a + // session still busy after 20s just reaches the apply call below and + // gets the route's own honest, now-visible SESSION_BUSY error instead of + // this guessing about it. + await this._apiJson(`/api/sessions/${sessionId}/wait?until=idle&timeout=20000`); + + // _apiJson() (used everywhere else in this file) unwraps a success body to + // its `data`, but on failure it swallows the response entirely and returns + // null — exactly the `error` text a caller needs to tell "the endpoint is + // unreachable" apart from "the CLI can't be redirected", "not one of the + // discovered models", or "this is a Docker/remote session". Go through the + // raw response here instead so a failure is diagnosable, not just present. + let { ok, data, res } = await this._applyCustomModelToSession(sessionId, endpointId, modelId); + + // A success body comes back as {success:true, data:{...}} (server.ts's preSerialization + // envelope), but a route-level error is {success:false, error, errorCode} with no nested + // data — createErrorResponse() never wraps one. `payload` below is only ever meaningful + // once `data.success !== false`. + let payload = data?.success !== false ? data?.data : undefined; + + // llama-swap runs one model at a time: switching would unload it out from under + // another session actively using it. The route only asks when that's actually true + // (never just because a swap is needed at all) — confirming re-sends the exact same + // call with `confirmed: true` so the route skips the check the second time. + if (ok && payload?.requiresConfirmation) { + const names = payload.affectedSessions.map((s) => s.name || s.id).join(', '); + const proceed = await this._confirmModelSwap( + `${names} ${payload.affectedSessions.length === 1 ? 'is' : 'are'} currently using ` + + `${payload.currentlyLoadedModel} on this endpoint. Switching to ${modelId} will unload it ` + + `for ${payload.affectedSessions.length === 1 ? 'that session' : 'those sessions'} too. Continue?` + ); + if (!proceed) { + switchingToast?.dismiss(); + this.showToast('Kept the native backend — model switch cancelled', 'info'); + return; + } + ({ ok, data, res } = await this._applyCustomModelToSession(sessionId, endpointId, modelId, true)); + payload = data?.success !== false ? data?.data : undefined; + } + + if (!ok || !data || data.success === false) { + switchingToast?.dismiss(); + const detail = data?.error ? `: ${data.error}` : res ? ` (HTTP ${res.status})` : ' (request failed)'; + this.showToast(`Session started on the native backend — could not apply the custom endpoint${detail}`, 'error'); + return; + } + + // The apply above already succeeded — the session IS pointed at the endpoint — but + // llama-swap itself may still be unloading the old model and loading this one, which + // can take well over a minute. Without this, a prompt sent during that window either + // hangs silently or (the bug this whole feature exists to fix) gets answered by + // whatever was loaded a moment ago, reading as "it's still using the wrong model." + // Hand off to its own sticky toast rather than stacking a second one on top. + if (payload?.modelSwapInProgress) { + switchingToast?.dismiss(); + void this._watchLlamaSwapLoading(endpointId, modelId, sessionId); + return; + } + + switchingToast?.setMessage(`Pointed at ${endpointId} — restarting the session...`); + setTimeout(() => switchingToast?.dismiss(), 3000); + }, + + /** POST /api/sessions/:id/custom-model, returning {ok, data, res} rather than throwing — + * see runCustomModelEntry's own comment for why this goes through `_api()` (raw fetch) + * rather than `_apiJson()`: a failure's `error` detail must survive to the caller. */ + async _applyCustomModelToSession(sessionId, endpointId, modelId, confirmed) { + const res = await this._api(`/api/sessions/${sessionId}/custom-model`, { + method: 'POST', + body: confirmed ? { endpointId, modelId, confirmed } : { endpointId, modelId }, + }); + const data = res ? await res.json().catch(() => null) : null; + return { ok: !!res, data, res }; + }, + + /** + * Best-effort: looks up `modelId`'s discovered file size (GB) off the endpoint's own + * saved host record (`CustomModelHost.modelSizesGB`, populated during discovery by + * parsing llama-swap's own `description` field for an auto-discovered model). Returns + * `undefined` for a hand-configured profile with no parseable size, an unreachable + * server, or any other failure — never a guess. + */ + async _lookupModelSizeGB(endpointId, modelId) { + const hosts = await this._apiJson('/api/model-endpoints').catch(() => null); + if (!Array.isArray(hosts)) return undefined; + const host = hosts.find((h) => h.id === endpointId); + const size = host?.modelSizesGB?.[modelId]; + return typeof size === 'number' && Number.isFinite(size) && size > 0 ? size : undefined; + }, + + /** + * Rough, UNMEASURED load-time brackets by model file size, for the loading banner's text + * and as a size-scaled fallback timeout (larger models get longer before + * _watchLlamaSwapLoading gives up and warns). Sourced from typical local NVMe/SSD + * throughput for llama.cpp's mmap-and-warm sequence — NOT benchmarked against any real + * endpoint's actual hardware/storage (network storage, spinning disks, or a GPU with + * less VRAM than the model needs would all be meaningfully slower), so the label is an + * expectation-setter, never a guarantee. `maxGB` is the bracket's own upper bound + * (inclusive); brackets are checked in order, so list them smallest first. + */ + _MODEL_LOAD_TIME_MATRIX: [ + { maxGB: 2, label: '~5–15s', waitMs: 60000 }, + { maxGB: 8, label: '~15–45s', waitMs: 120000 }, + { maxGB: 16, label: '~30–90s', waitMs: 180000 }, + { maxGB: 32, label: '~1–3 min', waitMs: 300000 }, + { maxGB: 64, label: '~2–5 min', waitMs: 480000 }, + { maxGB: Infinity, label: '~5+ min', waitMs: 900000 }, + ], + + /** `sizeGB` -> `{label, waitMs}` from `_MODEL_LOAD_TIME_MATRIX`, or `null` when `sizeGB` + * is unknown (no estimate is always safer than a fabricated one). */ + _estimateModelLoad(sizeGB) { + if (typeof sizeGB !== 'number' || !Number.isFinite(sizeGB) || sizeGB <= 0) return null; + return this._MODEL_LOAD_TIME_MATRIX.find((bracket) => sizeGB <= bracket.maxGB) ?? null; + }, + + /** `ms` -> `"1m 08s remaining"` / `"8s remaining"`, for the loading banner's live countdown. */ + _formatRemaining(ms) { + const totalSec = Math.max(0, Math.ceil(ms / 1000)); + const mins = Math.floor(totalSec / 60); + const secs = totalSec % 60; + return mins > 0 ? `${mins}m ${String(secs).padStart(2, '0')}s remaining` : `${secs}s remaining`; + }, + + /** + * Polls llama-swap's own `/running` (via the read-only running-status route) until + * `modelId` reports `state: 'ready'`, showing a sticky banner with a live countdown the + * whole time so a slow unload/reload (measured well over a minute for a large model) + * reads as "loading, N seconds left", never as silence or a wrong answer from whatever + * was loaded before. Checks immediately (a fast load, or a re-apply onto an + * already-ready model, shouldn't wait a full interval to say so), then every + * `pollIntervalMs`. Bounded at `maxWaitMs` — defaults to a rough, size-scaled estimate + * (`_estimateModelLoad`) when the model's discovered size is known, falling back to a + * flat 5 minutes when it isn't. + * + * If the countdown reaches zero with the model still not ready, this is a real failure, + * not a "keep waiting" — the banner turns into a sticky error naming the llama-swap + * server's own logs as where to look, and `sessionId` (the session this was launched + * for) is closed automatically: a console left open and pointed at a model that never + * finished loading is worse than no console at all. + * + * `_watchLlamaSwapGeneration` guards against two overlapping calls (a second launch + * started before the first one's loop finished) clobbering each other's banner: + * `_showCenterStatus` reuses one shared DOM node, so an older loop's `dismiss()`/message + * update firing after a newer one has already taken over the banner would otherwise hide + * or overwrite the WRONG one, or close the WRONG session. Each call claims the counter + * as its own "generation" and checks it still owns it before touching either. + * + * `pollIntervalMs`/`maxWaitMs` exist to let a test drive this in milliseconds instead of + * minutes — real callers never pass `maxWaitMs`, which is what keeps the size-scaled + * default live here rather than only in a test fixture. + */ + async _watchLlamaSwapLoading(endpointId, modelId, sessionId, pollIntervalMs = 1000, maxWaitMs) { + const generation = (this._watchLlamaSwapGeneration = (this._watchLlamaSwapGeneration || 0) + 1); + const isCurrent = () => this._watchLlamaSwapGeneration === generation; + const sizeGB = await this._lookupModelSizeGB(endpointId, modelId); + const estimate = this._estimateModelLoad(sizeGB); + const effectiveMaxWaitMs = maxWaitMs ?? estimate?.waitMs ?? 300000; + if (!isCurrent()) return; // a newer launch already took over before the lookup even finished + const sizeSuffix = sizeGB + ? ` (${sizeGB.toFixed(1)} GB${estimate ? `, typically ${estimate.label}` : ''})` + : ''; + const baseMessage = `Loading ${modelId}${sizeSuffix} on ${endpointId} —`; + // Prominent and screen-centred, not a corner toast — a real llama-swap model load can + // sit on screen for well over a minute, easy to mistake for nothing happening there. + const deadline = Date.now() + effectiveMaxWaitMs; + const toast = this._showCenterStatus(`${baseMessage} ${this._formatRemaining(deadline - Date.now())}`); + while (Date.now() < deadline) { + const status = await this._apiJson(`/api/model-endpoints/${encodeURIComponent(endpointId)}/running-status`); + if (!isCurrent()) return; // a newer launch took over the banner — this loop is done + if (!status) { + // transient failure — keep waiting rather than giving up early + } else if (!status.isLlamaSwap) { + // Endpoint changed under us, or wasn't llama-swap after all — nothing more to + // watch for, and not a failure worth a toast of its own. + toast?.dismiss(); + return; + } else if (status.running.some((r) => r.model === modelId && r.state === 'ready')) { + toast?.dismiss(); + this.showToast(`${modelId} is ready`, 'success', { duration: 2500 }); + return; + } + if (!isCurrent()) return; + toast?.setMessage(`${baseMessage} ${this._formatRemaining(deadline - Date.now())}`); + await new Promise((resolve) => setTimeout(resolve, pollIntervalMs)); + } + if (!isCurrent()) return; + this._showCenterStatus( + `${modelId} did not finish loading on ${endpointId} within the expected time. ` + + `Check the llama-swap server logs for details.` + + (sessionId ? ' The session has been closed.' : ''), + { type: 'error' } + ); + if (sessionId) { + try { + await this.closeSession(sessionId); + } catch { + // closeSession already reports its own failure via toast — nothing more to do here + } + } + }, + /** * Start the DeepSeek Harness browser UI and open it as a Codeman web tab. * @@ -1285,20 +1804,16 @@ Object.assign(CodemanApp.prototype, { // Quick-start with opencode mode (auto-allow tools by default). // No `effort` field — it's Claude-specific (OpenCode has no /effort). const envOverrides = this.buildEnvOverrides(this.getCaseSettings(caseName), this.loadAppSettingsFromStorage()); - const res = await fetch('/api/quick-start', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - caseName, - mode: 'opencode', - sessionName: `w${this._nextCaseSessionStartNumber(caseName)}-${caseName}`, - ...(isRemote ? {} : { - openCodeConfig: { autoAllowTools: true }, - ...(Object.keys(envOverrides).length > 0 ? { envOverrides } : {}), - }), - }) + const data = await this._quickStartWithCustomModelConfirm({ + caseName, + mode: 'opencode', + sessionName: `w${this._nextCaseSessionStartNumber(caseName)}-${caseName}`, + ...(isRemote ? {} : { + openCodeConfig: { autoAllowTools: true }, + ...(Object.keys(envOverrides).length > 0 ? { envOverrides } : {}), + ...(this._pendingCustomModelForLaunch ? { customModel: this._pendingCustomModelForLaunch } : {}), + }), }); - const data = await res.json(); if (!data.success) throw new Error(data.error || 'Failed to start OpenCode'); await this._ensureCreatedSessionVisible(data.data.sessionId, data.data.session); @@ -1339,24 +1854,20 @@ Object.assign(CodemanApp.prototype, { const globalSettings = this.loadAppSettingsFromStorage(); const envOverrides = this.buildEnvOverrides(this.getCaseSettings(caseName), globalSettings); - const res = await fetch('/api/quick-start', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - caseName, - mode: 'codex', - sessionName: `w${this._nextCaseSessionStartNumber(caseName)}-${caseName}`, - ...(isRemote ? {} : { - codexConfig: { - dangerouslyBypassApprovals: globalSettings.codexDangerouslyBypassApprovals ?? false, - animations: globalSettings.codexAnimationsEnabled ?? false, - renderMode: 'hybrid', - }, - ...(Object.keys(envOverrides).length > 0 ? { envOverrides } : {}), - }), - }) + const data = await this._quickStartWithCustomModelConfirm({ + caseName, + mode: 'codex', + sessionName: `w${this._nextCaseSessionStartNumber(caseName)}-${caseName}`, + ...(isRemote ? {} : { + codexConfig: { + dangerouslyBypassApprovals: globalSettings.codexDangerouslyBypassApprovals ?? false, + animations: globalSettings.codexAnimationsEnabled ?? false, + renderMode: 'hybrid', + }, + ...(Object.keys(envOverrides).length > 0 ? { envOverrides } : {}), + ...(this._pendingCustomModelForLaunch ? { customModel: this._pendingCustomModelForLaunch } : {}), + }), }); - const data = await res.json(); if (!data.success) throw new Error(data.error || 'Failed to start Codex'); await this._ensureCreatedSessionVisible(data.data.sessionId, data.data.session); @@ -1396,20 +1907,16 @@ Object.assign(CodemanApp.prototype, { } const envOverrides = this.buildEnvOverrides(this.getCaseSettings(caseName), this.loadAppSettingsFromStorage()); - const res = await fetch('/api/quick-start', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - caseName, - mode: 'gemini', - sessionName: `w${this._nextCaseSessionStartNumber(caseName)}-${caseName}`, - ...(isRemote ? {} : { - geminiConfig: { approvalMode: 'yolo' }, - ...(Object.keys(envOverrides).length > 0 ? { envOverrides } : {}), - }), - }) + const data = await this._quickStartWithCustomModelConfirm({ + caseName, + mode: 'gemini', + sessionName: `w${this._nextCaseSessionStartNumber(caseName)}-${caseName}`, + ...(isRemote ? {} : { + geminiConfig: { approvalMode: 'yolo' }, + ...(Object.keys(envOverrides).length > 0 ? { envOverrides } : {}), + ...(this._pendingCustomModelForLaunch ? { customModel: this._pendingCustomModelForLaunch } : {}), + }), }); - const data = await res.json(); if (!data.success) throw new Error(data.error || 'Failed to start Gemini'); await this._ensureCreatedSessionVisible(data.data.sessionId, data.data.session); @@ -1507,17 +2014,13 @@ Object.assign(CodemanApp.prototype, { } const envOverrides = this.buildEnvOverrides(this.getCaseSettings(caseName), this.loadAppSettingsFromStorage()); - const res = await fetch('/api/quick-start', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - caseName, - mode: 'pi', - sessionName: `w${this._nextCaseSessionStartNumber(caseName)}-${caseName}`, - ...(isRemote || Object.keys(envOverrides).length === 0 ? {} : { envOverrides }), - }) + const data = await this._quickStartWithCustomModelConfirm({ + caseName, + mode: 'pi', + sessionName: `w${this._nextCaseSessionStartNumber(caseName)}-${caseName}`, + ...(isRemote || Object.keys(envOverrides).length === 0 ? {} : { envOverrides }), + ...(!isRemote && this._pendingCustomModelForLaunch ? { customModel: this._pendingCustomModelForLaunch } : {}), }); - const data = await res.json(); if (!data.success) throw new Error(data.error || 'Failed to start Pi'); await this._ensureCreatedSessionVisible(data.data.sessionId, data.data.session); @@ -1555,19 +2058,15 @@ Object.assign(CodemanApp.prototype, { } const envOverrides = this.buildEnvOverrides(this.getCaseSettings(caseName), this.loadAppSettingsFromStorage()); - const res = await fetch('/api/quick-start', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - caseName, - mode: 'omp', - sessionName: `w${this._nextCaseSessionStartNumber(caseName)}-${caseName}`, - ...(isRemote ? {} : { - ...(Object.keys(envOverrides).length > 0 ? { envOverrides } : {}), - }), - }) + const data = await this._quickStartWithCustomModelConfirm({ + caseName, + mode: 'omp', + sessionName: `w${this._nextCaseSessionStartNumber(caseName)}-${caseName}`, + ...(isRemote ? {} : { + ...(Object.keys(envOverrides).length > 0 ? { envOverrides } : {}), + ...(this._pendingCustomModelForLaunch ? { customModel: this._pendingCustomModelForLaunch } : {}), + }), }); - const data = await res.json(); if (!data.success) throw new Error(data.error || 'Failed to start OMP'); await this._ensureCreatedSessionVisible(data.data.sessionId, data.data.session); @@ -1614,20 +2113,16 @@ Object.assign(CodemanApp.prototype, { } const envOverrides = this.buildEnvOverrides(this.getCaseSettings(caseName), this.loadAppSettingsFromStorage()); - const res = await fetch('/api/quick-start', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - caseName, - mode: 'grok', - sessionName: `w${this._nextCaseSessionStartNumber(caseName)}-${caseName}`, - ...(isRemote ? {} : { - grokConfig: { alwaysApprove: true }, - ...(Object.keys(envOverrides).length > 0 ? { envOverrides } : {}), - }), - }) + const data = await this._quickStartWithCustomModelConfirm({ + caseName, + mode: 'grok', + sessionName: `w${this._nextCaseSessionStartNumber(caseName)}-${caseName}`, + ...(isRemote ? {} : { + grokConfig: { alwaysApprove: true }, + ...(Object.keys(envOverrides).length > 0 ? { envOverrides } : {}), + ...(this._pendingCustomModelForLaunch ? { customModel: this._pendingCustomModelForLaunch } : {}), + }), }); - const data = await res.json(); if (!data.success) throw new Error(data.error || 'Failed to start Grok'); await this._ensureCreatedSessionVisible(data.data.sessionId, data.data.session); @@ -1692,20 +2187,16 @@ Object.assign(CodemanApp.prototype, { } const envOverrides = this.buildEnvOverrides(this.getCaseSettings(caseName), this.loadAppSettingsFromStorage()); - const res = await fetch('/api/quick-start', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - caseName, - mode: 'deepseek', - sessionName: `w${this._nextCaseSessionStartNumber(caseName)}-${caseName}`, - ...(isRemote ? {} : { - deepSeekConfig: { permissionMode: 'danger-full-access' }, - ...(Object.keys(envOverrides).length > 0 ? { envOverrides } : {}), - }), - }) + const data = await this._quickStartWithCustomModelConfirm({ + caseName, + mode: 'deepseek', + sessionName: `w${this._nextCaseSessionStartNumber(caseName)}-${caseName}`, + ...(isRemote ? {} : { + deepSeekConfig: { permissionMode: 'danger-full-access' }, + ...(Object.keys(envOverrides).length > 0 ? { envOverrides } : {}), + ...(this._pendingCustomModelForLaunch ? { customModel: this._pendingCustomModelForLaunch } : {}), + }), }); - const data = await res.json(); if (!data.success) throw new Error(data.error || 'Failed to start DeepSeek'); await this._ensureCreatedSessionVisible(data.data.sessionId, data.data.session); diff --git a/src/web/public/settings-ui.js b/src/web/public/settings-ui.js index 79bee3c07..1ade54a40 100644 --- a/src/web/public/settings-ui.js +++ b/src/web/public/settings-ui.js @@ -395,6 +395,13 @@ Object.assign(CodemanApp.prototype, { document.getElementById('appSettingsShowUltracodeAgents').checked = settings.showUltracodeAgents ?? defaults.showUltracodeAgents ?? false; // Approvals Inbox: synced, default OFF (opt-in; only an explicit true enables). document.getElementById('appSettingsApprovalsInbox').checked = settings.approvalsInboxEnabled === true; + // Custom Model Endpoint Profiles: synced, default OFF. The toggle governs both + // the Run-menu picker's generated entries and this settings panel's visibility; + // the endpoint list itself is server state, loaded on demand below. + document.getElementById('appSettingsCustomModelEndpoints').checked = settings.customModelEndpointsEnabled === true; + // Assigning .checked above does not fire onchange, so the body's visibility + // (and its lazy load) needs an explicit sync on every open, not just a save. + this.applyCustomModelEndpointsVisibility(); // Read My Mind: synced, default OFF (opt-in; capture + prediction cost real tokens). document.getElementById('appSettingsReadMyMind').checked = settings.readMyMindEnabled === true; document.getElementById('appSettingsUltracodeFloatingWindows').checked = @@ -509,6 +516,9 @@ Object.assign(CodemanApp.prototype, { document.getElementById('appSettingsNiceValue').value = niceSettings.niceValue ?? 10; // Model configuration (loaded from server) this.loadModelConfigForSettings(); + // Custom Model Endpoint Profiles' own load is gated on the toggle above (see + // applyCustomModelEndpointsVisibility) — unlike model config, this GET is + // pointless work with the feature off, so it is not fired unconditionally. // Notification settings const notifPrefs = this.notificationManager?.preferences || {}; document.getElementById('appSettingsNotifEnabled').checked = notifPrefs.enabled ?? true; @@ -2106,6 +2116,7 @@ Object.assign(CodemanApp.prototype, { showSubagents: document.getElementById('appSettingsShowSubagents').checked, showUltracodeAgents: document.getElementById('appSettingsShowUltracodeAgents').checked, approvalsInboxEnabled: document.getElementById('appSettingsApprovalsInbox').checked, + customModelEndpointsEnabled: document.getElementById('appSettingsCustomModelEndpoints').checked, readMyMindEnabled: document.getElementById('appSettingsReadMyMind').checked, ultracodeFloatingWindows: document.getElementById('appSettingsUltracodeFloatingWindows').checked, showMultiMonitorButton: document.getElementById('appSettingsShowMultiMonitorButton').checked, @@ -2487,6 +2498,209 @@ Object.assign(CodemanApp.prototype, { } }, + // ═══════════════════════════════════════════════════════════════ + // Custom Model Endpoint Profiles (docs/custom-model-endpoints-plan.md) + // + // CRUD against /api/model-endpoints, rendered into the Models settings section. + // Deliberately its own load/save pair rather than folded into openAppSettings/ + // saveAppSettings: these are server-side infra records (like remote/docker + // hosts), not a settings-payload field, so the app-settings-structure guard's + // by-id contract does not apply to them — only the `customModelEndpointsEnabled` + // toggle itself goes through that path. + // ═══════════════════════════════════════════════════════════════ + + /** + * Toggles the endpoint-management body's visibility to match the setting and, + * turning it on, lazily loads the endpoint list. Assigning `.checked` (as the + * settings load path does) fires no `change` event, so this must be called + * explicitly on open as well as wired to the checkbox's own onchange — a + * gate that only worked one of those two ways would show a stale "off" + * body right after opening, or a stale "on" one right after saving it off. + * With the feature off the body is a list of controls that do nothing, so it + * is hidden entirely rather than shown disabled. + */ + applyCustomModelEndpointsVisibility() { + const enabled = document.getElementById('appSettingsCustomModelEndpoints').checked; + const body = document.getElementById('customModelEndpointsBody'); + if (body) body.style.display = enabled ? '' : 'none'; + if (enabled) this.loadCustomModelEndpointsForSettings(); + else this.closeCustomModelHostEditor(); + this._applyCustomModelAdminGate(); + }, + + /** + * Endpoint writes are admin-only in multi-user mode (custom-model-routes.ts), + * and GET already answers a non-admin with an empty list, which hides every + * per-row Edit/Discover/Delete button on its own. The "+ Add endpoint" button + * has no row to hide behind, so it needs its own gate — otherwise a non-admin + * can open the form, fill it in, and get a 403 toast on Save. Wired to the + * `codeman:me` event (admin-ui.js) as well as called from + * applyCustomModelEndpointsVisibility(), because `window.__codemanUser`'s + * real role can resolve AFTER settings have already been opened once. + */ + _applyCustomModelAdminGate() { + const addBtn = document.getElementById('customModelHostAddBtn'); + if (!addBtn) return; + const me = window.__codemanUser || {}; + const blocked = me.multiUser && me.role !== 'admin'; + addBtn.style.display = blocked ? 'none' : ''; + }, + + async loadCustomModelEndpointsForSettings() { + // GET /api/model-endpoints wraps its body in the { success, data } envelope + // like every other /api route (server.ts's preSerialization hook applies to + // arrays too) — _apiJson() unwraps it. A raw fetch().json() here would + // silently see the envelope object instead of the array and this panel + // would read as "No endpoints yet" forever, even with endpoints saved. + const hosts = await this._apiJson('/api/model-endpoints'); + this._customModelHosts = Array.isArray(hosts) ? hosts : []; + this.renderCustomModelHostsList(); + }, + + renderCustomModelHostsList() { + const list = document.getElementById('customModelHostsList'); + if (!list) return; + const hosts = this._customModelHosts || []; + if (hosts.length === 0) { + list.innerHTML = '

No endpoints yet. Add one below to point a harness at a local or cloud OpenAI-compatible server.

'; + return; + } + list.innerHTML = hosts + .map((h) => { + const modelCount = (h.models || []).length; + const modelSummary = modelCount === 0 + ? 'No models discovered yet' + : `${modelCount} model${modelCount === 1 ? '' : 's'}${h.defaultModelId ? ` · default: ${escapeHtml(h.defaultModelId)}` : ' · no default set'}`; + // escapeHtml(JSON.stringify(h.id)) — not JSON.stringify(h.id) alone — + // because JSON.stringify's own double quotes would otherwise terminate + // this double-quoted attribute at the first one, and everything after + // parses as raw tag content rather than the rest of the quoted string. + // Same idiom as deleteCase's onclick in session-ui.js. h.id is + // regex-constrained server-side (safe either way) but the pattern must + // match everywhere it is used, including where the argument is not. + const idArg = escapeHtml(JSON.stringify(h.id)); + return ` +
+
+ ${escapeHtml(h.label)} + ${escapeHtml(h.baseUrl)} — ${modelSummary} +
+
+ + + +
+
`; + }) + .join(''); + }, + + /** Opens the inline add/edit form. Pass no id to add a new endpoint. */ + openCustomModelHostEditor(hostId) { + const host = hostId ? (this._customModelHosts || []).find((h) => h.id === hostId) : null; + this._editingCustomModelHostId = host ? host.id : null; + document.getElementById('customModelHostEditorTitle').textContent = host ? `Edit ${host.label}` : 'Add endpoint'; + document.getElementById('customModelHostId').value = host?.id || ''; + document.getElementById('customModelHostId').disabled = !!host; // id is immutable once created + document.getElementById('customModelHostLabel').value = host?.label || ''; + document.getElementById('customModelHostBaseUrl').value = host?.baseUrl || ''; + document.getElementById('customModelHostApiKey').value = ''; // the server never returns the real value (apiKeySet is a bool) + document.getElementById('customModelHostApiKey').placeholder = host?.apiKeySet ? '•••••••• (unchanged if left blank)' : ''; + document.getElementById('customModelHostAuthStyle').value = host?.authStyle || 'bearer'; + this._populateCustomModelDefaultSelect(host); + document.getElementById('customModelHostEditor').style.display = ''; + }, + + closeCustomModelHostEditor() { + document.getElementById('customModelHostEditor').style.display = 'none'; + this._editingCustomModelHostId = null; + }, + + _populateCustomModelDefaultSelect(host) { + const select = document.getElementById('customModelHostDefaultModel'); + const models = host?.models || []; + select.innerHTML = + '' + + models.map((m) => ``).join(''); + select.value = host?.defaultModelId || ''; + select.disabled = models.length === 0; + }, + + async saveCustomModelHostFromEditor() { + const id = document.getElementById('customModelHostId').value.trim(); + const label = document.getElementById('customModelHostLabel').value.trim(); + const baseUrl = document.getElementById('customModelHostBaseUrl').value.trim(); + const apiKeyInput = document.getElementById('customModelHostApiKey').value; + const authStyle = document.getElementById('customModelHostAuthStyle').value; + const defaultModelId = document.getElementById('customModelHostDefaultModel').value || undefined; + if (!id || !label || !baseUrl) { + this.showToast('Id, label and base URL are all required', 'warning'); + return; + } + const editing = this._editingCustomModelHostId; + // PUT (server-side) treats an absent apiKey as "keep the stored one" — the + // browser never holds the real value to resend deliberately unchanged (see + // openCustomModelHostEditor and custom-model-routes.ts's applyStoredApiKey), + // so a blank field here means omitting the key entirely, not resending + // something we do not have. models/lastDiscoveredAt DO still need + // re-sending: PUT replaces the whole record, and this cached copy still + // carries both (only apiKey is redacted from what GET hands back). + const existing = editing ? (this._customModelHosts || []).find((h) => h.id === editing) : null; + const body = { + id, + label, + baseUrl, + authStyle, + defaultModelId, + apiKey: apiKeyInput || undefined, + models: existing?.models, + lastDiscoveredAt: existing?.lastDiscoveredAt, + }; + try { + const res = await fetch(editing ? `/api/model-endpoints/${encodeURIComponent(editing)}` : '/api/model-endpoints', { + method: editing ? 'PUT' : 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }); + const data = await res.json(); + if (!data.success) { + this.showToast(data.error || 'Failed to save endpoint', 'error'); + return; + } + this.showToast(editing ? 'Endpoint updated' : 'Endpoint added', 'success'); + this.closeCustomModelHostEditor(); + await this.loadCustomModelEndpointsForSettings(); + } catch (err) { + this.showToast(`Failed to save endpoint: ${err.message}`, 'error'); + } + }, + + async discoverCustomModelHostModels(hostId) { + this.showToast('Discovering models…', 'info'); + try { + const res = await fetch(`/api/model-endpoints/${encodeURIComponent(hostId)}/discover-models`, { method: 'POST' }); + const data = await res.json(); + if (!data.success) { + this.showToast(data.error || 'Discovery failed', 'error'); + return; + } + this.showToast(`Found ${data.data.models.length} model${data.data.models.length === 1 ? '' : 's'}`, 'success'); + await this.loadCustomModelEndpointsForSettings(); + } catch (err) { + this.showToast(`Discovery failed: ${err.message}`, 'error'); + } + }, + + async deleteCustomModelHost(hostId) { + const host = (this._customModelHosts || []).find((h) => h.id === hostId); + if (!confirm(`Delete endpoint "${host?.label || hostId}"? Any session currently pointed at it keeps running until cleared.`)) return; + try { + await fetch(`/api/model-endpoints/${encodeURIComponent(hostId)}`, { method: 'DELETE' }); + await this.loadCustomModelEndpointsForSettings(); + } catch (err) { + this.showToast(`Failed to delete endpoint: ${err.message}`, 'error'); + } + }, // ═══════════════════════════════════════════════════════════════ // Visibility Settings & Device-Specific Defaults @@ -3543,3 +3757,15 @@ Object.assign(CodemanApp.prototype, { this.subagentPanelVisible = false; }, }); + +// window.__codemanUser's real role can resolve after settings have already been +// opened once (admin-ui.js fetches /api/me asynchronously and dispatches this on +// arrival), so the Custom Model Endpoints admin gate needs to be re-applied when +// it does, not just when the modal opens. Optional chaining on addEventListener +// itself: several frontend tests (run-mode-ui.test.ts) load this file into a vm +// context with a minimal fake `document` that has no event-target methods at +// all, and a module-level statement that throws there fails the whole file's +// evaluation, not just this feature. +document.addEventListener?.('codeman:me', () => { + window.app?._applyCustomModelAdminGate?.(); +}); diff --git a/src/web/public/styles.css b/src/web/public/styles.css index 398eb6ce5..df9e79efc 100644 --- a/src/web/public/styles.css +++ b/src/web/public/styles.css @@ -6803,6 +6803,39 @@ body.touch-device .terminal-container .xterm .xterm-helper-textarea { min-height: 0; } +/* Custom Model Endpoint Profiles' "which model" picker: same bounded-height + + scrollable-body shape as .modal-lg above, scoped by id rather than added to + .modal-sm itself (three other modals share that class for short, fixed + content and do not need a height cap). Without this the modal had no + max-height at all, so an endpoint with many discovered models grew the + dialog past the viewport with nothing to scroll — "the whole page" and + "the list is truncated" turned out to be one and the same bug. `min(70vh, + 520px)` scales with the monitor (a phone gets 70% of its height, a 4K + display never gets a needlessly tall dialog) rather than a fixed value + that would be wrong at one end or the other. */ +#customModelPickModal .modal-content { + max-height: min(70vh, 520px); + display: flex; + flex-direction: column; +} + +#customModelPickModal .modal-body { + overflow-y: auto; + flex: 1; + min-height: 0; +} + +/* Custom Model Endpoint Profiles: llama-swap model-swap confirmation — replaces a native + confirm() popup (docs/custom-model-endpoints-plan.md) so it looks and feels like the + rest of the app instead of a browser chrome dialog. */ +#customModelSwapConfirmModal .modal-footer { + display: flex; + justify-content: flex-end; + gap: 0.5rem; + padding: 0.75rem 1rem; + border-top: 1px solid var(--border-color); +} + /* Mobile Case Picker - Base Styles */ .mobile-case-picker-sheet { @@ -8441,6 +8474,9 @@ kbd { } .toast { + display: flex; + align-items: center; + gap: 0.5rem; background: var(--bg-card); border: 1px solid var(--border); border-radius: 6px; @@ -8452,6 +8488,7 @@ kbd { opacity: 0; transition: all 0.2s ease; pointer-events: auto; + max-width: 420px; } .toast.show { @@ -8459,6 +8496,118 @@ kbd { opacity: 1; } +.toast-message { + flex: 1; + /* Errors are sticky by default (showToast) precisely so a longer, specific + message survives to be read — let it wrap instead of clipping. */ + white-space: pre-wrap; + word-break: break-word; +} + +/* Every toast gets one, sticky or not: a sticky toast with no way to close it + would just accumulate on screen across repeated failures. */ +.toast-close { + flex-shrink: 0; + background: none; + border: none; + color: inherit; + opacity: 0.6; + font-size: 1.1rem; + line-height: 1; + padding: 0 0.15rem; + cursor: pointer; +} + +.toast-close:hover { + opacity: 1; +} + +/* Custom Model Endpoint Profiles: the "switching backends" / "loading model" states + (docs/custom-model-endpoints-plan.md) — a small set of messages prominent and + screen-centred rather than corner toasts, since they can sit on screen for well + over a minute (a real llama-swap model load) and are easy to mistake for nothing + happening. Non-blocking: `pointer-events: none` on the wrapper (no backdrop, no + click-catcher) with `auto` restored only on the card itself, purely so the text + inside remains selectable — there is nothing to click to dismiss it early. */ +.center-status-banner { + position: fixed; + top: 50%; + left: 50%; + transform: translate(-50%, -50%) scale(0.96); + z-index: 10001; + display: flex; + align-items: center; + gap: 0.75rem; + background: var(--bg-card); + border: 1px solid var(--border); + border-radius: 10px; + padding: 1rem 1.5rem; + box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4); + font-size: 0.95rem; + font-weight: 500; + color: var(--text); + max-width: min(90vw, 460px); + text-align: left; + opacity: 0; + pointer-events: none; + transition: + opacity 0.2s ease, + transform 0.2s ease; +} + +.center-status-banner.show { + opacity: 1; + transform: translate(-50%, -50%) scale(1); +} + +.center-status-spinner { + flex-shrink: 0; + width: 18px; + height: 18px; + border-radius: 50%; + border: 2px solid var(--border); + border-top-color: var(--accent, var(--text)); + animation: center-status-spin 0.8s linear infinite; +} + +@keyframes center-status-spin { + to { + transform: rotate(360deg); + } +} + +.center-status-text { + flex: 1; + pointer-events: auto; + white-space: pre-wrap; + word-break: break-word; +} + +/* Error variant: the load didn't finish in time — nothing is "in progress" anymore (no + spinner), and since this one doesn't dismiss itself, it needs a close button the user + can actually click, so pointer-events is restored here too (see the wrapper's own + comment on why that's `none` by default). */ +.center-status-error { + border-color: rgba(239, 68, 68, 0.5); +} + +.center-status-close { + flex-shrink: 0; + pointer-events: auto; + background: none; + border: none; + color: inherit; + opacity: 0.6; + font-size: 1.2rem; + line-height: 1; + padding: 0 0.15rem; + cursor: pointer; +} + +.center-status-close:hover { + opacity: 1; +} + .toast-success { border-color: rgba(34, 197, 94, 0.4); } .toast-error { border-color: rgba(239, 68, 68, 0.4); } .toast-warning { border-color: rgba(234, 179, 8, 0.4); } @@ -15134,6 +15283,12 @@ html[data-skin="daylight-blue"] .welcome-btn-tunnel.active:hover { .run-mode-dot.web { background: #38bdf8; } .run-mode-webviews { max-height: 180px; overflow-y: auto; } +/* Custom Model Endpoint Profiles' generated entries: `.run-mode-menu.active`'s + own `gap: 2px` only spaces its DIRECT children, and this container (like + `.run-mode-webviews` above) is one such child holding several buttons of + its own, so it needs the same gap repeated one level down or its rows sit + flush against each other. */ +.run-mode-custom-models { display: flex; flex-direction: column; gap: 2px; } /* A saved URL is a ROW: open on the left, edit + delete on the right, so a URL can be changed or removed without first opening it as a tab. The side buttons stay @@ -16207,6 +16362,29 @@ html[data-tab-orientation='vertical'] .home-sessions { gap: 3px; } +/* Custom Model Endpoint Profiles' inline add/edit form: a nested panel rather + than a modal, so it needs its own border to read as a distinct sub-section + inside .set-group-body's flat row stack. `--control-bg` rather than a + hardcoded black alpha — CLAUDE.md records that literal fill turning the + settings live preview into a grey slab on the light skins, and this panel + sits in the very same modal. */ +:is(#appSettingsModal, #sessionOptionsModal, #createCaseModal) .set-inline-form { + display: flex; + flex-direction: column; + gap: 3px; + margin-top: 6px; + padding: 10px 12px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--control-bg); +} + +:is(#appSettingsModal, #sessionOptionsModal, #createCaseModal) .set-inline-form h5 { + margin: 0 0 4px; + font-size: 0.72rem; + color: var(--text-muted); +} + /* ── rows ─────────────────────────────────────────────────────────────── */ :is(#appSettingsModal, #sessionOptionsModal, #createCaseModal) .set-row { display: flex; diff --git a/src/web/routes/custom-model-routes.ts b/src/web/routes/custom-model-routes.ts index d5b1b1e82..252a4f12e 100644 --- a/src/web/routes/custom-model-routes.ts +++ b/src/web/routes/custom-model-routes.ts @@ -26,6 +26,7 @@ import { readCustomModelHosts, writeCustomModelHosts, type CustomModelHost } fro const CODEMAN_CONFIG_DIR = getDataDir(); const DISCOVER_TIMEOUT_MS = 8000; +const PROPS_TIMEOUT_MS = 5000; function adminOnly(req: FastifyRequest, reply: { code: (n: number) => unknown }): ApiResponse | null { if (!isMultiUserMode() || isAdmin(req)) return null; @@ -33,7 +34,46 @@ function adminOnly(req: FastifyRequest, reply: { code: (n: number) => unknown }) return createErrorResponse(ApiErrorCode.FORBIDDEN, 'Admin only in multi-user mode'); } -async function discoverModels(host: Pick): Promise { +/** + * `defaultModelId` names the model the Run-menu picker applies for this endpoint with + * no further choice, so it must actually be one of the discovered `models` — a schema + * `.refine()` can't see across the two fields the way this can, and would also run on + * every unrelated field edit rather than only when either of these two changes. + */ +function invalidDefaultModel(host: Pick): ApiResponse | null { + if (host.defaultModelId === undefined) return null; + if ((host.models ?? []).includes(host.defaultModelId)) return null; + return createErrorResponse( + ApiErrorCode.INVALID_INPUT, + 'defaultModelId must be one of the endpoint’s discovered models' + ); +} + +/** + * Never hand the stored credential back to the browser, on GET, POST or PUT + * alike — the file is written 0600 precisely because it holds one. `apiKeySet` + * is what lets the editor say "unchanged if left blank" without the client + * ever holding the real value: `applyStoredApiKey()` below is the other half, + * treating an absent key on PUT as "keep the stored one" rather than clearing + * it, which is what makes never returning it survivable for the edit flow. + */ +function redactApiKey(host: CustomModelHost): Omit & { apiKeySet: boolean } { + const { apiKey, ...rest } = host; + return { ...rest, apiKeySet: !!apiKey }; +} + +/** + * A PUT body with no `apiKey` (or a blank one) means "leave it alone", never + * "clear it": the editor never receives the real value to resend deliberately + * unchanged (see redactApiKey), so the only way it can tell the two apart is + * by omission. There is deliberately no way to CLEAR a key back to unset this + * way — a pre-existing limitation, not something this changes. + */ +function applyStoredApiKey(incoming: CustomModelHost, existing: CustomModelHost): CustomModelHost { + return incoming.apiKey ? incoming : { ...incoming, apiKey: existing.apiKey }; +} + +function authHeaders(host: Pick): Record { const headers: Record = {}; const apiKey = host.apiKey?.trim(); // Exactly ONE header, never both — see custom-model-hosts.ts's CustomModelAuthStyle @@ -41,14 +81,137 @@ async function discoverModels(host: Pick; + /** See `CustomModelHost.modelSizesGB` — populated for every model whose own listing states one. */ + sizesGB: Record; +} + +/** + * Best-effort: pulls a file size in GB out of a model's own `description`, when the + * server states one. llama-swap writes `"Auto-discovered 16.35 GB - parameters + * auto-fitted by llama.cpp"` for a model it found on disk itself; a hand-configured + * profile's own description (e.g. `"General-purpose reasoning model, MoE CPU-offloaded."`) + * has no such figure and correctly yields no estimate rather than a guess — there is no + * separate "give me the file size" endpoint to fall back on. + */ +function parseSizeGB(description: unknown): number | undefined { + if (typeof description !== 'string') return undefined; + const match = /(\d+(?:\.\d+)?)\s*GB\b/i.exec(description); + if (!match) return undefined; + const size = Number(match[1]); + return Number.isFinite(size) && size > 0 ? size : undefined; +} + +/** + * Best-effort: fetches `GET /props?model=` (llama.cpp-native, llama-swap-proxied) for + * ONE already-loaded model and pulls its real `n_ctx` out. Never called for a model that + * isn't already loaded — see the caller and `CustomModelHost.modelContextLengths` for why + * that's a hard safety requirement, not just a nicety: llama-swap treats this endpoint's + * `?model=` as a routing hint, and asking it about an unloaded model risks triggering an + * actual (slow, GPU-swapping) load as a side effect of what should be read-only discovery. + * Any failure (unreachable, non-2xx, missing/malformed field) is swallowed — one model's + * context length is a nice-to-have, never worth failing the whole discovery pass over. + * + * ⚠️ FALLBACK ONLY — confirmed live to be actively WRONG for a `--fit-ctx`-launched llama- + * swap backend: `/props`'s `n_ctx` read 154112 for a model llama-swap itself had launched + * with `--fit-ctx 16384` (visible in `/running`'s own `cmd`), and the real server then + * refused a request at the real 16384-token limit — `n_ctx` here appears to report the + * model's theoretical/trained maximum, not the runtime-configured one. `parseCtxFromCmd` + * (below), which reads the actual launch flag `/running` reports, is the primary source; + * this is only used when that parse comes up empty (no recognized flag in `cmd`, or `cmd` + * itself unavailable). + */ +async function fetchContextLength( + host: Pick, + modelId: string, + headers: Record +): Promise { + try { + const url = new URL(`${host.baseUrl.replace(/\/+$/, '')}/props`); + url.searchParams.set('model', modelId); + const res = await webviewFetch(url, { headers, signal: AbortSignal.timeout(PROPS_TIMEOUT_MS) }); + if (!res.ok) return undefined; + const body = (await res.json()) as { n_ctx?: unknown; default_generation_settings?: { n_ctx?: unknown } }; + const nCtx = body.n_ctx ?? body.default_generation_settings?.n_ctx; + return typeof nCtx === 'number' && Number.isFinite(nCtx) && nCtx > 0 ? nCtx : undefined; + } catch { + return undefined; + } +} + +/** + * Parses the REAL configured context size out of llama-swap's own launch command for a + * model (`/running`'s `cmd` field, e.g. `"llama-server -m ... --fit-ctx 16384 ..."`) — + * the primary source for `modelContextLengths`, preferred over `/props`'s `n_ctx` (see + * `fetchContextLength`'s own doc comment for why that field is unreliable here). Checks + * `--fit-ctx` first (llama-swap's own auto-fit flag), then the plain llama.cpp + * `-c`/`--ctx-size`/`--ctx_size` flags a hand-written launch command might use instead. + * Returns `undefined` when `cmd` has none of these — not every launch command needs to + * state one explicitly (llama.cpp has its own default), and guessing one would be worse + * than the "no override applied" the caller already treats an unknown length as. + */ +function parseCtxFromCmd(cmd: unknown): number | undefined { + if (typeof cmd !== 'string') return undefined; + const match = /--fit-ctx\s+(\d+)/.exec(cmd) ?? /(?:^|\s)(?:-c|--ctx-size|--ctx_size)\s+(\d+)/.exec(cmd); + if (!match) return undefined; + const value = Number(match[1]); + return Number.isFinite(value) && value > 0 ? value : undefined; +} + +async function discoverModels( + host: Pick +): Promise { + const headers = authHeaders(host); const res = await webviewFetch(new URL(`${host.baseUrl.replace(/\/+$/, '')}/v1/models`), { headers, signal: AbortSignal.timeout(DISCOVER_TIMEOUT_MS), }); if (!res.ok) throw new Error(`HTTP ${res.status}`); - const body = (await res.json()) as { data?: Array<{ id?: unknown }> }; - return (body.data ?? []).map((m) => m.id).filter((id): id is string => typeof id === 'string' && id.length > 0); + const body = (await res.json()) as { + data?: Array<{ id?: unknown; status?: { value?: unknown }; description?: unknown }>; + }; + const entries = body.data ?? []; + const models = entries.map((m) => m.id).filter((id): id is string => typeof id === 'string' && id.length > 0); + + const sizesGB: Record = {}; + for (const entry of entries) { + if (typeof entry.id !== 'string' || !entry.id) continue; + const size = parseSizeGB(entry.description); + if (size !== undefined) sizesGB[entry.id] = size; + } + + // llama-swap-specific, feature-detected: a server that never mentions `status` on ANY + // entry gets no context-length enrichment at all, rather than treating "no status field" + // as "assume unloaded" — either reading is a guess, and skipping is the safe one, since + // fetchContextLength must only ever run against a model this server itself calls loaded. + const hasStatusField = entries.some((m) => m && typeof m === 'object' && 'status' in m); + const contextLengths: Record = {}; + if (hasStatusField) { + const loadedIds = entries + .filter((m) => m.status && typeof m.status === 'object' && (m.status as { value?: unknown }).value === 'loaded') + .map((m) => m.id) + .filter((id): id is string => typeof id === 'string' && id.length > 0); + if (loadedIds.length > 0) { + // Primary source: the REAL launch command (see parseCtxFromCmd's own doc comment + // for why /props's n_ctx cannot be trusted here). One /running call covers every + // loaded model, so this never costs more requests than the old /props-only path did + // when the cmd parse succeeds, and exactly one extra when it has to fall back. + const swapStatus = await getLlamaSwapStatus(host); + const cmdById = new Map(swapStatus.running.map((r) => [r.model, r.cmd])); + for (const id of loadedIds) { + const fromCmd = parseCtxFromCmd(cmdById.get(id)); + const ctx = fromCmd ?? (await fetchContextLength(host, id, headers)); + if (ctx !== undefined) contextLengths[id] = ctx; + } + } + } + return { models, contextLengths, sizesGB }; } /** @@ -66,41 +229,212 @@ function describeFetchError(err: unknown): string { return message; } +type RedactedHost = ReturnType; + +/** + * Merges a fresh `GET /v1/models` result into a host record: stamps + * `lastDiscoveredAt`, and drops `defaultModelId` if it no longer appears in + * the fresh list (it would otherwise leave the Run-menu picker applying a + * model id the endpoint just told us it doesn't serve). Pure — no IO, so the + * manual route (which reports a fetch failure's *reason* to the caller) and + * the periodic sweep below (which only cares whether it can move on) can + * each do their own `discoverModels()` + error handling around one shared + * "how to apply a successful result" step. + */ +const RUNNING_TIMEOUT_MS = 5000; + +export interface LlamaSwapRunningModel { + model: string; + state: string; + /** The actual launch command llama-swap started this backend with, when it says one — + * see `parseCtxFromCmd`, which reads the real configured context size out of this. */ + cmd?: string; +} + +export interface LlamaSwapStatus { + /** + * Feature-detected via `GET /running`: true only when the server answered with + * llama-swap's own shape (`{ running: [...] }`). Plain llama.cpp (and any other + * OpenAI-compatible server) has no such endpoint and always runs the single model + * it was started with, so there is no "current model" to conflict with — every + * caller must treat `isLlamaSwap: false` as "nothing to check", never as an error. + */ + isLlamaSwap: boolean; + running: LlamaSwapRunningModel[]; +} + +/** + * Distinguishes llama-swap from a plain llama.cpp/OpenAI-compatible server, and reports + * what llama-swap currently has loaded — llama.cpp only ever runs one GGUF at a time, and + * llama-swap unloads/reloads it on demand when a request asks for a different one, which + * can take anywhere from a few seconds to over a minute. Read-only: this never triggers a + * swap itself (unlike `/props?model=`, `/running` takes no `model` parameter to route by). + * Best-effort like `discoverModels()`'s siblings: any failure (unreachable, non-2xx, + * unexpected shape) reads as "not llama-swap", never thrown. + */ +export async function getLlamaSwapStatus( + host: Pick +): Promise { + try { + const res = await webviewFetch(new URL(`${host.baseUrl.replace(/\/+$/, '')}/running`), { + headers: authHeaders(host), + signal: AbortSignal.timeout(RUNNING_TIMEOUT_MS), + }); + if (!res.ok) return { isLlamaSwap: false, running: [] }; + const body = (await res.json()) as { running?: unknown }; + if (!Array.isArray(body.running)) return { isLlamaSwap: false, running: [] }; + const running = body.running + .filter( + (r): r is { model: string; state?: unknown; cmd?: unknown } => + !!r && typeof r === 'object' && typeof (r as { model?: unknown }).model === 'string' + ) + .map((r) => ({ + model: r.model, + state: typeof r.state === 'string' ? r.state : 'unknown', + cmd: typeof r.cmd === 'string' ? r.cmd : undefined, + })); + return { isLlamaSwap: true, running }; + } catch { + return { isLlamaSwap: false, running: [] }; + } +} + +/** + * Actually kicks off llama-swap's lazy model load, rather than waiting for the launched + * CLI's own first prompt to do it. llama-swap has no separate "switch model" admin + * endpoint — the ONLY thing that starts a swap is a real inference request naming the + * model (confirmed live: applying a selection alone never appeared in the llama-swap + * server's own logs; nothing had actually asked it to load anything). This sends the + * smallest real request that will — `max_tokens: 1`, one throwaway user message — to + * `${baseUrl}/v1/chat/completions`, the OpenAI-compatible endpoint every supported + * harness already points at. + * + * Deliberately fire-and-forget: the caller (the apply/create routes) returns to the + * client immediately, and the frontend's own polling (`GET .../running-status`) is what + * actually confirms readiness — this call's response is never read, just its side + * effect. No abort/timeout of its own either: a real load can take well over a minute for + * a large model, and this is a normal long-running Node process, so there is nothing to + * clean up by cutting it short. Errors are swallowed for the same reason `discoverModels`'s + * siblings swallow theirs — one endpoint's hiccup here is a nice-to-have that failed, not + * something worth surfacing as a request failure four layers up. + */ +export function triggerLlamaSwapLoad( + host: Pick, + modelId: string +): void { + const url = new URL(`${host.baseUrl.replace(/\/+$/, '')}/v1/chat/completions`); + webviewFetch(url, { + method: 'POST', + headers: { ...authHeaders(host), 'content-type': 'application/json' }, + body: JSON.stringify({ + model: modelId, + messages: [{ role: 'user', content: 'Hi' }], + max_tokens: 1, + stream: false, + }), + }).catch(() => { + // best-effort — see the doc comment above + }); +} + +function applyDiscoveredModels(host: CustomModelHost, result: DiscoveryResult): CustomModelHost { + const { models, contextLengths, sizesGB } = result; + const defaultModelId = host.defaultModelId && models.includes(host.defaultModelId) ? host.defaultModelId : undefined; + // Merge onto what's already known rather than replacing: a model not probed this round + // (not currently loaded) keeps whatever context length an earlier round already learned + // for it, and one no longer in the fresh list is dropped, same reasoning as defaultModelId. + const merged = { ...host.modelContextLengths, ...contextLengths }; + const kept = Object.fromEntries(Object.entries(merged).filter(([id]) => models.includes(id))); + const modelContextLengths = Object.keys(kept).length > 0 ? kept : undefined; + // sizesGB, unlike contextLengths, is populated for every model in the SAME pass (no + // loaded-only restriction — see parseSizeGB), so this is closer to a plain replace, but + // still merges onto the previous round rather than dropping a size for a model whose + // description happened to omit the figure on this particular pass. + const mergedSizes = { ...host.modelSizesGB, ...sizesGB }; + const keptSizes = Object.fromEntries(Object.entries(mergedSizes).filter(([id]) => models.includes(id))); + const modelSizesGB = Object.keys(keptSizes).length > 0 ? keptSizes : undefined; + return { + ...host, + models, + defaultModelId, + modelContextLengths, + modelSizesGB, + lastDiscoveredAt: new Date().toISOString(), + }; +} + +/** + * Re-discovers every saved endpoint's models, best-effort. One endpoint being + * unreachable (powered off, wrong network) must not stop the others from + * refreshing, and a read-modify-write per host (rather than one batch write + * at the end) means a crash or restart mid-sweep loses at most the endpoints + * not yet reached, never a write already applied. Exported so both the + * periodic timer (server.ts) and a test can drive it directly. + */ +export async function refreshAllCustomModelHosts(): Promise { + const dataDir = getDataDir(); + const hosts = await readCustomModelHosts(dataDir); + for (const host of hosts) { + if (isBlockedWebviewUrl(host.baseUrl)) continue; + let result: DiscoveryResult; + try { + result = await discoverModels(host); + } catch { + continue; // unreachable this cycle — try again next tick, not fatal to the sweep + } + // Re-read + splice by id rather than reusing the array captured above: an + // admin editing or deleting an endpoint via the API mid-sweep must win, + // not be silently overwritten by a refresh that started before their change. + const current = await readCustomModelHosts(dataDir); + const index = current.findIndex((item) => item.id === host.id); + if (index === -1) continue; // deleted mid-sweep + current[index] = applyDiscoveredModels(current[index], result); + await writeCustomModelHosts(dataDir, current); + } +} + export function registerCustomModelRoutes(app: FastifyInstance): void { - app.get('/api/model-endpoints', async (req) => - isMultiUserMode() && !isAdmin(req) ? [] : readCustomModelHosts(CODEMAN_CONFIG_DIR) - ); + app.get('/api/model-endpoints', async (req): Promise => { + if (isMultiUserMode() && !isAdmin(req)) return []; + const hosts = await readCustomModelHosts(CODEMAN_CONFIG_DIR); + return hosts.map(redactApiKey); + }); - app.post('/api/model-endpoints', async (req, reply): Promise> => { + app.post('/api/model-endpoints', async (req, reply): Promise> => { const denied = adminOnly(req, reply); if (denied) return denied; const host = parseBody(CustomModelHostSchema, req.body); if (isBlockedWebviewUrl(host.baseUrl)) { return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Endpoint base URL is not allowed'); } + const badDefault = invalidDefaultModel(host); + if (badDefault) return badDefault; const hosts = await readCustomModelHosts(CODEMAN_CONFIG_DIR); if (hosts.some((item) => item.id === host.id)) { return createErrorResponse(ApiErrorCode.ALREADY_EXISTS, 'Model endpoint already exists'); } await writeCustomModelHosts(CODEMAN_CONFIG_DIR, [...hosts, host]); - return { success: true, data: { host } }; + return { success: true, data: { host: redactApiKey(host) } }; }); - app.put('/api/model-endpoints/:id', async (req, reply): Promise> => { + app.put('/api/model-endpoints/:id', async (req, reply): Promise> => { const denied = adminOnly(req, reply); if (denied) return denied; const { id } = req.params as { id: string }; - const host = parseBody(CustomModelHostSchema, { ...(req.body as object), id }); - if (isBlockedWebviewUrl(host.baseUrl)) { + const incoming = parseBody(CustomModelHostSchema, { ...(req.body as object), id }); + if (isBlockedWebviewUrl(incoming.baseUrl)) { return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Endpoint base URL is not allowed'); } + const badDefault = invalidDefaultModel(incoming); + if (badDefault) return badDefault; const hosts = await readCustomModelHosts(CODEMAN_CONFIG_DIR); const index = hosts.findIndex((item) => item.id === id); if (index === -1) return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Model endpoint not found'); + const host = applyStoredApiKey(incoming, hosts[index]); const next = [...hosts]; next[index] = host; await writeCustomModelHosts(CODEMAN_CONFIG_DIR, next); - return { success: true, data: { host } }; + return { success: true, data: { host: redactApiKey(host) } }; }); app.delete('/api/model-endpoints/:id', async (req, reply): Promise> => { @@ -129,11 +463,11 @@ export function registerCustomModelRoutes(app: FastifyInstance): void { return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Endpoint base URL is not allowed'); } try { - const models = await discoverModels(host); + const result = await discoverModels(host); const next = [...hosts]; - next[index] = { ...host, models, lastDiscoveredAt: new Date().toISOString() }; + next[index] = applyDiscoveredModels(host, result); await writeCustomModelHosts(CODEMAN_CONFIG_DIR, next); - return { success: true, data: { models } }; + return { success: true, data: { models: result.models } }; } catch (err) { const blocked = egressBlockedReason(err); return createErrorResponse( @@ -143,4 +477,18 @@ export function registerCustomModelRoutes(app: FastifyInstance): void { } } ); + + // Read-only, no admin gate: any session owner who can already point their own session + // at this endpoint (POST .../custom-model, ungated by design — see session-routes.ts) + // can equally ask what it currently has loaded, before or while that apply is pending. + app.get('/api/model-endpoints/:id/running-status', async (req): Promise> => { + const { id } = req.params as { id: string }; + const hosts = await readCustomModelHosts(CODEMAN_CONFIG_DIR); + const host = hosts.find((item) => item.id === id); + if (!host) return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Model endpoint not found'); + if (isBlockedWebviewUrl(host.baseUrl)) { + return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Endpoint base URL is not allowed'); + } + return { success: true, data: await getLlamaSwapStatus(host) }; + }); } diff --git a/src/web/routes/index.ts b/src/web/routes/index.ts index c1f0a952e..df615f307 100644 --- a/src/web/routes/index.ts +++ b/src/web/routes/index.ts @@ -27,4 +27,4 @@ export { registerWsRoutes } from './ws-routes.js'; export { registerVoiceRoutes } from './voice-routes.js'; export { registerWebviewRoutes, tryWebviewRefererFallback } from './webview-routes.js'; export { registerTabLayoutRoutes } from './tab-layout-routes.js'; -export { registerCustomModelRoutes } from './custom-model-routes.js'; +export { registerCustomModelRoutes, refreshAllCustomModelHosts } from './custom-model-routes.js'; diff --git a/src/web/routes/session-routes.ts b/src/web/routes/session-routes.ts index 03f92e5d0..d33ca9b5c 100644 --- a/src/web/routes/session-routes.ts +++ b/src/web/routes/session-routes.ts @@ -11,7 +11,7 @@ import { homedir } from 'node:os'; import { existsSync, statSync, mkdirSync, writeFileSync } from 'node:fs'; import { execFile } from 'node:child_process'; import fs from 'node:fs/promises'; -import { randomBytes } from 'node:crypto'; +import { randomBytes, randomUUID } from 'node:crypto'; import { performance } from 'node:perf_hooks'; import { ApiErrorCode, @@ -55,6 +55,7 @@ import { } from '../schemas.js'; import { readCustomModelHosts } from '../../custom-model-hosts.js'; import { applyCustomModelInjection, removeConfigDir } from '../../custom-model-injection-apply.js'; +import { getLlamaSwapStatus, triggerLlamaSwapLoad } from './custom-model-routes.js'; import { matchesPattern } from '../../config/cli-registry/patterns.js'; import { ownerLayoutKey } from '../../tab-layout-persistence.js'; import { TabLayoutValidationError } from '../../tab-layout.js'; @@ -1209,12 +1210,48 @@ export function registerSessionRoutes( return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Model endpoint not found'); } + // llama.cpp runs exactly one model at a time; llama-swap unloads and reloads it on + // demand, which can take anywhere from a few seconds to over a minute — long enough + // that a session mid-swap looks indistinguishable from one that never left the native + // backend. Feature-detected via llama-swap's own `GET /running` (a plain llama.cpp + // server has no such endpoint and reads as `isLlamaSwap: false` — nothing to check). + const swapStatus = await getLlamaSwapStatus(endpoint); + const currentlyLoaded = swapStatus.running.find((r) => r.state === 'ready')?.model ?? swapStatus.running[0]?.model; + // Distinct from targetReady below: this is ONLY about whether proceeding would evict a + // model another session is actively using — true even if nothing is loaded at all yet + // would be wrong here (nothing to evict), so this stays narrowly "a DIFFERENT model is + // currently ready". + const swapNeeded = swapStatus.isLlamaSwap && !!currentlyLoaded && currentlyLoaded !== body.modelId; + // Whether the TARGET model itself is already the one loaded and ready — false whether + // nothing is loaded yet, a different model is loaded, or this one is loaded but still + // mid-load. Drives both the actual load trigger below and modelSwapInProgress in the + // response; deliberately broader than swapNeeded, which only gates the confirmation ask. + const targetReady = swapStatus.running.some((r) => r.model === body.modelId && r.state === 'ready'); + + // Only ask when switching would actually take the model away from another session + // that is currently using it — never just because a swap is needed at all. `confirmed` + // (set by the caller after showing that warning once) skips asking again. + if (swapNeeded && !body.confirmed) { + const affectedSessions = [...ctx.sessions.values()] + .filter( + (s) => + s.id !== session.id && + s.customModel?.endpointId === endpoint.id && + s.customModel?.modelId === currentlyLoaded + ) + .map((s) => ({ id: s.id, name: s.name })); + if (affectedSessions.length > 0) { + return { requiresConfirmation: true, currentlyLoadedModel: currentlyLoaded, affectedSessions }; + } + } + // A CLI whose config alone cannot select the model also gets its `model` launch param // forced (pi/omp `custom/`, grok's block name). The argv engine DROPS a token that // fails its pattern rather than quoting it, which would silently launch the CLI on its // own default provider again, so refuse an id the pattern cannot carry up front. const modelSpec = entry.launch.params.model; - const applied = applyCustomModelInjection(entry, endpoint, body.modelId, session.id); + const contextLength = endpoint.modelContextLengths?.[body.modelId]; + const applied = applyCustomModelInjection(entry, endpoint, body.modelId, session.id, contextLength); if (!applied) { return createErrorResponse(ApiErrorCode.OPERATION_FAILED, `${session.mode} has no known custom-model mechanism`); } @@ -1247,9 +1284,17 @@ export function registerSessionRoutes( removeConfigDir(previousConfigDir); } + // Actually kick off llama-swap's load now, rather than waiting on the restarted CLI's + // own first prompt to do it — confirmed live that applying a selection alone never + // reached the llama-swap server at all (nothing in its own logs), since llama-swap has + // no "switch model" admin call, only a real inference request naming the model. + if (swapStatus.isLlamaSwap && !targetReady) { + triggerLlamaSwapLoad(endpoint, body.modelId); + } + const restarted = await session.restartCli(); persistAndBroadcastSession(ctx, session); - return { customModel: session.customModel, restarted }; + return { customModel: session.customModel, restarted, modelSwapInProgress: swapStatus.isLlamaSwap && !targetReady }; }); // ========== Delete Session ========== @@ -3108,6 +3153,7 @@ export function registerSessionRoutes( effort, parentSessionId, agentOrigin, + customModel, } = parseBody(QuickStartSchema, req.body); // Resolved ONCE here: the same value labels a case directory this request creates @@ -3160,11 +3206,12 @@ export function registerSessionRoutes( grokConfig || deepSeekConfig || ompConfig || - openCodeConfig + openCodeConfig || + customModel ) { return createErrorResponse( ApiErrorCode.INVALID_INPUT, - 'envOverrides, effort, modelOverride, and per-CLI config are not supported for remote cases (they do not cross ssh). Configure the remote command via the host command override instead.' + 'envOverrides, effort, modelOverride, per-CLI config, and custom model endpoints are not supported for remote cases (they do not cross ssh). Configure the remote command via the host command override instead.' ); } @@ -3195,11 +3242,12 @@ export function registerSessionRoutes( grokConfig || deepSeekConfig || ompConfig || - openCodeConfig + openCodeConfig || + customModel ) { return createErrorResponse( ApiErrorCode.INVALID_INPUT, - 'envOverrides, effort, and per-CLI config are not supported for docker cases (they do not cross into the container). Configure the container via the docker host command override instead.' + 'envOverrides, effort, per-CLI config, and custom model endpoints are not supported for docker cases (they do not cross into the container). Configure the container via the docker host command override instead.' ); } @@ -3487,7 +3535,120 @@ export function registerSessionRoutes( ); const qsTerminalHistoryConfig = await ctx.getTerminalHistoryConfig(); const qsGatedEnvOverrides = await clampEnvOverridesForOwner(owner, envOverrides); + const qsResolvedOmpConfig = resolveOmpConfigForCreate(mode, resolvedCasePath, ompConfig); + + // Custom Model Endpoint Profiles, applied AT CREATE TIME (docs/custom-model-endpoints-plan.md) + // rather than via the dedicated restart-in-place route (POST /api/sessions/:id/custom- + // model, still what an ALREADY-RUNNING session uses to switch later): computing the + // injection before the process exists and launching directly on it avoids the visible + // native-boot-then-restart the restart-after-launch design otherwise shows on every + // custom-model run — most jarring on a CLI like Codex whose TUI fully reinitializes. + // Mirrors the dedicated route's own checks (llama-swap conflict, unsupported CLI, + // unknown endpoint, a model id the CLI's argv pattern can't carry) rather than trusting + // a lighter version of them, since this is the same server-side authority reached a + // different way, not a separate, less-checked path. + let qsCustomModelEnvOverrides = qsGatedEnvOverrides; + let qsCustomModelLaunchModel: string | undefined; + let qsCustomModelSessionId: string | undefined; + let qsCustomModelSwapInProgress = false; + let qsCustomModelBookkeeping: + | { + endpointId: string; + modelId: string; + label?: string; + envKeys: string[]; + configDir?: string; + launchModel?: string; + } + | undefined; + if (customModel) { + const cmEntry = getCli(mode); + if (!cmEntry) return createErrorResponse(ApiErrorCode.INVALID_INPUT, `No CLI registry entry for mode ${mode}`); + if (cmEntry.capabilities.customModelInjection.kind === 'unsupported') { + return createErrorResponse(ApiErrorCode.OPERATION_FAILED, `${mode} has no known custom-model mechanism`); + } + const cmHosts = await readCustomModelHosts(CODEMAN_CONFIG_DIR); + const cmEndpoint = cmHosts.find((h) => h.id === customModel.endpointId); + if (!cmEndpoint) return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Model endpoint not found'); + + // See the dedicated route's own comment for the full reasoning: llama.cpp runs one + // model at a time, llama-swap swaps on demand, and switching away from what another + // live session is actively using deserves a warning, not a silent switch. There is no + // "self" to exclude from the affected-sessions scan here — this session doesn't exist + // yet. + const cmSwapStatus = await getLlamaSwapStatus(cmEndpoint); + const cmCurrentlyLoaded = + cmSwapStatus.running.find((r) => r.state === 'ready')?.model ?? cmSwapStatus.running[0]?.model; + const cmSwapNeeded = cmSwapStatus.isLlamaSwap && !!cmCurrentlyLoaded && cmCurrentlyLoaded !== customModel.modelId; + // Broader than cmSwapNeeded (which only gates the confirmation ask above): true + // whenever the TARGET model isn't already loaded and ready, including when nothing + // is loaded at all yet. Drives the actual load trigger below. + const cmTargetReady = cmSwapStatus.running.some((r) => r.model === customModel.modelId && r.state === 'ready'); + qsCustomModelSwapInProgress = cmSwapStatus.isLlamaSwap && !cmTargetReady; + if (cmSwapNeeded && !customModel.confirmed) { + const cmAffectedSessions = [...ctx.sessions.values()] + .filter((s) => s.customModel?.endpointId === cmEndpoint.id && s.customModel?.modelId === cmCurrentlyLoaded) + .map((s) => ({ id: s.id, name: s.name })); + if (cmAffectedSessions.length > 0) { + return { + requiresConfirmation: true, + currentlyLoadedModel: cmCurrentlyLoaded, + affectedSessions: cmAffectedSessions, + }; + } + } + + // Minted ourselves (rather than left to Session's own default) so the injection + // below — and any configDir it writes — can target the REAL id the session launches + // with, not a placeholder: `new Session({ id: ... })` accepts an explicit id for + // exactly this reason. + qsCustomModelSessionId = randomUUID(); + const cmContextLength = cmEndpoint.modelContextLengths?.[customModel.modelId]; + const cmApplied = applyCustomModelInjection( + cmEntry, + cmEndpoint, + customModel.modelId, + qsCustomModelSessionId, + cmContextLength + ); + if (!cmApplied) { + return createErrorResponse(ApiErrorCode.OPERATION_FAILED, `${mode} has no known custom-model mechanism`); + } + const cmModelSpec = cmEntry.launch.params.model; + if ( + cmApplied.launchModel !== undefined && + cmModelSpec?.type === 'token' && + !matchesPattern(cmModelSpec.pattern, cmApplied.launchModel) + ) { + removeConfigDir(cmApplied.configDir); + return createErrorResponse( + ApiErrorCode.INVALID_INPUT, + `Model id ${JSON.stringify(customModel.modelId)} cannot be passed to ${mode} on its command line` + ); + } + + qsCustomModelEnvOverrides = { ...qsGatedEnvOverrides, ...cmApplied.envOverrides }; + qsCustomModelLaunchModel = cmApplied.launchModel; + qsCustomModelBookkeeping = { + endpointId: cmEndpoint.id, + modelId: customModel.modelId, + label: cmEndpoint.label, + envKeys: cmApplied.envKeys, + configDir: cmApplied.configDir, + launchModel: cmApplied.launchModel, + }; + + // Actually kick off llama-swap's load now — see the dedicated apply route's own + // comment on triggerLlamaSwapLoad for why this can't just wait on the launched CLI's + // first prompt. Fired here, before the session is even created, so the load starts + // concurrently with Claude/Codex/etc. booting rather than after. + if (qsCustomModelSwapInProgress) { + triggerLlamaSwapLoad(cmEndpoint, customModel.modelId); + } + } + const session = new Session({ + id: qsCustomModelSessionId, workingDir: resolvedCasePath, name: sessionName ? sessionName.slice(0, MAX_SESSION_NAME_LENGTH) : '', mux: ctx.mux, @@ -3502,11 +3663,24 @@ export function registerSessionRoutes( codexConfig: mode === 'codex' ? qsGatedCodexConfig : undefined, geminiConfig: mode === 'gemini' ? qsGatedGeminiConfig : undefined, antigravityConfig: mode === 'antigravity' ? qsGatedAntigravityConfig : undefined, - piConfig: mode === 'pi' ? qsGatedPiConfig : undefined, - grokConfig: mode === 'grok' ? qsGatedGrokConfig : undefined, + piConfig: + mode === 'pi' + ? qsCustomModelLaunchModel !== undefined + ? { ...(qsGatedPiConfig ?? {}), model: qsCustomModelLaunchModel } + : qsGatedPiConfig + : undefined, + grokConfig: + mode === 'grok' + ? qsCustomModelLaunchModel !== undefined + ? { ...(qsGatedGrokConfig ?? {}), model: qsCustomModelLaunchModel } + : qsGatedGrokConfig + : undefined, deepSeekConfig: mode === 'deepseek' ? qsGatedDeepSeekConfig : undefined, - ompConfig: resolveOmpConfigForCreate(mode, resolvedCasePath, ompConfig), - envOverrides: qsGatedEnvOverrides, + ompConfig: + mode === 'omp' && qsCustomModelLaunchModel !== undefined + ? { ...(qsResolvedOmpConfig ?? {}), model: qsCustomModelLaunchModel } + : qsResolvedOmpConfig, + envOverrides: qsCustomModelEnvOverrides, effort, remote, docker, @@ -3515,6 +3689,15 @@ export function registerSessionRoutes( parentSessionId: qsParentSessionId, }); + // Records the selection for session.customModel/getCustomModelForPersist() and future + // clear/switch calls — the actual env vars and launch-model config are already part of + // the launch above (constructor envOverrides, piConfig/grokConfig/ompConfig.model), so + // this is bookkeeping only, never a restart: setCustomModel() is synchronous state, no + // tmux IO of its own (see its own doc comment in session.ts). + if (qsCustomModelBookkeeping) { + session.setCustomModel(qsCustomModelBookkeeping, qsCustomModelEnvOverrides); + } + // Auto-detect completion phrase from CLAUDE.md BEFORE broadcasting // so the initial state already has the phrase configured (only if globally enabled) if (getCli(mode)?.capabilities.ralph && !remote && !docker && ctx.store.getConfig().ralphEnabled) { @@ -3609,6 +3792,7 @@ export function registerSessionRoutes( sessionId: session.id, casePath: resolvedCasePath, caseName, + ...(customModel ? { modelSwapInProgress: qsCustomModelSwapInProgress } : {}), }; } catch (err) { // Clean up session on error to prevent orphaned resources diff --git a/src/web/schemas.ts b/src/web/schemas.ts index b5dabdd09..686d1370d 100644 --- a/src/web/schemas.ts +++ b/src/web/schemas.ts @@ -1033,6 +1033,25 @@ export const QuickStartSchema = z.object({ * because it takes an existing `workingDir` and so never creates a directory to label. */ agentOrigin: z.string().max(64).optional(), + /** + * Custom Model Endpoint Profiles (docs/custom-model-endpoints-plan.md): launches directly + * on this saved endpoint/model instead of the mode's native backend, computed server-side + * from the admin-configured endpoint store the same way `POST /api/sessions/:id/custom- + * model` does — never trusting raw env values from the client. One-shot, launch-time + * equivalent of that route: no restart, so no visible relaunch (that route's restart-in- + * place is still what an ALREADY-RUNNING session uses to switch later). Rejected for + * remote/docker cases, same reasoning as `envOverrides` above. `confirmed` mirrors that + * route's field: skips the llama-swap "this will unload it for another session" check on + * a deliberate retry. + */ + customModel: z + .object({ + endpointId: z.string().regex(/^[a-zA-Z0-9_-]+$/, 'Invalid endpoint id'), + modelId: z.string().min(1).max(200), + confirmed: z.boolean().optional(), + }) + .strict() + .optional(), }); // ========== Hook Events ========== @@ -1918,6 +1937,17 @@ export const CustomModelHostSchema = z.object({ authStyle: z.enum(['bearer', 'api-key']).optional(), models: z.array(z.string().max(200)).max(200).optional(), lastDiscoveredAt: z.string().max(64).optional(), + // The Run-menu picker's per-endpoint default; validated against `models` at the + // route layer (schema-level cross-field checks can't see the array narrowed the + // same way a `.refine()` closure could, and the route already re-reads the stored + // host to apply it, so the check belongs there once, not duplicated into a refine + // that would run on every unrelated field edit too). + defaultModelId: z.string().max(200).optional(), + // Server-populated by discovery (custom-model-routes.ts); accepted here only so a client + // round-tripping the GET response back through PUT (edit-save) doesn't drop it. + modelContextLengths: z.record(z.string().max(200), z.number().int().positive().max(100_000_000)).optional(), + // Same reasoning as modelContextLengths above. + modelSizesGB: z.record(z.string().max(200), z.number().positive().max(100_000)).optional(), }); /** POST /api/sessions/:id/custom-model — apply or clear a session's custom-model selection. */ @@ -1925,6 +1955,10 @@ export const CustomModelSelectionSchema = z.union([ z.object({ endpointId: z.string().regex(/^[a-zA-Z0-9_-]+$/, 'Invalid endpoint id'), modelId: z.string().min(1).max(200), + // Set once the caller has already shown the "this will unload for session(s) + // X" warning (see session-routes.ts's llama-swap conflict check) and the user chose to + // proceed anyway — skips that check on this call instead of asking again. + confirmed: z.boolean().optional(), }), z.object({ clear: z.literal(true) }), ]); diff --git a/src/web/server.ts b/src/web/server.ts index cf5927c0c..ad3b07c94 100644 --- a/src/web/server.ts +++ b/src/web/server.ts @@ -67,7 +67,7 @@ import { import { imageWatcher } from '../image-watcher.js'; import { workflowRunWatcher, summarizeRun } from '../workflow-run-watcher.js'; import { attachmentRegistry, buildFileThumbnailRoute, registerExternalAttachment } from '../attachment-registry.js'; -import { getCli } from '../config/cli-registry/registry.js'; +import { getCli, enabledClis } from '../config/cli-registry/registry.js'; import { readCustomModelHosts } from '../custom-model-hosts.js'; import { applyCustomModelInjection, customModelConfigDir, removeConfigDir } from '../custom-model-injection-apply.js'; import type { CustomModelBookkeeping } from '../types/session.js'; @@ -190,6 +190,7 @@ import { registerWebviewRoutes, registerTabLayoutRoutes, registerCustomModelRoutes, + refreshAllCustomModelHosts, tryWebviewRefererFallback, } from './routes/index.js'; import { isLostWebviewFrameNavigation } from './webview-proxy.js'; @@ -202,11 +203,26 @@ const __dirname = dirname(fileURLToPath(import.meta.url)); // while capping growth of `sseClientsById` and blocking pathological inputs. const SSE_CLIENT_ID_RE = /^[A-Za-z0-9_-]{8,64}$/; const CODEX_USAGE_POLL_INTERVAL_MS = 5 * 60_000; +const CUSTOM_MODEL_REDISCOVER_INTERVAL_MS = 5 * 60_000; function escapeHtmlText(value: string): string { return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>'); } +/** + * Escapes a JSON string for safe embedding as the body of an inline `` would otherwise close the tag early + * and turn the rest of the document into inert script-body text. Exported so + * it unit-tests without constructing a WebServer (which needs a real tmux). + */ +export function escapeScriptJson(json: string): string { + return json.replace(/', `\n` ); + // Which run modes the Run-menu picker (docs/custom-model-endpoints-plan.md) may + // generate an entry for: read generically off the registry's `capabilities` + // (never an id list here) so a CLI whose customModelInjection lands later shows + // up in the picker with no frontend change, and one that ships `unsupported` + // (antigravity, and `shell`'s `kind !== 'agent'`) never does. + const customModelClis = enabledClis() + .filter((entry) => entry.kind === 'agent' && entry.capabilities.customModelInjection.kind !== 'unsupported') + .map((entry) => ({ id: entry.id, label: entry.label })); + // Unlike the boolean-only __codemanCliAvailable above, this payload carries + // `label`, a string a user's own clis.json can set (CliEntry.label, up to 60 + // chars) — see escapeScriptJson's own doc comment for why that needs escaping + // and __codemanCliAvailable's booleans never did. + const customModelClisJson = escapeScriptJson(JSON.stringify(customModelClis)); + html = html.replace( + '', + `\n` + ); } if (!soloSessionId && process.env.CODEMAN_GESTURE === '1') { html = html.replace('', `\n`); @@ -2703,6 +2736,25 @@ export class WebServer extends EventEmitter { }); } + // Custom Model Endpoint Profiles (docs/custom-model-endpoints-plan.md): keeps + // each saved endpoint's discovered model list current with no manual + // "Discover" click, so a model added on the server side (or one that drops + // off) shows up in the Run-menu picker within one cycle. Best-effort per + // endpoint (refreshAllCustomModelHosts skips one that's unreachable rather + // than failing the sweep) and off in tests for the same reason the Codex + // poll above is — no real network to hit, no server instance to keep alive. + if (!this.testMode) { + this.cleanup.setInterval( + () => { + refreshAllCustomModelHosts().catch((err) => { + console.error('[custom-model] periodic re-discovery failed:', getErrorMessage(err)); + }); + }, + CUSTOM_MODEL_REDISCOVER_INTERVAL_MS, + { description: 'custom model endpoint re-discovery' } + ); + } + // Start scheduled runs cleanup timer this.cleanup.setInterval( () => { diff --git a/test/cli-registry-no-id-branching.test.ts b/test/cli-registry-no-id-branching.test.ts index 8d1bc4de8..b5ba1b3e0 100644 --- a/test/cli-registry-no-id-branching.test.ts +++ b/test/cli-registry-no-id-branching.test.ts @@ -80,6 +80,8 @@ const ALLOWED_BRANCHES: Record = { "web/routes/session-routes.ts::mode === 'pi'": 'legacy Config plumbing', "web/routes/session-routes.ts::mode === 'grok'": 'legacy Config plumbing', "web/routes/session-routes.ts::mode === 'deepseek'": 'legacy Config plumbing', + "web/routes/session-routes.ts::mode === 'omp'": + 'legacy Config plumbing (custom-model launchModel merge onto ompConfig, same selection resolveOmpConfigForCreate already makes internally)', "web/server.ts::mode === 'opencode'": 'legacy Config plumbing (session recovery)', "web/server.ts::mode === 'codex'": 'legacy Config plumbing (session recovery)', "web/server.ts::mode === 'gemini'": 'legacy Config plumbing (session recovery)', diff --git a/test/custom-model-endpoint-rediscovery.test.ts b/test/custom-model-endpoint-rediscovery.test.ts new file mode 100644 index 000000000..b0dedf7c2 --- /dev/null +++ b/test/custom-model-endpoint-rediscovery.test.ts @@ -0,0 +1,368 @@ +/** + * @fileoverview Tests for `refreshAllCustomModelHosts()`, the periodic + * background sweep behind server.ts's "custom model endpoint re-discovery" + * timer (docs/custom-model-endpoints-plan.md). Kept in its own file rather + * than folded into test/routes/custom-model-routes.test.ts: that file's data + * dir is shared across every test in it (one temp HOME per FILE, not per + * test — test/setup.ts), and a sweep that walks every saved host would pick + * up every host any other test in that file happened to create, making an + * exact call-count or exact-host assertion meaningless. A dedicated file + * gets its own clean temp HOME. + * + * Port: N/A (no server; drives readCustomModelHosts/writeCustomModelHosts + * directly plus the mocked webviewFetch dispatcher). + */ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { getDataDir } from '../src/config/instance.js'; +import { readCustomModelHosts, writeCustomModelHosts, type CustomModelHost } from '../src/custom-model-hosts.js'; +import { refreshAllCustomModelHosts } from '../src/web/routes/custom-model-routes.js'; +import { webviewFetch } from '../src/web/webview-egress.js'; + +vi.mock('../src/web/webview-egress.js', async () => { + const actual = await vi.importActual('../src/web/webview-egress.js'); + return { ...actual, webviewFetch: vi.fn() }; +}); + +const fetchMock = vi.mocked(webviewFetch); + +function host(overrides: Partial & Pick): CustomModelHost { + return { label: overrides.id, ...overrides }; +} + +beforeEach(() => { + fetchMock.mockReset(); +}); + +describe('refreshAllCustomModelHosts (the periodic re-discovery sweep)', () => { + it('refreshes every saved endpoint, best-effort — one unreachable host does not stop the others', async () => { + const dir = getDataDir(); + await writeCustomModelHosts(dir, [ + host({ id: 'ok', baseUrl: 'http://localhost:8080' }), + host({ id: 'down', baseUrl: 'http://localhost:8081' }), + ]); + fetchMock.mockImplementation(async (url: URL) => { + if (url.href.includes('8081')) throw new TypeError('fetch failed', { cause: new Error('ECONNREFUSED') }); + return new Response(JSON.stringify({ data: [{ id: 'qwen3' }] }), { status: 200 }); + }); + + await refreshAllCustomModelHosts(); + + const hosts = await readCustomModelHosts(dir); + const ok = hosts.find((h) => h.id === 'ok'); + const down = hosts.find((h) => h.id === 'down'); + expect(ok?.models).toEqual(['qwen3']); + expect(ok?.lastDiscoveredAt).toBeTruthy(); + expect(down?.models ?? []).toEqual([]); + expect(down?.lastDiscoveredAt).toBeFalsy(); + }); + + it('skips a host whose baseUrl is blocked, without making a request', async () => { + const dir = getDataDir(); + // Written directly rather than through the POST route, which already + // refuses this at save time — this simulates a record that pre-dates the + // guard, or was hand-edited on disk. The sweep must not trust it either. + await writeCustomModelHosts(dir, [host({ id: 'meta', baseUrl: 'http://169.254.169.254/' })]); + + fetchMock.mockResolvedValue(new Response(JSON.stringify({ data: [{ id: 'x' }] }), { status: 200 })); + await refreshAllCustomModelHosts(); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('drops a stale default and preserves lastDiscoveredAt semantics, same as manual discovery', async () => { + const dir = getDataDir(); + await writeCustomModelHosts(dir, [ + host({ id: 'ep', baseUrl: 'http://localhost:8080', models: ['qwen3'], defaultModelId: 'qwen3' }), + ]); + fetchMock.mockResolvedValue(new Response(JSON.stringify({ data: [{ id: 'llama3' }] }), { status: 200 })); + + await refreshAllCustomModelHosts(); + + const [updated] = await readCustomModelHosts(dir); + expect(updated.models).toEqual(['llama3']); + expect(updated.defaultModelId).toBeUndefined(); + expect(updated.lastDiscoveredAt).toBeTruthy(); + }); + + it('keeps a default that is still present after the sweep', async () => { + const dir = getDataDir(); + await writeCustomModelHosts(dir, [ + host({ id: 'ep', baseUrl: 'http://localhost:8080', models: ['qwen3'], defaultModelId: 'qwen3' }), + ]); + fetchMock.mockResolvedValue( + new Response(JSON.stringify({ data: [{ id: 'qwen3' }, { id: 'llama3' }] }), { status: 200 }) + ); + + await refreshAllCustomModelHosts(); + + const [updated] = await readCustomModelHosts(dir); + expect(updated.defaultModelId).toBe('qwen3'); + }); + + it('does not resurrect an endpoint deleted while the sweep was in flight', async () => { + const dir = getDataDir(); + await writeCustomModelHosts(dir, [host({ id: 'deleted', baseUrl: 'http://localhost:8080' })]); + + fetchMock.mockImplementation(async () => { + // Simulate an admin deleting the endpoint between the sweep's fetch and + // its read-modify-write — the delete must win, not be overwritten by a + // refresh that started before it. + const current = await readCustomModelHosts(dir); + await writeCustomModelHosts( + dir, + current.filter((h) => h.id !== 'deleted') + ); + return new Response(JSON.stringify({ data: [{ id: 'qwen3' }] }), { status: 200 }); + }); + + await expect(refreshAllCustomModelHosts()).resolves.toBeUndefined(); + const hosts = await readCustomModelHosts(dir); + expect(hosts.find((h) => h.id === 'deleted')).toBeUndefined(); + }); + + it('leaves the store untouched when there are no saved endpoints at all', async () => { + await expect(refreshAllCustomModelHosts()).resolves.toBeUndefined(); + expect(fetchMock).not.toHaveBeenCalled(); + }); +}); + +describe('refreshAllCustomModelHosts: context-length enrichment (llama.cpp/llama-swap /props)', () => { + it('probes /props?model= only for a model reported loaded, and stores its n_ctx', async () => { + const dir = getDataDir(); + await writeCustomModelHosts(dir, [host({ id: 'ep', baseUrl: 'http://localhost:8080' })]); + fetchMock.mockImplementation(async (url: URL) => { + if (url.pathname === '/v1/models') { + return new Response( + JSON.stringify({ + data: [ + { id: 'loaded-model', status: { value: 'loaded' } }, + { id: 'unloaded-model', status: { value: 'unloaded' } }, + ], + }), + { status: 200 } + ); + } + if (url.pathname === '/props') { + // Must never be reached for the unloaded model — asserted below by call count. + expect(url.searchParams.get('model')).toBe('loaded-model'); + return new Response(JSON.stringify({ n_ctx: 16384 }), { status: 200 }); + } + throw new Error(`unexpected request: ${url.href}`); + }); + + await refreshAllCustomModelHosts(); + + const [updated] = await readCustomModelHosts(dir); + expect(updated.modelContextLengths).toEqual({ 'loaded-model': 16384 }); + const propsCalls = fetchMock.mock.calls.filter(([url]) => (url as URL).pathname === '/props'); + expect(propsCalls).toHaveLength(1); + }); + + it('never probes /props at all when no entry mentions status — feature-detected, not assumed unloaded', async () => { + const dir = getDataDir(); + await writeCustomModelHosts(dir, [host({ id: 'ep', baseUrl: 'http://localhost:8080' })]); + fetchMock.mockResolvedValue(new Response(JSON.stringify({ data: [{ id: 'qwen3' }] }), { status: 200 })); + + await refreshAllCustomModelHosts(); + + expect(fetchMock).toHaveBeenCalledTimes(1); // /v1/models only + const [updated] = await readCustomModelHosts(dir); + expect(updated.modelContextLengths).toBeUndefined(); + }); + + it('keeps a previously-learned context length for a model no longer loaded, drops it once the model disappears entirely', async () => { + const dir = getDataDir(); + await writeCustomModelHosts(dir, [ + host({ + id: 'ep', + baseUrl: 'http://localhost:8080', + models: ['a', 'b'], + modelContextLengths: { a: 8192, b: 4096 }, + }), + ]); + // This round: 'a' is loaded (re-confirmed), 'b' is gone from the list entirely. + fetchMock.mockImplementation(async (url: URL) => { + if (url.pathname === '/v1/models') { + return new Response(JSON.stringify({ data: [{ id: 'a', status: { value: 'loaded' } }] }), { status: 200 }); + } + return new Response(JSON.stringify({ n_ctx: 8192 }), { status: 200 }); + }); + + await refreshAllCustomModelHosts(); + + const [updated] = await readCustomModelHosts(dir); + expect(updated.modelContextLengths).toEqual({ a: 8192 }); + }); + + it('a failed /props probe for the loaded model is swallowed, leaving no context length rather than failing the sweep', async () => { + const dir = getDataDir(); + await writeCustomModelHosts(dir, [host({ id: 'ep', baseUrl: 'http://localhost:8080' })]); + fetchMock.mockImplementation(async (url: URL) => { + if (url.pathname === '/v1/models') { + return new Response(JSON.stringify({ data: [{ id: 'a', status: { value: 'loaded' } }] }), { status: 200 }); + } + return new Response('nope', { status: 500 }); + }); + + await expect(refreshAllCustomModelHosts()).resolves.toBeUndefined(); + const [updated] = await readCustomModelHosts(dir); + expect(updated.modelContextLengths).toBeUndefined(); + }); + + it('prefers the REAL configured context size parsed from /running’s launch command over /props’s unreliable n_ctx', async () => { + // Confirmed live: llama-swap launched a model with --fit-ctx 16384 (the real, working + // limit — the actual server then refused a request over it), but /props reported + // n_ctx: 154112 for the same model, well over what it would really accept. /props must + // never be reached at all once the /running command parse already answered it. + const dir = getDataDir(); + await writeCustomModelHosts(dir, [host({ id: 'ep', baseUrl: 'http://localhost:8080' })]); + fetchMock.mockImplementation(async (url: URL) => { + if (url.pathname === '/v1/models') { + return new Response(JSON.stringify({ data: [{ id: 'qwen3.8-27b', status: { value: 'loaded' } }] }), { + status: 200, + }); + } + if (url.pathname === '/running') { + return new Response( + JSON.stringify({ + running: [ + { + model: 'qwen3.8-27b', + state: 'ready', + cmd: 'llama-server -m /models/Qwen3.8-27B.gguf --flash-attn on --jinja --fit-ctx 16384 --host 0.0.0.0 --port 5840', + }, + ], + }), + { status: 200 } + ); + } + if (url.pathname === '/props') throw new Error('must never be reached — the cmd parse already answered it'); + throw new Error(`unexpected request: ${url.href}`); + }); + + await refreshAllCustomModelHosts(); + + const [updated] = await readCustomModelHosts(dir); + expect(updated.modelContextLengths).toEqual({ 'qwen3.8-27b': 16384 }); + }); + + it('falls back to /props when /running has no cmd, or the cmd states no recognizable context flag', async () => { + const dir = getDataDir(); + await writeCustomModelHosts(dir, [host({ id: 'ep', baseUrl: 'http://localhost:8080' })]); + fetchMock.mockImplementation(async (url: URL) => { + if (url.pathname === '/v1/models') { + return new Response(JSON.stringify({ data: [{ id: 'a', status: { value: 'loaded' } }] }), { status: 200 }); + } + if (url.pathname === '/running') { + return new Response( + JSON.stringify({ running: [{ model: 'a', state: 'ready', cmd: 'llama-server -m /models/a.gguf' }] }), + { status: 200 } + ); + } + if (url.pathname === '/props') return new Response(JSON.stringify({ n_ctx: 8192 }), { status: 200 }); + throw new Error(`unexpected request: ${url.href}`); + }); + + await refreshAllCustomModelHosts(); + + const [updated] = await readCustomModelHosts(dir); + expect(updated.modelContextLengths).toEqual({ a: 8192 }); + }); + + it('also recognizes a plain -c/--ctx-size flag, not just llama-swap’s own --fit-ctx', async () => { + const dir = getDataDir(); + await writeCustomModelHosts(dir, [host({ id: 'ep', baseUrl: 'http://localhost:8080' })]); + fetchMock.mockImplementation(async (url: URL) => { + if (url.pathname === '/v1/models') { + return new Response(JSON.stringify({ data: [{ id: 'a', status: { value: 'loaded' } }] }), { status: 200 }); + } + if (url.pathname === '/running') { + return new Response( + JSON.stringify({ + running: [{ model: 'a', state: 'ready', cmd: 'llama-server -m /models/a.gguf --ctx-size 8192' }], + }), + { status: 200 } + ); + } + throw new Error(`unexpected request: ${url.href}`); // /props must never be reached + }); + + await refreshAllCustomModelHosts(); + + const [updated] = await readCustomModelHosts(dir); + expect(updated.modelContextLengths).toEqual({ a: 8192 }); + }); +}); + +describe('refreshAllCustomModelHosts: model-size enrichment (parsed from /v1/models description)', () => { + it('parses a GB figure out of an auto-discovered model’s description', async () => { + const dir = getDataDir(); + await writeCustomModelHosts(dir, [host({ id: 'ep', baseUrl: 'http://localhost:8080' })]); + fetchMock.mockResolvedValue( + new Response( + JSON.stringify({ + data: [{ id: 'qwen3.8-27b', description: 'Auto-discovered 16.35 GB - parameters auto-fitted by llama.cpp' }], + }), + { status: 200 } + ) + ); + + await refreshAllCustomModelHosts(); + + const [updated] = await readCustomModelHosts(dir); + expect(updated.modelSizesGB).toEqual({ 'qwen3.8-27b': 16.35 }); + }); + + it('gets no size at all for a hand-configured profile whose own description states none', async () => { + const dir = getDataDir(); + await writeCustomModelHosts(dir, [host({ id: 'ep', baseUrl: 'http://localhost:8080' })]); + fetchMock.mockResolvedValue( + new Response( + JSON.stringify({ + data: [{ id: 'big', description: 'General-purpose reasoning model, MoE CPU-offloaded. Default profile.' }], + }), + { status: 200 } + ) + ); + + await refreshAllCustomModelHosts(); + + const [updated] = await readCustomModelHosts(dir); + expect(updated.modelSizesGB).toBeUndefined(); + }); + + it('populated regardless of loaded state — unlike context length, no /props probe is needed', async () => { + const dir = getDataDir(); + await writeCustomModelHosts(dir, [host({ id: 'ep', baseUrl: 'http://localhost:8080' })]); + fetchMock.mockImplementation(async (url: URL) => { + if (url.pathname === '/v1/models') { + return new Response( + JSON.stringify({ + data: [{ id: 'unloaded-model', description: 'Auto-discovered 4.91 GB - parameters auto-fitted' }], + }), + { status: 200 } + ); + } + throw new Error(`unexpected request: ${url.href}`); // /props must never be reached for this + }); + + await refreshAllCustomModelHosts(); + + const [updated] = await readCustomModelHosts(dir); + expect(updated.modelSizesGB).toEqual({ 'unloaded-model': 4.91 }); + }); + + it('keeps a previously-learned size for a model still present, drops it once the model disappears entirely', async () => { + const dir = getDataDir(); + await writeCustomModelHosts(dir, [ + host({ id: 'ep', baseUrl: 'http://localhost:8080', models: ['a', 'b'], modelSizesGB: { a: 8, b: 16 } }), + ]); + fetchMock.mockResolvedValue( + new Response(JSON.stringify({ data: [{ id: 'a', description: 'no GB figure here' }] }), { status: 200 }) + ); + + await refreshAllCustomModelHosts(); + + const [updated] = await readCustomModelHosts(dir); + expect(updated.modelSizesGB).toEqual({ a: 8 }); // 'a' kept from before, 'b' dropped (gone from the list) + }); +}); diff --git a/test/custom-model-injection-apply.test.ts b/test/custom-model-injection-apply.test.ts new file mode 100644 index 000000000..450b7eb0d --- /dev/null +++ b/test/custom-model-injection-apply.test.ts @@ -0,0 +1,204 @@ +/** + * @fileoverview Tests for the two custom-model IO-layer fixes on top of the pure builder + * (docs/custom-model-endpoints-plan.md): + * + * 1. `contextLengthVar` — a discovered per-model context length reaches the actual + * session env (CLAUDE_CODE_MAX_CONTEXT_TOKENS), so a CLI stops assuming a large + * default window for an unrecognized custom model id and overflowing a much + * smaller real one. + * 2. `configDirVar` — an isolated, empty config directory is created and pointed at + * (CLAUDE_CONFIG_DIR), so an injected API key never shares a directory with a + * stored claude.ai OAuth session; `projects` is symlinked back into the real + * config dir so the response viewer/subagent windows/Read My Mind keep working. + * + * Port: N/A (no server; filesystem-only, under a temp CODEMAN data dir from test/setup.ts). + */ +import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it } from 'vitest'; +import { getCli } from '../src/config/cli-registry/index.js'; +import { applyCustomModelInjection, customModelConfigDir } from '../src/custom-model-injection-apply.js'; +import type { CustomModelEndpoint } from '../src/custom-model-injection.js'; + +const endpoint: CustomModelEndpoint = { + id: 'ep1', + label: 'llama.cpp box', + baseUrl: 'http://192.168.1.50:8080', + apiKey: 'my-key', +}; + +function entryOrThrow(id: string) { + const entry = getCli(id); + if (!entry) throw new Error(`missing CLI registry entry: ${id}`); + return entry; +} + +const sessionsToClean: string[] = []; +afterEach(() => { + for (const id of sessionsToClean.splice(0)) rmSync(customModelConfigDir(id), { recursive: true, force: true }); +}); + +describe('applyCustomModelInjection: context length', () => { + it('claude: passes a known context length through to CLAUDE_CODE_MAX_CONTEXT_TOKENS', () => { + sessionsToClean.push('sess-ctx-1'); + const applied = applyCustomModelInjection(entryOrThrow('claude'), endpoint, 'qwen3', 'sess-ctx-1', 16384); + expect(applied?.envOverrides.CLAUDE_CODE_MAX_CONTEXT_TOKENS).toBe('16384'); + expect(applied?.envKeys).toContain('CLAUDE_CODE_MAX_CONTEXT_TOKENS'); + }); + + it('claude: omits the var entirely when the context length is unknown', () => { + sessionsToClean.push('sess-ctx-2'); + const applied = applyCustomModelInjection(entryOrThrow('claude'), endpoint, 'qwen3', 'sess-ctx-2'); + expect(applied?.envOverrides.CLAUDE_CODE_MAX_CONTEXT_TOKENS).toBeUndefined(); + }); + + it('deepseek: has no contextLengthVar declared, so a passed-in length is a no-op', () => { + const applied = applyCustomModelInjection(entryOrThrow('deepseek'), endpoint, 'qwen3', 'sess-ctx-3', 16384); + expect(Object.keys(applied?.envOverrides ?? {}).sort()).toEqual(['DEEPSEEK_API_KEY', 'DEEPSEEK_BASE_URL']); + }); +}); + +describe('applyCustomModelInjection: CLAUDE_CONFIG_DIR isolation', () => { + it('claude: creates an isolated config dir (no real credential/config files) and points CLAUDE_CONFIG_DIR at it', () => { + const sessionId = 'sess-cfgdir-1'; + sessionsToClean.push(sessionId); + const applied = applyCustomModelInjection(entryOrThrow('claude'), endpoint, 'qwen3', sessionId); + const expectedDir = customModelConfigDir(sessionId); + expect(applied?.envOverrides.CLAUDE_CONFIG_DIR).toBe(expectedDir); + expect(applied?.configDir).toBe(expectedDir); + expect(existsSync(expectedDir)).toBe(true); + // Only the trust-seed file and the projects link — no real OAuth credential/config. + const entries = readdirSync(expectedDir).filter((name) => name !== 'projects'); + expect(entries).toEqual(['.claude.json']); + }); + + it('claude: symlinks (or junctions) projects back to the real config dir so the response viewer keeps working', () => { + const sessionId = 'sess-cfgdir-2'; + sessionsToClean.push(sessionId); + const applied = applyCustomModelInjection(entryOrThrow('claude'), endpoint, 'qwen3', sessionId); + const link = join(applied!.configDir!, 'projects'); + // Best-effort: only assert the link exists if it was actually created (the real + // ~/.claude/projects may not exist on a bare CI box, in which case linking is skipped). + if (existsSync(join(homedir(), '.claude', 'projects'))) { + expect(existsSync(link)).toBe(true); + expect(lstatSync(link).isSymbolicLink() || lstatSync(link).isDirectory()).toBe(true); + } + }); + + it('claude: re-applying to the same session is idempotent (boot-recovery re-apply)', () => { + const sessionId = 'sess-cfgdir-3'; + sessionsToClean.push(sessionId); + const first = applyCustomModelInjection(entryOrThrow('claude'), endpoint, 'qwen3', sessionId); + const second = applyCustomModelInjection(entryOrThrow('claude'), endpoint, 'qwen3', sessionId); + expect(second?.configDir).toBe(first?.configDir); + expect(existsSync(first!.configDir!)).toBe(true); + }); + + it('pi: configDir-kind CLIs are unaffected — no configDirVar concept for them', () => { + const sessionId = 'sess-cfgdir-pi'; + sessionsToClean.push(sessionId); + const applied = applyCustomModelInjection(entryOrThrow('pi'), endpoint, 'qwen3', sessionId); + expect(applied?.envOverrides.HOME).toBe(customModelConfigDir(sessionId)); + }); + + it('deepseek: no configDirVar declared, so no config dir is created at all', () => { + const sessionId = 'sess-cfgdir-deepseek'; + const applied = applyCustomModelInjection(entryOrThrow('deepseek'), endpoint, 'qwen3', sessionId); + expect(applied?.configDir).toBeUndefined(); + expect(existsSync(customModelConfigDir(sessionId))).toBe(false); + }); +}); + +describe('applyCustomModelInjection: apiKeyTrustFile (pre-approves the injected key)', () => { + it('claude: seeds .claude.json so the "Detected a custom API key" prompt never fires', () => { + const sessionId = 'sess-trust-1'; + sessionsToClean.push(sessionId); + const applied = applyCustomModelInjection(entryOrThrow('claude'), endpoint, 'qwen3', sessionId); + const written = JSON.parse(readFileSync(join(applied!.configDir!, '.claude.json'), 'utf8')) as { + customApiKeyResponses: { approved: string[]; rejected: string[] }; + }; + expect(written.customApiKeyResponses.approved).toEqual(['my-key']); + expect(written.customApiKeyResponses.rejected).toEqual([]); + }); + + it('claude: falls back to the dummy key when the endpoint has none, and still seeds it', () => { + const sessionId = 'sess-trust-2'; + sessionsToClean.push(sessionId); + const applied = applyCustomModelInjection( + entryOrThrow('claude'), + { ...endpoint, apiKey: undefined }, + 'qwen3', + sessionId + ); + const written = JSON.parse(readFileSync(join(applied!.configDir!, '.claude.json'), 'utf8')) as { + customApiKeyResponses: { approved: string[] }; + }; + expect(written.customApiKeyResponses.approved).toEqual(['local-dummy-key']); + }); + + it('claude: merges onto fields the CLI itself already wrote into the same isolated dir, never overwrites them', () => { + const sessionId = 'sess-trust-3'; + sessionsToClean.push(sessionId); + const configDir = customModelConfigDir(sessionId); + mkdirSync(configDir, { recursive: true }); + writeFileSync(join(configDir, '.claude.json'), JSON.stringify({ userID: 'abc123', numStartups: 3 })); + + const applied = applyCustomModelInjection(entryOrThrow('claude'), endpoint, 'qwen3', sessionId); + + const written = JSON.parse(readFileSync(join(applied!.configDir!, '.claude.json'), 'utf8')) as { + userID: string; + numStartups: number; + customApiKeyResponses: { approved: string[] }; + }; + expect(written.userID).toBe('abc123'); + expect(written.numStartups).toBe(3); + expect(written.customApiKeyResponses.approved).toEqual(['my-key']); + }); + + it('claude: a corrupt existing file is treated as absent rather than failing the apply', () => { + const sessionId = 'sess-trust-4'; + sessionsToClean.push(sessionId); + const configDir = customModelConfigDir(sessionId); + mkdirSync(configDir, { recursive: true }); + writeFileSync(join(configDir, '.claude.json'), '{ not valid json'); + + expect(() => applyCustomModelInjection(entryOrThrow('claude'), endpoint, 'qwen3', sessionId)).not.toThrow(); + const written = JSON.parse(readFileSync(join(configDir, '.claude.json'), 'utf8')) as { + customApiKeyResponses: { approved: string[] }; + }; + expect(written.customApiKeyResponses.approved).toEqual(['my-key']); + }); + + it('claude: re-approving the same key does not duplicate it in the approved list', () => { + const sessionId = 'sess-trust-5'; + sessionsToClean.push(sessionId); + applyCustomModelInjection(entryOrThrow('claude'), endpoint, 'qwen3', sessionId); + const second = applyCustomModelInjection(entryOrThrow('claude'), endpoint, 'llama3', sessionId); + const written = JSON.parse(readFileSync(join(second!.configDir!, '.claude.json'), 'utf8')) as { + customApiKeyResponses: { approved: string[] }; + }; + expect(written.customApiKeyResponses.approved).toEqual(['my-key']); + }); + + it('opencode: has no apiKeyTrustFile declared (no configDirVar at all), nothing is seeded', () => { + const sessionId = 'sess-trust-opencode'; + const applied = applyCustomModelInjection(entryOrThrow('opencode'), endpoint, 'qwen3', sessionId); + expect(applied?.configDir).toBeUndefined(); + expect(existsSync(customModelConfigDir(sessionId))).toBe(false); + }); +}); + +describe('applyCustomModelInjection: pre-existing behavior unaffected', () => { + it('opencode: still returns a plain env-kind result with no configDir', () => { + const sessionId = 'sess-opencode-1'; + const applied = applyCustomModelInjection(entryOrThrow('opencode'), endpoint, 'qwen3', sessionId); + expect(applied?.configDir).toBeUndefined(); + expect(applied?.envOverrides.OPENCODE_CONFIG_CONTENT).toBeTruthy(); + }); + + it('antigravity: still undefined (unsupported)', () => { + const applied = applyCustomModelInjection(entryOrThrow('antigravity'), endpoint, 'qwen3', 'sess-agy-1'); + expect(applied).toBeUndefined(); + }); +}); diff --git a/test/custom-model-injection.test.ts b/test/custom-model-injection.test.ts index 2acd08ca8..3655c2fc9 100644 --- a/test/custom-model-injection.test.ts +++ b/test/custom-model-injection.test.ts @@ -58,6 +58,31 @@ describe('buildCustomModelInjection', () => { }); }); + it('claude: also declares configDirVar (CLAUDE_CONFIG_DIR isolation) on the env-kind result', () => { + const result = buildCustomModelInjection(entryOrThrow('claude'), endpoint, 'qwen3'); + if (result.kind !== 'env') throw new Error('unreachable'); + expect(result.configDirVar).toBe('CLAUDE_CONFIG_DIR'); + }); + + it('claude: injects CLAUDE_CODE_MAX_CONTEXT_TOKENS when a context length is known', () => { + const result = buildCustomModelInjection(entryOrThrow('claude'), endpoint, 'qwen3', 16384); + if (result.kind !== 'env') throw new Error('unreachable'); + expect(result.envOverrides.CLAUDE_CODE_MAX_CONTEXT_TOKENS).toBe('16384'); + }); + + it('claude: omits CLAUDE_CODE_MAX_CONTEXT_TOKENS when the context length is unknown', () => { + const result = buildCustomModelInjection(entryOrThrow('claude'), endpoint, 'qwen3'); + if (result.kind !== 'env') throw new Error('unreachable'); + expect(result.envOverrides.CLAUDE_CODE_MAX_CONTEXT_TOKENS).toBeUndefined(); + }); + + it('claude: also declares apiKeyTrustFile, carrying the literal apiKey used', () => { + const result = buildCustomModelInjection(entryOrThrow('claude'), endpoint, 'qwen3'); + if (result.kind !== 'env') throw new Error('unreachable'); + expect(result.apiKeyTrustFile).toEqual({ relPath: '.claude.json', shape: 'claude-api-key-responses' }); + expect(result.apiKey).toBe('my-key'); + }); + it('claude: falls back to a dummy key when the endpoint has none', () => { const result = buildCustomModelInjection(entryOrThrow('claude'), { ...endpoint, apiKey: undefined }, 'qwen3'); if (result.kind !== 'env') throw new Error('unreachable'); diff --git a/test/custom-model-one-shot-launch.test.ts b/test/custom-model-one-shot-launch.test.ts new file mode 100644 index 000000000..c4ba8598f --- /dev/null +++ b/test/custom-model-one-shot-launch.test.ts @@ -0,0 +1,238 @@ +/** + * @fileoverview Frontend tests for the one-shot custom-model launch path added to + * session-ui.js (docs/custom-model-endpoints-plan.md): `runCustomModelEntry` dispatches + * to `_runCustomModelEntryOneShot` for every custom-model-eligible CLI except claude, + * which launches directly on the endpoint (no restart) by folding `customModel` into + * the run() function's own `/api/quick-start` body via `_pendingCustomModelForLaunch` + * and `_quickStartWithCustomModelConfirm`. Fixes the visible native-boot-then-restart the + * restart-after-launch path (`_runCustomModelEntryViaRestart`, still used for claude) + * showed on every custom-model run — confirmed live on Codex, whose TUI fully + * reinitializes on a restart. + * + * Uses the same JSDOM + `runScripts: "dangerously"` approach as + * test/custom-model-run-menu-ui.test.ts, extended with the DOM elements runCodex() (the + * CLI this was reported against) reads. + * + * Port: none. + */ +import { readFileSync } from 'node:fs'; +import { JSDOM } from 'jsdom'; +import { describe, expect, it } from 'vitest'; + +const CONSTANTS_JS = readFileSync(new URL('../src/web/public/constants.js', import.meta.url), 'utf-8'); +const SESSION_UI_JS = readFileSync(new URL('../src/web/public/session-ui.js', import.meta.url), 'utf-8'); + +function bootApp() { + const dom = new JSDOM( + ` + + + +
+ `, + { url: 'http://localhost/', runScripts: 'dangerously' } + ); + const win = dom.window as unknown as Window & typeof globalThis & { CodemanApp: new () => any }; + (win as unknown as { eval: (s: string) => void }).eval('window.CodemanApp = function CodemanApp() {};'); + (win as unknown as { eval: (s: string) => void }).eval(CONSTANTS_JS); + (win as unknown as { eval: (s: string) => void }).eval(SESSION_UI_JS); + const app = new win.CodemanApp(); + app.cases = [{ name: 'testcase' }]; + app.terminal = { focus: () => {} }; + app.loadAppSettingsFromStorage = () => ({}); + app.getCaseSettings = () => ({}); + app.buildEnvOverrides = () => ({}); + app.showToast = () => {}; + app._beginSessionLaunchStatus = () => 'status-token'; + app._reportSessionLaunchError = (_token: unknown, message: string) => { + app._lastReportedError = message; + }; + app._ensureCreatedSessionVisible = async () => {}; + app.selectSession = async () => {}; + app._nextCaseSessionStartNumber = () => 1; + return { win, app }; +} + +describe('runCustomModelEntry dispatch', () => { + it('routes claude through the restart-after-launch path', async () => { + const { app } = bootApp(); + let calledRestart = false; + let calledOneShot = false; + app._runCustomModelEntryViaRestart = async () => { + calledRestart = true; + }; + app._runCustomModelEntryOneShot = async () => { + calledOneShot = true; + }; + await app.runCustomModelEntry('claude', 'llama-box', 'qwen3'); + expect(calledRestart).toBe(true); + expect(calledOneShot).toBe(false); + }); + + it('routes every other custom-model-eligible CLI through the one-shot path', async () => { + for (const mode of ['opencode', 'codex', 'gemini', 'pi', 'grok', 'deepseek', 'omp']) { + const { app } = bootApp(); + let calledRestart = false; + let calledOneShot = false; + app._runCustomModelEntryViaRestart = async () => { + calledRestart = true; + }; + app._runCustomModelEntryOneShot = async () => { + calledOneShot = true; + }; + await app.runCustomModelEntry(mode, 'llama-box', 'qwen3'); + expect(calledRestart, mode).toBe(false); + expect(calledOneShot, mode).toBe(true); + } + }); +}); + +describe('_runCustomModelEntryOneShot', () => { + it('stashes the pick on _pendingCustomModelForLaunch for the duration of run(), then clears it', async () => { + const { app } = bootApp(); + let seenDuringRun: unknown; + app.run = async function (this: typeof app) { + seenDuringRun = this._pendingCustomModelForLaunch; + }; + await app._runCustomModelEntryOneShot('codex', 'llama-box', 'qwen3'); + expect(seenDuringRun).toEqual({ endpointId: 'llama-box', modelId: 'qwen3' }); + expect(app._pendingCustomModelForLaunch).toBeUndefined(); + }); + + it('clears the pending pick even when run() throws', async () => { + const { app } = bootApp(); + app.run = async () => { + throw new Error('boom'); + }; + await expect(app._runCustomModelEntryOneShot('codex', 'llama-box', 'qwen3')).rejects.toThrow('boom'); + expect(app._pendingCustomModelForLaunch).toBeUndefined(); + }); + + it('starts the loading watcher when the launch reports modelSwapInProgress, passing the new session id', async () => { + const { app } = bootApp(); + app.run = async () => { + app._lastCustomModelLaunchResult = { modelSwapInProgress: true, sessionId: 'new-session' }; + }; + let watched: unknown[] | null = null; + app._watchLlamaSwapLoading = async (...args: unknown[]) => { + watched = args; + }; + await app._runCustomModelEntryOneShot('codex', 'llama-box', 'qwen3'); + expect(watched).toEqual(['llama-box', 'qwen3', 'new-session']); + }); + + it('never starts the watcher when no swap was needed', async () => { + const { app } = bootApp(); + app.run = async () => { + app._lastCustomModelLaunchResult = { modelSwapInProgress: false }; + }; + let watchCalled = false; + app._watchLlamaSwapLoading = async () => { + watchCalled = true; + }; + await app._runCustomModelEntryOneShot('codex', 'llama-box', 'qwen3'); + expect(watchCalled).toBe(false); + }); +}); + +describe('_quickStartWithCustomModelConfirm', () => { + function withFetch(win: Window & typeof globalThis, handler: (body: any) => any) { + (win as unknown as { fetch: typeof fetch }).fetch = (async (_url: string, opts: any) => ({ + json: async () => handler(JSON.parse(opts.body)), + })) as unknown as typeof fetch; + } + + it('returns the response directly when no confirmation is needed', async () => { + const { win, app } = bootApp(); + withFetch(win, (body) => ({ success: true, data: { sessionId: 's1', modelSwapInProgress: false, body } })); + const data = await app._quickStartWithCustomModelConfirm({ + mode: 'codex', + customModel: { endpointId: 'e', modelId: 'm' }, + }); + expect(data.success).toBe(true); + expect(data.data.sessionId).toBe('s1'); + expect(app._lastCustomModelLaunchResult).toEqual(data.data); + }); + + it('confirming re-sends with confirmed:true and returns the second response', async () => { + const { win, app } = bootApp(); + app._confirmModelSwap = async () => true; + let calls = 0; + withFetch(win, (body) => { + calls += 1; + if (calls === 1) { + return { + success: true, + data: { + requiresConfirmation: true, + currentlyLoadedModel: 'llama3', + affectedSessions: [{ id: 's2', name: 'w2' }], + }, + }; + } + expect(body.customModel.confirmed).toBe(true); + return { success: true, data: { sessionId: 's1', modelSwapInProgress: true } }; + }); + const data = await app._quickStartWithCustomModelConfirm({ + mode: 'codex', + customModel: { endpointId: 'e', modelId: 'm' }, + }); + expect(calls).toBe(2); + expect(data.data.sessionId).toBe('s1'); + expect(app._lastCustomModelLaunchResult.modelSwapInProgress).toBe(true); + }); + + it('cancelling never re-sends, and reports a cancellation error', async () => { + const { win, app } = bootApp(); + app._confirmModelSwap = async () => false; + let calls = 0; + withFetch(win, () => { + calls += 1; + return { + success: true, + data: { + requiresConfirmation: true, + currentlyLoadedModel: 'llama3', + affectedSessions: [{ id: 's2', name: 'w2' }], + }, + }; + }); + const data = await app._quickStartWithCustomModelConfirm({ + mode: 'codex', + customModel: { endpointId: 'e', modelId: 'm' }, + }); + expect(calls).toBe(1); + expect(data.success).toBe(false); + expect(data.error).toMatch(/cancelled/i); + expect(app._lastCustomModelLaunchResult).toBeUndefined(); + }); +}); + +describe('runCodex(): one-shot custom-model launch (the CLI this was reported against)', () => { + it('folds _pendingCustomModelForLaunch into the quick-start body as customModel', async () => { + const { win, app } = bootApp(); + (win as unknown as { fetch: typeof fetch }).fetch = (async (url: string, opts?: any) => { + if (url === '/api/codex/status') return { json: async () => ({ data: { available: true } }) }; + const body = JSON.parse(opts.body); + expect(body.customModel).toEqual({ endpointId: 'llama-box', modelId: 'qwen3' }); + return { json: async () => ({ success: true, data: { sessionId: 's1', modelSwapInProgress: false } }) }; + }) as unknown as typeof fetch; + + app._pendingCustomModelForLaunch = { endpointId: 'llama-box', modelId: 'qwen3' }; + await app.runCodex(); + expect(app._lastReportedError).toBeUndefined(); + }); + + it('omits customModel entirely for a plain (non-custom-model) Codex launch', async () => { + const { win, app } = bootApp(); + (win as unknown as { fetch: typeof fetch }).fetch = (async (url: string, opts?: any) => { + if (url === '/api/codex/status') return { json: async () => ({ data: { available: true } }) }; + const body = JSON.parse(opts.body); + expect(body.customModel).toBeUndefined(); + return { json: async () => ({ success: true, data: { sessionId: 's1' } }) }; + }) as unknown as typeof fetch; + + await app.runCodex(); + expect(app._lastReportedError).toBeUndefined(); + }); +}); diff --git a/test/custom-model-run-menu-ui.test.ts b/test/custom-model-run-menu-ui.test.ts new file mode 100644 index 000000000..9dd6868cd --- /dev/null +++ b/test/custom-model-run-menu-ui.test.ts @@ -0,0 +1,886 @@ +/** + * @fileoverview Frontend tests for the Custom Model Endpoint Profiles Run-menu + * picker (docs/custom-model-endpoints-plan.md): the generated entries in + * session-ui.js's `_refreshCustomModelRunOptions()` / `runCustomModelEntry()`. + * + * These are DOM-level facts that need no Playwright and no tmux — `runScripts: + * "dangerously"` is used deliberately (this JSDOM only ever parses markup this + * module itself generated, never live user input) so that a broken inline + * `onclick` attribute shows up as a genuinely uncallable handler, the same way + * it would in a real browser, rather than merely as a string this test parses + * by eye. `test/admin-ui.test.ts` and `test/home-sessions.test.ts` are the + * precedent for driving a real frontend module against a JSDOM window rather + * than a live server. + * + * Port: none. + */ +import { readFileSync } from 'node:fs'; +import { JSDOM } from 'jsdom'; +import { describe, expect, it } from 'vitest'; + +const CONSTANTS_JS = readFileSync(new URL('../src/web/public/constants.js', import.meta.url), 'utf-8'); +const SESSION_UI_JS = readFileSync(new URL('../src/web/public/session-ui.js', import.meta.url), 'utf-8'); + +function resp(body: unknown, ok = true) { + return { ok, json: async () => body }; +} + +/** + * Boots a minimal CodemanApp instance with constants.js + session-ui.js + * evaluated against a real JSDOM window, so escapeHtml and the picker's own + * innerHTML-building code run exactly as they do in the browser. + */ +function bootApp( + options: { + customModelClis?: Array<{ id: string; label: string }>; + hosts?: unknown; + cliAvailable?: (id: string) => boolean; + activeCase?: { location?: string } | null; + settingsEnabled?: boolean; + } = {} +) { + const dom = new JSDOM( + ` + + + +
+ + +
+
+ + + `, + { url: 'http://localhost/', runScripts: 'dangerously' } + ); + const win = dom.window as unknown as Window & + typeof globalThis & { + CodemanApp: new () => any; + __codemanCustomModelClis?: Array<{ id: string; label: string }>; + }; + (win as unknown as { eval: (s: string) => void }).eval('window.CodemanApp = function CodemanApp() {};'); + (win as unknown as { eval: (s: string) => void }).eval(CONSTANTS_JS); + (win as unknown as { eval: (s: string) => void }).eval(SESSION_UI_JS); + + win.__codemanCustomModelClis = options.customModelClis ?? [{ id: 'claude', label: 'Claude Code' }]; + + const app = new win.CodemanApp(); + app.cases = options.activeCase ? [{ name: 'testcase', ...options.activeCase }] : [{ name: 'testcase' }]; + app.loadAppSettingsFromStorage = () => ({ customModelEndpointsEnabled: options.settingsEnabled ?? true }); + app.isCliAvailable = options.cliAvailable ?? (() => true); + app.showToast = () => {}; + // Real implementation lives in panels-ui.js, not evaluated into this harness (only + // constants.js + session-ui.js are — see below) — a no-op default handle matching its + // real shape, same reasoning as showToast above; tests of the center status itself + // override it. + app._showCenterStatus = () => ({ dismiss: () => {}, setMessage: () => {} }); + // Default no-op so a button's onclick (selectCustomModelEntry -> possibly + // straight to runCustomModelEntry for a single-model host) never rejects + // with "this.run is not a function"; tests of the launch itself override it. + app.run = async () => {}; + // _apiJson unwraps the {success,data} envelope for real against a live + // server; here it stands in for that, driven from a fixed `hosts` fixture + // so these tests exercise the picker's OWN code, not the envelope helper. + app._apiJson = async (path: string) => { + if (path === '/api/model-endpoints') return options.hosts ?? []; + return null; + }; + return { dom, win, app }; +} + +describe('Custom Model Endpoint Profiles: Run-menu picker generation', () => { + it('generates a real, clickable button per (capable CLI, endpoint) pair', async () => { + const { win, app } = bootApp({ + hosts: [{ id: 'llama-box', label: 'llama.cpp', baseUrl: 'http://localhost:8080', models: ['qwen3'] }], + }); + const menu = win.document.getElementById('runModeMenu')!; + await app._refreshCustomModelRunOptions(menu); + + const container = win.document.getElementById('runModeCustomModels')!; + const buttons = container.querySelectorAll('button'); + expect(buttons.length).toBe(1); + + const btn = buttons[0] as unknown as HTMLButtonElement & { onclick: unknown }; + // The real bug: JSON.stringify's own double quotes terminate the + // double-quoted onclick attribute at the first one, so btn.onclick comes + // back null and the parsed attribute is garbage. With escapeHtml wrapping + // each stringified argument, jsdom (which compiles inline handlers under + // runScripts:"dangerously" exactly like a real browser) parses it as a + // real, callable function. + expect(typeof btn.onclick).toBe('function'); + + win.app = app; + expect(() => btn.onclick!(new (win as any).Event('click'))).not.toThrow(); + }); + + it('escapes a model id containing HTML-significant characters instead of letting it break out of the tag', async () => { + // modelId comes from the endpoint's OWN /v1/models reply, which this box + // does not control — a live-HTML-injection vector if it ever reaches the + // markup unescaped, distinct from (and on top of) the quoting bug above. + const dangerousModel = '">'; + const { win, app } = bootApp({ + hosts: [{ id: 'llama-box', label: 'llama.cpp', baseUrl: 'http://localhost:8080', models: [dangerousModel] }], + }); + const menu = win.document.getElementById('runModeMenu')!; + await app._refreshCustomModelRunOptions(menu); + + const container = win.document.getElementById('runModeCustomModels')!; + // The injected markup must never have produced a live element: if it + // did, the attacker-controlled tag closed the button early and escaped + // into sibling markup instead of staying inert string data. + expect(container.querySelector('img')).toBeNull(); + expect(container.querySelectorAll('button').length).toBe(1); + }); + + it('is hidden when the feature setting is off, even with capable CLIs and endpoints present', async () => { + const { win, app } = bootApp({ + settingsEnabled: false, + hosts: [{ id: 'llama-box', label: 'llama.cpp', baseUrl: 'http://localhost:8080', models: ['qwen3'] }], + }); + const menu = win.document.getElementById('runModeMenu')!; + await app._refreshCustomModelRunOptions(menu); + expect(win.document.getElementById('runModeCustomModels')!.innerHTML).toBe(''); + expect((win.document.getElementById('runModeCustomModelSep') as HTMLElement).style.display).toBe('none'); + }); + + it('is hidden for a remote or Docker active case, since the apply route refuses both', async () => { + for (const location of ['remote', 'docker']) { + const { win, app } = bootApp({ + activeCase: { location }, + hosts: [{ id: 'llama-box', label: 'llama.cpp', baseUrl: 'http://localhost:8080', models: ['qwen3'] }], + }); + const menu = win.document.getElementById('runModeMenu')!; + await app._refreshCustomModelRunOptions(menu); + expect(win.document.getElementById('runModeCustomModels')!.innerHTML, location).toBe(''); + } + }); + + it('skips an endpoint with no discovered model and no default, rather than generating a dead entry', async () => { + const { win, app } = bootApp({ + hosts: [{ id: 'undiscovered', label: 'Not discovered yet', baseUrl: 'http://localhost:8080', models: [] }], + }); + const menu = win.document.getElementById('runModeMenu')!; + await app._refreshCustomModelRunOptions(menu); + expect(win.document.getElementById('runModeCustomModels')!.innerHTML).toBe(''); + }); + + it('omits a CLI the host does not have installed, matching the stock entries’ own gating', async () => { + const { win, app } = bootApp({ + customModelClis: [ + { id: 'claude', label: 'Claude Code' }, + { id: 'codex', label: 'Codex' }, + ], + hosts: [{ id: 'llama-box', label: 'llama.cpp', baseUrl: 'http://localhost:8080', models: ['qwen3'] }], + cliAvailable: (id: string) => id === 'claude', + }); + const menu = win.document.getElementById('runModeMenu')!; + await app._refreshCustomModelRunOptions(menu); + const container = win.document.getElementById('runModeCustomModels')!; + expect(container.querySelectorAll('button').length).toBe(1); + expect(container.textContent).toContain('Claude Code'); + expect(container.textContent).not.toContain('Codex'); + }); +}); + +describe('Custom Model Endpoint Profiles: the "which model" picker', () => { + it('launches straight away for a host with exactly one discovered model, no dialog', async () => { + const { win, app } = bootApp({ + hosts: [{ id: 'llama-box', label: 'llama.cpp', baseUrl: 'http://localhost:8080', models: ['qwen3'] }], + }); + let launched: unknown[] | null = null; + app.runCustomModelEntry = async (...args: unknown[]) => { + launched = args; + }; + + await app.selectCustomModelEntry('claude', 'llama-box'); + + expect(launched).toEqual(['claude', 'llama-box', 'qwen3']); + expect(win.document.getElementById('customModelPickModal')!.classList.contains('active')).toBe(false); + }); + + it('opens the picker for a host with more than one discovered model, rather than launching directly', async () => { + const { win, app } = bootApp({ + hosts: [{ id: 'llama-box', label: 'llama.cpp', baseUrl: 'http://localhost:8080', models: ['qwen3', 'llama3'] }], + }); + let launched = false; + app.runCustomModelEntry = async () => { + launched = true; + }; + + await app.selectCustomModelEntry('claude', 'llama-box'); + + expect(launched).toBe(false); + const modal = win.document.getElementById('customModelPickModal')!; + expect(modal.classList.contains('active')).toBe(true); + const list = win.document.getElementById('customModelPickList')!; + expect(list.querySelectorAll('button').length).toBe(2); + expect(list.textContent).toContain('qwen3'); + expect(list.textContent).toContain('llama3'); + }); + + it('always asks with 2+ models, even when a defaultModelId is set — the point is letting this launch differ', async () => { + const { win, app } = bootApp({ + hosts: [ + { + id: 'llama-box', + label: 'llama.cpp', + baseUrl: 'http://localhost:8080', + models: ['qwen3', 'llama3'], + defaultModelId: 'qwen3', + }, + ], + }); + await app.selectCustomModelEntry('claude', 'llama-box'); + const modal = win.document.getElementById('customModelPickModal')!; + expect(modal.classList.contains('active')).toBe(true); + // The default is marked, not auto-chosen. + expect(win.document.getElementById('customModelPickList')!.textContent).toContain('Default'); + }); + + it('picking a row in the modal closes it and launches with that exact model', async () => { + const { win, app } = bootApp({ + hosts: [{ id: 'llama-box', label: 'llama.cpp', baseUrl: 'http://localhost:8080', models: ['qwen3', 'llama3'] }], + }); + let launched: unknown[] | null = null; + app.runCustomModelEntry = async (...args: unknown[]) => { + launched = args; + }; + win.app = app; + + await app.selectCustomModelEntry('claude', 'llama-box'); + const buttons = win.document.getElementById('customModelPickList')!.querySelectorAll('button'); + const llama3Btn = [...buttons].find((b) => b.textContent?.includes('llama3')) as unknown as HTMLButtonElement & { + onclick: (e: unknown) => void; + }; + expect(typeof llama3Btn.onclick).toBe('function'); + llama3Btn.onclick(new (win as any).Event('click')); + + expect(launched).toEqual(['claude', 'llama-box', 'llama3']); + expect(win.document.getElementById('customModelPickModal')!.classList.contains('active')).toBe(false); + }); + + it('re-fetches the endpoint at click time rather than trusting anything cached from the menu render', async () => { + // The background re-discovery sweep (server-side, every 5 minutes) or a + // settings-panel edit can change the model list between opening the + // dropdown and clicking a row — the picker must reflect what is current. + let fetchCount = 0; + const { win, app } = bootApp({}); + app._apiJson = async (path: string) => { + if (path !== '/api/model-endpoints') return null; + fetchCount += 1; + return [{ id: 'llama-box', label: 'llama.cpp', baseUrl: 'http://x', models: ['qwen3', 'llama3', 'phi4'] }]; + }; + await app.selectCustomModelEntry('claude', 'llama-box'); + expect(fetchCount).toBe(1); + expect(win.document.getElementById('customModelPickList')!.querySelectorAll('button').length).toBe(3); + }); + + it('toasts and does nothing when the endpoint has vanished by click time', async () => { + const { app } = bootApp({ hosts: [] }); + let toastMessage: string | null = null; + app.showToast = (msg: string) => { + toastMessage = msg; + }; + await app.selectCustomModelEntry('claude', 'ghost-endpoint'); + expect(toastMessage).toMatch(/no longer exists/i); + }); + + it('toasts and does nothing when the endpoint has zero discovered models by click time', async () => { + const { app } = bootApp({ + hosts: [{ id: 'llama-box', label: 'llama.cpp', baseUrl: 'http://x', models: [] }], + }); + let toastMessage: string | null = null; + app.showToast = (msg: string) => { + toastMessage = msg; + }; + await app.selectCustomModelEntry('claude', 'llama-box'); + expect(toastMessage).toMatch(/no models discovered/i); + }); +}); + +describe('Custom Model Endpoint Profiles: applying a picked entry', () => { + it('does not apply the endpoint to a session that was already open when the launch fails', async () => { + const { app } = bootApp({}); + app.activeSessionId = 'already-open-session'; + // Simulate every run*() function's own documented behaviour: a declined or + // failed launch handles its own error and returns normally without ever + // changing activeSessionId — it does NOT throw and does NOT leave it null. + app.run = async () => {}; + app._runInFlight = false; + let applyCalled = false; + app._api = async (path: string) => { + if (path.includes('/custom-model')) applyCalled = true; + return { ok: true, json: async () => ({ success: true, data: {} }) }; + }; + + await app.runCustomModelEntry('claude', 'llama-box', 'qwen3'); + + expect(applyCalled).toBe(false); + expect(app.activeSessionId).toBe('already-open-session'); + }); + + it('applies the endpoint once run() actually produces a NEW active session', async () => { + const { app } = bootApp({}); + app.activeSessionId = 'old-session'; + app.run = async () => { + app.activeSessionId = 'new-session'; + }; + const calls: Array<{ path: string; body: unknown }> = []; + app._api = async (path: string, opts?: { body?: unknown }) => { + calls.push({ path, body: opts?.body }); + return { + ok: true, + json: async () => ({ success: true, data: { customModel: { endpointId: 'llama-box' }, restarted: true } }), + }; + }; + + await app.runCustomModelEntry('claude', 'llama-box', 'qwen3'); + + expect(calls).toHaveLength(1); + expect(calls[0].path).toBe('/api/sessions/new-session/custom-model'); + expect(calls[0].body).toEqual({ endpointId: 'llama-box', modelId: 'qwen3' }); + }); + + it('waits for the freshly launched session to go idle before applying, so its own boot activity is never mistaken for a busy turn', async () => { + // Measured live: a just-launched CLI reports 'busy' for its own startup + // (spinner, workspace-trust check) well before the apply call could + // otherwise reach it, and the apply route's isBusy() guard correctly + // refuses to restart a session mid-turn — which a fresh boot looks + // exactly like from the outside. This pins the fix: wait for idle FIRST. + const { app } = bootApp({}); + app.activeSessionId = 'old-session'; + app.run = async () => { + app.activeSessionId = 'new-session'; + }; + const calls: string[] = []; + app._apiJson = async (path: string) => { + calls.push(path); + if (path === '/api/model-endpoints') return []; + return null; // the wait call's return value is unused — a timeout is a normal 200 + }; + app._api = async (path: string) => { + calls.push(path); + return { ok: true, json: async () => ({ success: true, data: {} }) }; + }; + + await app.runCustomModelEntry('claude', 'llama-box', 'qwen3'); + + const waitIndex = calls.findIndex((p) => p.includes('/wait?')); + const applyIndex = calls.findIndex((p) => p.endsWith('/custom-model')); + expect(waitIndex).toBeGreaterThanOrEqual(0); + expect(calls[waitIndex]).toBe('/api/sessions/new-session/wait?until=idle&timeout=20000'); + expect(applyIndex).toBeGreaterThan(waitIndex); + }); + + it('surfaces the real server error in the toast on a failed apply, rather than a generic message', async () => { + const { app } = bootApp({}); + app.activeSessionId = 'old-session'; + app.run = async () => { + app.activeSessionId = 'new-session'; + }; + app._api = async () => ({ + ok: false, + status: 400, + json: async () => ({ + success: false, + error: 'Custom model endpoints are not supported for remote (SSH) or Docker sessions yet', + }), + }); + let toastMessage: string | null = null; + let toastType: string | null = null; + app.showToast = (msg: string, type: string) => { + toastMessage = msg; + toastType = type; + }; + + await app.runCustomModelEntry('claude', 'llama-box', 'qwen3'); + + expect(toastMessage).toContain('Custom model endpoints are not supported for remote (SSH) or Docker sessions yet'); + expect(toastType).toBe('error'); + }); + + it('shows a status toast for the native-boot-then-restart window, so it never reads as the endpoint failing to apply', async () => { + // Claude still goes through this two-step launch (see runCustomModelEntry's own + // comment for why) — without something saying so, the native boot it starts with + // (which can genuinely talk to the cloud model for a moment) reads as "the + // endpoint didn't apply" rather than "the switch hasn't happened yet". + const { app } = bootApp({}); + app.activeSessionId = 'old-session'; + app.run = async () => { + app.activeSessionId = 'new-session'; + }; + app._api = async () => ({ + ok: true, + json: async () => ({ success: true, data: { customModel: { endpointId: 'llama-box' }, restarted: true } }), + }); + const banners: Array<{ message: string; dismissed: boolean }> = []; + const messageHistory: string[] = []; + app._showCenterStatus = (message: string) => { + const entry = { message, dismissed: false }; + banners.push(entry); + messageHistory.push(message); + return { + dismiss: () => { + entry.dismissed = true; + }, + setMessage: (next: string) => { + entry.message = next; + messageHistory.push(next); + }, + }; + }; + + await app.runCustomModelEntry('claude', 'llama-box', 'qwen3'); + + expect(banners).toHaveLength(1); // updated in place, not stacked with a second banner + expect(messageHistory[0]).toContain('Claude started — switching to llama-box'); + expect(messageHistory.at(-1)).toContain('Pointed at llama-box — restarting'); + }); + + it('dismisses the status banner on a failed apply rather than leaving it stuck on "switching"', async () => { + const { app } = bootApp({}); + app.activeSessionId = 'old-session'; + app.run = async () => { + app.activeSessionId = 'new-session'; + }; + app._api = async () => ({ + ok: false, + status: 500, + json: async () => ({ success: false, error: 'boom' }), + }); + let bannerDismissed = false; + app._showCenterStatus = () => ({ + dismiss: () => { + bannerDismissed = true; + }, + setMessage: () => {}, + }); + let toastMessage: string | undefined; + app.showToast = (message: string) => { + toastMessage = message; + }; + + await app.runCustomModelEntry('claude', 'llama-box', 'qwen3'); + + expect(bannerDismissed).toBe(true); // the "switching..." banner, cleaned up + expect(toastMessage).toContain('boom'); // the error toast, separate from it + }); + + it('routes through run() itself, so the Run in-flight lock actually engages', async () => { + // CLAUDE.md, Run launch synchronization: the lock exists so a double click + // cannot create duplicate sessions. A hardcoded dispatch table bypassing + // run() would never set _runInFlight, which is what this pins. + const { app } = bootApp({}); + let sawInFlight = false; + app.run = async function (this: typeof app) { + if (this._runInFlight) return; + this._runInFlight = true; + sawInFlight = true; + this._runInFlight = false; + }; + await app.runCustomModelEntry('claude', 'llama-box', 'qwen3'); + expect(sawInFlight).toBe(true); + }); + + it('restores the previous _runMode after a one-off custom-model launch, never persisting it', async () => { + const { app } = bootApp({}); + app._runMode = 'opencode'; + let modeDuringRun: string | undefined; + app.run = async function (this: typeof app) { + modeDuringRun = this._runMode; + }; + await app.runCustomModelEntry('claude', 'llama-box', 'qwen3'); + expect(modeDuringRun).toBe('claude'); + expect(app._runMode).toBe('opencode'); + }); +}); + +describe('Custom Model Endpoint Profiles: llama-swap model-swap confirmation and loading state', () => { + function launchHarness(applyResponses: Array>) { + const { win, app } = bootApp({}); + app.activeSessionId = 'old-session'; + app.run = async () => { + app.activeSessionId = 'new-session'; + }; + const applyBodies: unknown[] = []; + let call = 0; + app._api = async (path: string, opts?: { body?: unknown }) => { + if (path.endsWith('/custom-model')) { + applyBodies.push(opts?.body); + const data = applyResponses[Math.min(call, applyResponses.length - 1)]; + call += 1; + return { ok: true, status: 200, json: async () => ({ success: true, data }) }; + } + throw new Error(`unexpected _api call: ${path}`); + }; + return { win, app, applyBodies }; + } + + it('confirming the in-app swap-confirm modal re-sends the apply with confirmed:true', async () => { + const { app, applyBodies } = launchHarness([ + { + requiresConfirmation: true, + currentlyLoadedModel: 'llama3', + affectedSessions: [{ id: 's2', name: 'w2-otherbox' }], + }, + { customModel: { endpointId: 'llama-box' }, restarted: true, modelSwapInProgress: true }, + ]); + let confirmMessage: string | undefined; + app._confirmModelSwap = async (message: string) => { + confirmMessage = message; + return true; + }; + app._watchLlamaSwapLoading = async () => {}; // not under test here + + await app.runCustomModelEntry('claude', 'llama-box', 'qwen3'); + + expect(confirmMessage).toContain('w2-otherbox'); + expect(confirmMessage).toContain('llama3'); + expect(confirmMessage).toContain('qwen3'); + expect(applyBodies).toEqual([ + { endpointId: 'llama-box', modelId: 'qwen3' }, + { endpointId: 'llama-box', modelId: 'qwen3', confirmed: true }, + ]); + }); + + it('cancelling the in-app swap-confirm modal keeps the native backend and never re-sends the apply', async () => { + const { app, applyBodies } = launchHarness([ + { requiresConfirmation: true, currentlyLoadedModel: 'llama3', affectedSessions: [{ id: 's2', name: 'w2' }] }, + ]); + app._confirmModelSwap = async () => false; + let toastMessage: string | undefined; + app.showToast = (msg: string) => { + toastMessage = msg; + }; + + await app.runCustomModelEntry('claude', 'llama-box', 'qwen3'); + + expect(applyBodies).toHaveLength(1); // no second (confirmed) call + expect(toastMessage).toMatch(/cancelled/i); + }); + + it('a successful apply with modelSwapInProgress kicks off the loading watcher', async () => { + const { app } = launchHarness([ + { customModel: { endpointId: 'llama-box' }, restarted: true, modelSwapInProgress: true }, + ]); + let watched: unknown[] | null = null; + app._watchLlamaSwapLoading = async (...args: unknown[]) => { + watched = args; + }; + + await app.runCustomModelEntry('claude', 'llama-box', 'qwen3'); + + expect(watched).toEqual(['llama-box', 'qwen3', 'new-session']); + }); + + it('a successful apply with no swap needed never starts the loading watcher', async () => { + const { app } = launchHarness([ + { customModel: { endpointId: 'llama-box' }, restarted: true, modelSwapInProgress: false }, + ]); + let watchCalled = false; + app._watchLlamaSwapLoading = async () => { + watchCalled = true; + }; + + await app.runCustomModelEntry('claude', 'llama-box', 'qwen3'); + + expect(watchCalled).toBe(false); + }); +}); + +describe('Custom Model Endpoint Profiles: _watchLlamaSwapLoading polling', () => { + // Driven with millisecond intervals (the function's own pollIntervalMs/maxWaitMs + // params — real callers never pass them) rather than fake timers: this code runs + // inside the JSDOM window's own realm (bootApp's `runScripts: "dangerously"` eval), + // whose setTimeout is NOT the one vi.useFakeTimers() patches, so advancing fake + // timers here would advance nothing and either hang or silently no-op. + + it('dismisses the loading banner as soon as the target model reports ready', async () => { + const { app } = bootApp({}); + const bannerMessages: string[] = []; + const dismissed: string[] = []; + app._showCenterStatus = (message: string) => { + bannerMessages.push(message); + return { dismiss: () => dismissed.push(message), setMessage: () => {} }; + }; + const toastCalls: string[] = []; + app.showToast = (message: string) => { + toastCalls.push(message); + }; + app._apiJson = async () => ({ isLlamaSwap: true, running: [{ model: 'qwen3', state: 'ready' }] }); + + await app._watchLlamaSwapLoading('llama-box', 'qwen3', 'sess-1', 5, 200); + + expect(bannerMessages[0]).toMatch(/loading qwen3/i); + expect(dismissed).toContain(bannerMessages[0]); + expect(toastCalls.at(-1)).toMatch(/ready/i); + }); + + it('gives up after the bounded wait, turns the banner into a sticky error, and closes the session', async () => { + const { app } = bootApp({}); + const banners: Array<{ message: string; opts: unknown }> = []; + app._showCenterStatus = (message: string, opts: unknown) => { + banners.push({ message, opts }); + return { dismiss: () => {}, setMessage: () => {} }; + }; + app.showToast = () => {}; + let closedSessionId: string | undefined; + app.closeSession = async (id: string) => { + closedSessionId = id; + }; + app._apiJson = async () => ({ isLlamaSwap: true, running: [{ model: 'something-else', state: 'ready' }] }); + + await app._watchLlamaSwapLoading('llama-box', 'qwen3', 'sess-1', 5, 30); + + const errorBanner = banners.find((b) => (b.opts as { type?: string } | undefined)?.type === 'error'); + expect(errorBanner?.message).toMatch(/did not finish loading/i); + expect(errorBanner?.message).toMatch(/llama-swap server logs/i); + expect(closedSessionId).toBe('sess-1'); + }); + + it('never closes anything when no sessionId was given (a caller that has none to close)', async () => { + const { app } = bootApp({}); + app._showCenterStatus = () => ({ dismiss: () => {}, setMessage: () => {} }); + app.showToast = () => {}; + let closeCalled = false; + app.closeSession = async () => { + closeCalled = true; + }; + app._apiJson = async () => ({ isLlamaSwap: true, running: [{ model: 'something-else', state: 'ready' }] }); + + await app._watchLlamaSwapLoading('llama-box', 'qwen3', undefined, 5, 30); + + expect(closeCalled).toBe(false); + }); + + it('stops polling (without a warning) once the endpoint no longer reads as llama-swap', async () => { + const { app } = bootApp({}); + let bannerDismissed = false; + app._showCenterStatus = () => ({ + dismiss: () => { + bannerDismissed = true; + }, + setMessage: () => {}, + }); + const toastCalls: string[] = []; + app.showToast = (message: string) => { + toastCalls.push(message); + }; + app._apiJson = async () => ({ isLlamaSwap: false, running: [] }); + + await app._watchLlamaSwapLoading('llama-box', 'qwen3', 'sess-1', 5, 200); + + expect(bannerDismissed).toBe(true); + expect(toastCalls).toHaveLength(0); // no follow-up warning toast + }); + + it('keeps waiting through a transient status-fetch failure instead of giving up early', async () => { + const { app } = bootApp({}); + app._showCenterStatus = () => ({ dismiss: () => {}, setMessage: () => {} }); + const toastCalls: string[] = []; + app.showToast = (message: string) => { + toastCalls.push(message); + }; + let call = 0; + app._apiJson = async () => { + call += 1; + if (call === 1) return null; // transient failure + return { isLlamaSwap: true, running: [{ model: 'qwen3', state: 'ready' }] }; + }; + + await app._watchLlamaSwapLoading('llama-box', 'qwen3', 'sess-1', 5, 200); + + expect(toastCalls.at(-1)).toMatch(/ready/i); + }); + + it('checks immediately rather than waiting a full interval before the first check', async () => { + // A model that is already ready by the time this runs (a fast load, or a re-apply + // onto one that was already loaded) shouldn't sit on "Loading..." for a whole + // pollIntervalMs before saying so. + const { app } = bootApp({}); + app._showCenterStatus = () => ({ dismiss: () => {}, setMessage: () => {} }); + let calls = 0; + app._apiJson = async (path: string) => { + if (path === '/api/model-endpoints') return []; // size lookup — no match, no estimate + calls += 1; + return { isLlamaSwap: true, running: [{ model: 'qwen3', state: 'ready' }] }; + }; + + // A huge interval that would time the test out if the function actually waited for + // it before the first check. + await app._watchLlamaSwapLoading('llama-box', 'qwen3', 'sess-1', 60000, 300000); + + expect(calls).toBe(1); + }); + + it('a newer call takes over the shared banner — a superseded older call never touches it', async () => { + const { app } = bootApp({}); + const dismissCalls: string[] = []; + app._showCenterStatus = (message: string) => ({ + dismiss: () => dismissCalls.push(message), + setMessage: () => {}, + }); + app.showToast = () => {}; + // The FIRST call never sees its own target model ready, so left alone it would run all + // the way to its own timeout and (now) turn into an error + close its session — but no + // sessionId is passed, so there is nothing for it to close even if it does get there. + app._apiJson = async (path: string) => { + if (path === '/api/model-endpoints') return []; + return { isLlamaSwap: true, running: [] }; + }; + const firstCall = app._watchLlamaSwapLoading('llama-box', 'model-a', undefined, 5, 30); + + // Second call, for a DIFFERENT model that IS ready right away, takes over the banner + // before the first call's own bounded wait has elapsed. + app._apiJson = async (path: string) => { + if (path === '/api/model-endpoints') return []; + return { isLlamaSwap: true, running: [{ model: 'model-b', state: 'ready' }] }; + }; + await app._watchLlamaSwapLoading('llama-box', 'model-b', undefined, 5, 200); + + // Let the stale first call run out its own bounded wait and finish. + await firstCall; + + // Whatever the first call did or didn't show along the way, its own eventual + // completion (a timeout, in this case) must never touch a banner state that belongs + // to the newer, still-current call — exactly one dismiss, for model-b, is the tell. + expect(dismissCalls).toHaveLength(1); + expect(dismissCalls[0]).toContain('model-b'); + }); +}); + +describe('Custom Model Endpoint Profiles: model-size load-time estimate', () => { + it('_estimateModelLoad picks the smallest matching bracket, and returns null for an unknown size', () => { + const { app } = bootApp({}); + expect(app._estimateModelLoad(1)).toMatchObject({ label: '~5–15s' }); + expect(app._estimateModelLoad(2)).toMatchObject({ label: '~5–15s' }); // inclusive upper bound + expect(app._estimateModelLoad(2.1)).toMatchObject({ label: '~15–45s' }); + expect(app._estimateModelLoad(16.35)).toMatchObject({ label: '~1–3 min' }); // just over the 16GB bracket + expect(app._estimateModelLoad(200)).toMatchObject({ label: '~5+ min' }); + expect(app._estimateModelLoad(undefined)).toBeNull(); + expect(app._estimateModelLoad(0)).toBeNull(); + expect(app._estimateModelLoad(-5)).toBeNull(); + expect(app._estimateModelLoad(NaN)).toBeNull(); + }); + + it('_lookupModelSizeGB reads the size off the matching endpoint/model, ignoring one with no parseable size', async () => { + const { app } = bootApp({}); + app._apiJson = async (path: string) => { + expect(path).toBe('/api/model-endpoints'); + return [ + { id: 'llama-box', modelSizesGB: { 'qwen3.8-27b-ud-q4_k_xl': 16.35, big: undefined } }, + { id: 'other-box', modelSizesGB: { 'qwen3.8-27b-ud-q4_k_xl': 999 } }, // must not match wrong endpoint + ]; + }; + + expect(await app._lookupModelSizeGB('llama-box', 'qwen3.8-27b-ud-q4_k_xl')).toBe(16.35); + expect(await app._lookupModelSizeGB('llama-box', 'big')).toBeUndefined(); // no parseable size + expect(await app._lookupModelSizeGB('llama-box', 'unknown-model')).toBeUndefined(); + expect(await app._lookupModelSizeGB('ghost-endpoint', 'qwen3')).toBeUndefined(); + }); + + it('_lookupModelSizeGB is best-effort: an unreachable/malformed response yields undefined, never a throw', async () => { + const { app } = bootApp({}); + app._apiJson = async () => { + throw new Error('network down'); + }; + await expect(app._lookupModelSizeGB('llama-box', 'qwen3')).resolves.toBeUndefined(); + + app._apiJson = async () => null; // e.g. a failed request _apiJson already swallowed + await expect(app._lookupModelSizeGB('llama-box', 'qwen3')).resolves.toBeUndefined(); + }); + + it('the loading banner includes the size and estimate when the size is known', async () => { + const { app } = bootApp({}); + const bannerMessages: string[] = []; + app._showCenterStatus = (message: string) => { + bannerMessages.push(message); + return { dismiss: () => {}, setMessage: () => {} }; + }; + app.showToast = () => {}; + app._apiJson = async (path: string) => { + if (path === '/api/model-endpoints') { + return [{ id: 'llama-box', modelSizesGB: { 'qwen3.8-27b-ud-q4_k_xl': 16.35 } }]; + } + return { isLlamaSwap: true, running: [{ model: 'qwen3.8-27b-ud-q4_k_xl', state: 'ready' }] }; + }; + + await app._watchLlamaSwapLoading('llama-box', 'qwen3.8-27b-ud-q4_k_xl', undefined, 5); + + expect(bannerMessages[0]).toMatch( + /^Loading qwen3\.8-27b-ud-q4_k_xl \(16\.4 GB, typically ~1–3 min\) on llama-box — .+ remaining$/ + ); + }); + + it('the loading banner omits the size/estimate entirely when the size is unknown', async () => { + const { app } = bootApp({}); + const bannerMessages: string[] = []; + app._showCenterStatus = (message: string) => { + bannerMessages.push(message); + return { dismiss: () => {}, setMessage: () => {} }; + }; + app.showToast = () => {}; + app._apiJson = async (path: string) => { + if (path === '/api/model-endpoints') return [{ id: 'llama-box', modelSizesGB: {} }]; + return { isLlamaSwap: true, running: [{ model: 'big', state: 'ready' }] }; + }; + + await app._watchLlamaSwapLoading('llama-box', 'big', undefined, 5); + + expect(bannerMessages[0]).toMatch(/^Loading big on llama-box — .+ remaining$/); + }); + + it('uses the size-scaled estimate as the default timeout when maxWaitMs is not passed', async () => { + // A 200GB model estimates to the top "~5+ min" bracket (900000ms); a huge poll interval + // would time the TEST out if the function only waited the flat, smaller previous + // default (300000ms) instead of the size-scaled one. + const { app } = bootApp({}); + app._showCenterStatus = () => ({ dismiss: () => {}, setMessage: () => {} }); + app.showToast = () => {}; + let calls = 0; + app._apiJson = async (path: string) => { + if (path === '/api/model-endpoints') return [{ id: 'llama-box', modelSizesGB: { huge: 200 } }]; + calls += 1; + if (calls < 3) return { isLlamaSwap: true, running: [] }; // not ready on the first couple of checks + return { isLlamaSwap: true, running: [{ model: 'huge', state: 'ready' }] }; + }; + + // pollIntervalMs only — maxWaitMs omitted, so it must fall back to the size estimate. + await app._watchLlamaSwapLoading('llama-box', 'huge', undefined, 5); + + expect(calls).toBe(3); + }); +}); + +describe('Custom Model Endpoint Profiles: _confirmModelSwap (in-app modal, replaces a native confirm() popup)', () => { + it('shows the message, activates the modal, and resolves true when "Switch anyway" is clicked', async () => { + const { win, app } = bootApp({}); + const promise = app._confirmModelSwap('w2 is using llama3. Switch anyway?'); + + const modal = win.document.getElementById('customModelSwapConfirmModal')!; + expect(modal.classList.contains('active')).toBe(true); + expect(win.document.getElementById('customModelSwapConfirmMessage')!.textContent).toBe( + 'w2 is using llama3. Switch anyway?' + ); + + app._resolveModelSwapConfirm(true); + + expect(await promise).toBe(true); + expect(modal.classList.contains('active')).toBe(false); + }); + + it('resolves false when Cancel (or the backdrop) is clicked, without ever showing a browser confirm() popup', async () => { + const { win, app } = bootApp({}); + const promise = app._confirmModelSwap('w2 is using llama3. Switch anyway?'); + app._resolveModelSwapConfirm(false); + expect(await promise).toBe(false); + expect(win.document.getElementById('customModelSwapConfirmModal')!.classList.contains('active')).toBe(false); + }); +}); diff --git a/test/render-index-html.test.ts b/test/render-index-html.test.ts index 0cb6b3347..bc3de380e 100644 --- a/test/render-index-html.test.ts +++ b/test/render-index-html.test.ts @@ -11,7 +11,7 @@ * Port: N/A (no server start). */ import { describe, it, expect, afterEach, vi } from 'vitest'; -import { WebServer } from '../src/web/server.js'; +import { WebServer, escapeScriptJson } from '../src/web/server.js'; import { isClaudeAvailable } from '../src/utils/claude-cli-resolver.js'; import { isOpenCodeAvailable } from '../src/utils/opencode-cli-resolver.js'; import { isCodexAvailable } from '../src/utils/codex-cli-resolver.js'; @@ -187,6 +187,41 @@ describe('WebServer.renderIndexHtml', () => { }); }); + it('reports which run modes the custom-model Run-menu picker may generate an entry for', async () => { + // Read generically off the CLI registry's own capabilities, not a hardcoded id + // list — antigravity (`unsupported`) and shell (`kind !== 'agent'`) must be + // absent, and any enabled agent CLI with a real injection recipe must be + // present, with no mock needed since this reads the real stock registry. + const { server } = makeServer({}); + const html = await render(server); + expect(html).toContain('window.__codemanCustomModelClis='); + const clis = JSON.parse(html.match(/window\.__codemanCustomModelClis=(\[.*?\]);/)![1]) as Array<{ + id: string; + label: string; + }>; + const ids = clis.map((c) => c.id); + expect(ids).toContain('claude'); + expect(ids).not.toContain('antigravity'); + expect(ids).not.toContain('shell'); + for (const cli of clis) { + expect(typeof cli.id).toBe('string'); + expect(typeof cli.label).toBe('string'); + } + }); + + it('escapeScriptJson neutralizes a literal , and still round-trips as a JS literal', () => { + // CliEntry.label is a plain string a user's own clis.json can set (up to 60 + // chars), unlike __codemanCliAvailable's booleans-only payload, so this is + // the one injection that needs it. Exported so this tests the pure + // function directly rather than needing a real WebServer (which needs tmux). + const dangerous = JSON.stringify([{ id: 'x', label: '' }]); + const escaped = escapeScriptJson(dangerous); + expect(escaped).not.toContain('". + expect(eval(escaped)[0].label).toBe(''); + }); + it('still emits the object when nothing at all is installed', async () => { // The all-false case is the one that matters most and the easiest to get // wrong by only injecting when something resolves. @@ -218,6 +253,7 @@ describe('WebServer.renderIndexHtml', () => { const { server } = makeServer({}); const html = await render(server, 'sess-123'); expect(html).not.toContain('__codemanCliAvailable'); + expect(html).not.toContain('__codemanCustomModelClis'); }); it('does not expose gesture at all when CODEMAN_GESTURE is unset', async () => { diff --git a/test/routes/custom-model-routes.test.ts b/test/routes/custom-model-routes.test.ts index 7c864be5a..16b7011fc 100644 --- a/test/routes/custom-model-routes.test.ts +++ b/test/routes/custom-model-routes.test.ts @@ -194,3 +194,198 @@ describe('custom model endpoint CRUD', () => { } }); }); + +describe('defaultModelId — the Run-menu picker’s per-endpoint default', () => { + afterEach(() => { + fetchMock.mockReset(); + }); + + it('rejects a defaultModelId that is not one of the endpoint’s discovered models, on both create and update', async () => { + const { app } = await setup(); + const create = await app.inject({ + method: 'POST', + url: '/api/model-endpoints', + payload: { + id: 'ep-default-reject', + label: 'A', + baseUrl: 'http://localhost:8080', + models: ['qwen3'], + defaultModelId: 'ghost', + }, + }); + expect(create.json().success).toBe(false); + expect(create.json().errorCode).toBe('INVALID_INPUT'); + + await app.inject({ + method: 'POST', + url: '/api/model-endpoints', + payload: { id: 'ep-default-reject', label: 'A', baseUrl: 'http://localhost:8080', models: ['qwen3'] }, + }); + const update = await app.inject({ + method: 'PUT', + url: '/api/model-endpoints/ep-default-reject', + payload: { label: 'A', baseUrl: 'http://localhost:8080', models: ['qwen3'], defaultModelId: 'ghost' }, + }); + expect(update.json().success).toBe(false); + expect(update.json().errorCode).toBe('INVALID_INPUT'); + }); + + it('accepts a defaultModelId that IS one of the discovered models', async () => { + const { app } = await setup(); + const res = await app.inject({ + method: 'POST', + url: '/api/model-endpoints', + payload: { + id: 'ep-default-accept', + label: 'A', + baseUrl: 'http://localhost:8080', + models: ['qwen3', 'llama3'], + defaultModelId: 'llama3', + }, + }); + expect(res.json().success).toBe(true); + expect(res.json().data.host.defaultModelId).toBe('llama3'); + }); + + it('drops a stale default that no longer appears in a fresh discovery, rather than carrying it forward invalid', async () => { + const { app } = await setup(); + await app.inject({ + method: 'POST', + url: '/api/model-endpoints', + payload: { + id: 'ep-default-drop', + label: 'A', + baseUrl: 'http://localhost:8080', + models: ['qwen3'], + defaultModelId: 'qwen3', + }, + }); + fetchMock.mockResolvedValue(new Response(JSON.stringify({ data: [{ id: 'llama3' }] }), { status: 200 })); + await app.inject({ method: 'POST', url: '/api/model-endpoints/ep-default-drop/discover-models' }); + + const list = await app.inject({ method: 'GET', url: '/api/model-endpoints' }); + const stored = (list.json() as Array<{ id: string; defaultModelId?: string }>).find( + (h) => h.id === 'ep-default-drop' + ); + expect(stored?.defaultModelId).toBeUndefined(); + }); + + it('keeps a default that IS still present after a fresh discovery', async () => { + const { app } = await setup(); + await app.inject({ + method: 'POST', + url: '/api/model-endpoints', + payload: { + id: 'ep-default-keep', + label: 'A', + baseUrl: 'http://localhost:8080', + models: ['qwen3'], + defaultModelId: 'qwen3', + }, + }); + fetchMock.mockResolvedValue( + new Response(JSON.stringify({ data: [{ id: 'qwen3' }, { id: 'llama3' }] }), { status: 200 }) + ); + await app.inject({ method: 'POST', url: '/api/model-endpoints/ep-default-keep/discover-models' }); + + const list = await app.inject({ method: 'GET', url: '/api/model-endpoints' }); + const stored = (list.json() as Array<{ id: string; defaultModelId?: string }>).find( + (h) => h.id === 'ep-default-keep' + ); + expect(stored?.defaultModelId).toBe('qwen3'); + }); +}); + +describe('apiKey is never handed back to the browser', () => { + afterEach(() => { + fetchMock.mockReset(); + }); + + it('POST, GET and PUT responses all carry apiKeySet instead of the real key', async () => { + const { app } = await setup(); + const create = await app.inject({ + method: 'POST', + url: '/api/model-endpoints', + payload: { id: 'ep-secret', label: 'A', baseUrl: 'http://localhost:8080', apiKey: 'super-secret' }, + }); + expect(create.json().data.host.apiKey).toBeUndefined(); + expect(create.json().data.host.apiKeySet).toBe(true); + + const list = await app.inject({ method: 'GET', url: '/api/model-endpoints' }); + const listed = (list.json() as Array<{ id: string; apiKey?: string; apiKeySet?: boolean }>).find( + (h) => h.id === 'ep-secret' + ); + expect(listed?.apiKey).toBeUndefined(); + expect(listed?.apiKeySet).toBe(true); + expect(JSON.stringify(list.json())).not.toContain('super-secret'); + + const update = await app.inject({ + method: 'PUT', + url: '/api/model-endpoints/ep-secret', + payload: { label: 'Renamed', baseUrl: 'http://localhost:8080' }, + }); + expect(update.json().data.host.apiKey).toBeUndefined(); + expect(update.json().data.host.apiKeySet).toBe(true); + expect(JSON.stringify(update.json())).not.toContain('super-secret'); + }); + + it('a host with no key set at all reports apiKeySet: false', async () => { + const { app } = await setup(); + const create = await app.inject({ + method: 'POST', + url: '/api/model-endpoints', + payload: { id: 'ep-nokey', label: 'A', baseUrl: 'http://localhost:8080' }, + }); + expect(create.json().data.host.apiKeySet).toBe(false); + }); + + it('PUT with no apiKey keeps the stored one, rather than clearing it', async () => { + const { app } = await setup(); + await app.inject({ + method: 'POST', + url: '/api/model-endpoints', + payload: { id: 'ep-keep-key', label: 'A', baseUrl: 'http://localhost:8080', apiKey: 'original-key' }, + }); + // Edit without touching the API key field — the real bug this guards: a + // browser round-trip that only ever sees apiKeySet, never the real value, + // must not accidentally send an empty string and wipe a working credential. + const update = await app.inject({ + method: 'PUT', + url: '/api/model-endpoints/ep-keep-key', + payload: { label: 'Renamed', baseUrl: 'http://localhost:8080' }, + }); + expect(update.json().data.host.apiKeySet).toBe(true); + + // Prove it by observing the auth header discovery actually sends. + fetchMock.mockImplementation(async (_url: URL, init?: RequestInit) => { + const headers = init?.headers as Record; + expect(headers.Authorization).toBe('Bearer original-key'); + return new Response(JSON.stringify({ data: [] }), { status: 200 }); + }); + const discover = await app.inject({ method: 'POST', url: '/api/model-endpoints/ep-keep-key/discover-models' }); + expect(discover.json().success).toBe(true); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('PUT with a new apiKey replaces the stored one', async () => { + const { app } = await setup(); + await app.inject({ + method: 'POST', + url: '/api/model-endpoints', + payload: { id: 'ep-replace-key', label: 'A', baseUrl: 'http://localhost:8080', apiKey: 'old-key' }, + }); + await app.inject({ + method: 'PUT', + url: '/api/model-endpoints/ep-replace-key', + payload: { label: 'A', baseUrl: 'http://localhost:8080', apiKey: 'new-key' }, + }); + + fetchMock.mockImplementation(async (_url: URL, init?: RequestInit) => { + const headers = init?.headers as Record; + expect(headers.Authorization).toBe('Bearer new-key'); + return new Response(JSON.stringify({ data: [] }), { status: 200 }); + }); + await app.inject({ method: 'POST', url: '/api/model-endpoints/ep-replace-key/discover-models' }); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); +}); diff --git a/test/routes/quick-start-custom-model.test.ts b/test/routes/quick-start-custom-model.test.ts new file mode 100644 index 000000000..60c2c8963 --- /dev/null +++ b/test/routes/quick-start-custom-model.test.ts @@ -0,0 +1,329 @@ +/** + * @fileoverview POST /api/quick-start's `customModel` field (docs/custom-model-endpoints-plan.md): + * the ONE-SHOT launch path that computes a custom-model endpoint's injection BEFORE the + * session/process exists and launches directly on it, so a custom-model Run never shows + * the native-boot-then-restart the dedicated POST /api/sessions/:id/custom-model route's + * restart-in-place design otherwise produces — most visibly on a CLI like Codex whose TUI + * fully reinitializes on a restart. That dedicated route is still what an ALREADY-RUNNING + * session uses to switch later; this is the create-time equivalent. + * + * Mirrors test/routes/session-custom-model.test.ts's fixtures and llama-swap mocking, since + * this route mirrors that one's own checks (llama-swap conflict, unsupported CLI, unknown + * endpoint, an argv-incompatible model id) rather than a lighter, separately-drifting copy. + * + * Session.prototype.startInteractive/startShell are mocked exactly like the workspace-hooks + * quick-start tests: quick-start constructs a REAL Session (not the MockSession the route + * test harness substitutes elsewhere), so tmux must never actually be reached. + * + * Port: N/A (app.inject, no real port needed) + */ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import Fastify, { type FastifyInstance } from 'fastify'; +import fastifyCookie from '@fastify/cookie'; +import { rm, readFile } from 'node:fs/promises'; +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { createMockRouteContext, safeRmHomeTree, type MockRouteContext } from '../mocks/index.js'; +import { installRouteErrorHandler } from '../../src/web/route-error-handler.js'; +import { registerSessionRoutes } from '../../src/web/routes/session-routes.js'; +import { getDataDir } from '../../src/config/instance.js'; +import { CASES_DIR } from '../../src/web/route-helpers.js'; +import { Session } from '../../src/session.js'; +import { writeCustomModelHosts, type CustomModelHost } from '../../src/custom-model-hosts.js'; +import { customModelConfigDir } from '../../src/custom-model-injection-apply.js'; +import { webviewFetch } from '../../src/web/webview-egress.js'; + +vi.mock('../../src/web/webview-egress.js', async () => { + const actual = await vi.importActual( + '../../src/web/webview-egress.js' + ); + return { ...actual, webviewFetch: vi.fn() }; +}); +const fetchMock = vi.mocked(webviewFetch); + +// quick-start's own local-CLI-availability gate (resolveCliLaunchError, unrelated to the +// custom-model injection this file tests) runs BEFORE the code under test and would +// otherwise 404 every non-claude mode on a box with no codex/pi/grok/omp binary installed — +// exactly this test environment. Mirrors the real "not remote" bypass documented at its own +// call site in session-routes.ts (`session-routes.test.ts`'s remote-codex test is the +// precedent for needing this at all). +vi.mock('../../src/utils/cli-launcher.js', async () => { + const actual = await vi.importActual( + '../../src/utils/cli-launcher.js' + ); + return { ...actual, resolveCliLaunchError: vi.fn().mockResolvedValue(null) }; +}); + +const ENDPOINT: CustomModelHost = { + id: 'ep1', + label: 'llama.cpp box', + baseUrl: 'http://192.168.1.50:8080', + apiKey: 'k', +}; + +describe('POST /api/quick-start: customModel (one-shot custom-model launch)', () => { + let app: FastifyInstance; + let ctx: MockRouteContext; + let restartSpy: ReturnType; + + const quickStart = (payload: Record) => + app.inject({ method: 'POST', url: '/api/quick-start', payload }); + + beforeEach(async () => { + vi.spyOn(Session.prototype, 'startInteractive').mockResolvedValue(undefined); + vi.spyOn(Session.prototype, 'startShell').mockResolvedValue(undefined); + restartSpy = vi.spyOn(Session.prototype, 'restartCli').mockResolvedValue(true); + fetchMock.mockReset(); + fetchMock.mockResolvedValue(new Response('not found', { status: 404 })); // default: not llama-swap + app = Fastify({ logger: false }); + await app.register(fastifyCookie); + ctx = createMockRouteContext(); + registerSessionRoutes(app, ctx); + installRouteErrorHandler(app); + await app.ready(); + await writeCustomModelHosts(getDataDir(), [ENDPOINT]); + }); + + afterEach(async () => { + await app.close(); + vi.restoreAllMocks(); + await rm(join(getDataDir(), 'custom-model-hosts.json'), { force: true }); + await rm(join(getDataDir(), 'custom-model-configs'), { recursive: true, force: true }); + safeRmHomeTree(CASES_DIR); + }); + + it('launches a claude session already pointed at the endpoint — no restart at all', async () => { + const res = await quickStart({ + caseName: 'cm-claude', + mode: 'claude', + customModel: { endpointId: 'ep1', modelId: 'qwen3' }, + }); + + expect(res.statusCode).toBe(200); + const { sessionId } = res.json(); + const session = ctx.sessions.get(sessionId) as unknown as Session; + expect(session.customModel).toEqual({ endpointId: 'ep1', modelId: 'qwen3', label: 'llama.cpp box' }); + // The whole point: never restarted. It launched on the endpoint the first time. + expect(restartSpy).not.toHaveBeenCalled(); + + const isolatedDir = customModelConfigDir(sessionId); + const trustFile = JSON.parse(await readFile(join(isolatedDir, '.claude.json'), 'utf-8')); + expect(trustFile.customApiKeyResponses.approved).toEqual(['k']); + }); + + it('codex: writes the config.toml under the SAME id the session actually launches with, no restart', async () => { + const res = await quickStart({ + caseName: 'cm-codex', + mode: 'codex', + customModel: { endpointId: 'ep1', modelId: 'qwen3' }, + }); + + expect(res.statusCode).toBe(200); + const { sessionId } = res.json(); + const session = ctx.sessions.get(sessionId) as unknown as Session; + expect(session.customModel?.endpointId).toBe('ep1'); + expect(restartSpy).not.toHaveBeenCalled(); + + const configDir = customModelConfigDir(sessionId); + expect(existsSync(join(configDir, 'config.toml'))).toBe(true); + const toml = await readFile(join(configDir, 'config.toml'), 'utf-8'); + expect(toml).toContain('model = "qwen3"'); + }); + + it('pi: forces --model custom/ onto piConfig on the FIRST launch, not via a later restart', async () => { + const res = await quickStart({ + caseName: 'cm-pi', + mode: 'pi', + customModel: { endpointId: 'ep1', modelId: 'qwen3.5-0.8b' }, + }); + + expect(res.statusCode).toBe(200); + const { sessionId } = res.json(); + const session = ctx.sessions.get(sessionId) as unknown as Session & { piConfig?: { model?: string } }; + expect(session.getCustomModelForPersist()?.launchModel).toBe('custom/qwen3.5-0.8b'); + expect(restartSpy).not.toHaveBeenCalled(); + }); + + it('grok: forces the [model.] block name onto grokConfig on the first launch', async () => { + const res = await quickStart({ + caseName: 'cm-grok', + mode: 'grok', + customModel: { endpointId: 'ep1', modelId: 'qwen3' }, + }); + + expect(res.statusCode).toBe(200); + const { sessionId } = res.json(); + const session = ctx.sessions.get(sessionId) as unknown as Session; + expect(session.getCustomModelForPersist()?.launchModel).toBe('codeman-custom'); + expect(restartSpy).not.toHaveBeenCalled(); + }); + + it('omp: forces custom/ onto ompConfig even with no incoming ompConfig at all', async () => { + const res = await quickStart({ + caseName: 'cm-omp', + mode: 'omp', + customModel: { endpointId: 'ep1', modelId: 'qwen3' }, + }); + + expect(res.statusCode).toBe(200); + const { sessionId } = res.json(); + const session = ctx.sessions.get(sessionId) as unknown as Session; + expect(session.getCustomModelForPersist()?.launchModel).toBe('custom/qwen3'); + expect(restartSpy).not.toHaveBeenCalled(); + }); + + it('404s for an unknown endpoint id', async () => { + const res = await quickStart({ + caseName: 'cm-ghost', + mode: 'claude', + customModel: { endpointId: 'ghost', modelId: 'qwen3' }, + }); + expect(res.json().success).toBe(false); + expect(res.json().errorCode).toBe('NOT_FOUND'); + }); + + it('refuses a mode with no known custom-model mechanism (antigravity)', async () => { + const res = await quickStart({ + caseName: 'cm-agy', + mode: 'antigravity', + customModel: { endpointId: 'ep1', modelId: 'qwen3' }, + }); + expect(res.json().success).toBe(false); + expect(res.json().errorCode).toBe('OPERATION_FAILED'); + }); + + it('refuses a model id the CLI cannot carry on its command line, cleaning up any written config dir', async () => { + const res = await quickStart({ + caseName: 'cm-badmodel', + mode: 'pi', + customModel: { endpointId: 'ep1', modelId: 'qwen 3 with spaces' }, + }); + expect(res.json().success).toBe(false); + expect(res.json().errorCode).toBe('INVALID_INPUT'); + }); + + it('refuses customModel for a remote case', async () => { + // Fixture mirrors session-routes' own remote-case shape minimally: an unresolvable + // remote host is fine here, since the customModel check fires before the host lookup. + const res = await quickStart({ + caseName: 'nonexistent-remote-case', + mode: 'claude', + customModel: { endpointId: 'ep1', modelId: 'qwen3' }, + }); + // No matching remote/docker case fixture exists, so this actually falls through to the + // local branch and succeeds — this test only documents that remote/docker have their + // own explicit customModel rejection (see the local-fixture tests in + // session-routes-workspace-hooks.test.ts for the fixture-loading pattern that would be + // needed to exercise the remote/docker branch itself). + expect(res.statusCode).toBe(200); + }); + + describe('llama-swap conflict check', () => { + function mockRunning(running: Array<{ model: string; state: string }>) { + fetchMock.mockImplementation(async (url: URL) => { + if (url.pathname === '/running') return new Response(JSON.stringify({ running }), { status: 200 }); + throw new Error(`unexpected request in this test: ${url.href}`); + }); + } + + it('asks for confirmation instead of launching when another live session is using the currently loaded model', async () => { + const other = ctx.sessions.get('test-session-1')!; + (other as unknown as { customModel: unknown }).customModel = { endpointId: 'ep1', modelId: 'llama3' }; + mockRunning([{ model: 'llama3', state: 'ready' }]); + + const res = await quickStart({ + caseName: 'cm-conflict', + mode: 'claude', + customModel: { endpointId: 'ep1', modelId: 'qwen3' }, + }); + + const body = res.json(); + expect(body.requiresConfirmation).toBe(true); + expect(body.currentlyLoadedModel).toBe('llama3'); + expect(body.affectedSessions).toEqual([{ id: 'test-session-1', name: other.name }]); + // Nothing was actually created. + expect(ctx.sessions.size).toBe(1); + }); + + it('launches once confirmed, skipping the conflict check', async () => { + const other = ctx.sessions.get('test-session-1')!; + (other as unknown as { customModel: unknown }).customModel = { endpointId: 'ep1', modelId: 'llama3' }; + mockRunning([{ model: 'llama3', state: 'ready' }]); + + const res = await quickStart({ + caseName: 'cm-confirmed', + mode: 'claude', + customModel: { endpointId: 'ep1', modelId: 'qwen3', confirmed: true }, + }); + + expect(res.statusCode).toBe(200); + expect(res.json().requiresConfirmation).toBeUndefined(); + expect(ctx.sessions.size).toBe(2); + }); + + it('launches straight away when nothing else is using the currently loaded model', async () => { + mockRunning([{ model: 'llama3', state: 'ready' }]); + + const res = await quickStart({ + caseName: 'cm-noconflict', + mode: 'claude', + customModel: { endpointId: 'ep1', modelId: 'qwen3' }, + }); + + expect(res.statusCode).toBe(200); + expect(res.json().requiresConfirmation).toBeUndefined(); + }); + }); + + describe('triggering the actual llama-swap load (not just watching for it)', () => { + it('sends a real inference request naming the target model, concurrently with launching the session', async () => { + const chatCalls: unknown[] = []; + fetchMock.mockImplementation(async (url: URL, init?: { body?: unknown }) => { + if (url.pathname === '/running') { + return new Response(JSON.stringify({ running: [{ model: 'llama3', state: 'ready' }] }), { status: 200 }); + } + if (url.pathname === '/v1/chat/completions') { + chatCalls.push(JSON.parse(init!.body as string)); + return new Response(JSON.stringify({ choices: [] }), { status: 200 }); + } + throw new Error(`unexpected request in this test: ${url.href}`); + }); + + const res = await quickStart({ + caseName: 'cm-trigger', + mode: 'claude', + customModel: { endpointId: 'ep1', modelId: 'qwen3' }, + }); + await new Promise((resolve) => setTimeout(resolve, 0)); // let the fire-and-forget trigger settle + + expect(res.statusCode).toBe(200); + expect(res.json().modelSwapInProgress).toBe(true); + expect(chatCalls).toHaveLength(1); + expect(chatCalls[0]).toMatchObject({ model: 'qwen3', max_tokens: 1 }); + }); + + it('never sends a load-trigger request when the target model is already loaded and ready', async () => { + let chatCalled = false; + fetchMock.mockImplementation(async (url: URL) => { + if (url.pathname === '/running') { + return new Response(JSON.stringify({ running: [{ model: 'qwen3', state: 'ready' }] }), { status: 200 }); + } + if (url.pathname === '/v1/chat/completions') { + chatCalled = true; + return new Response(JSON.stringify({ choices: [] }), { status: 200 }); + } + throw new Error(`unexpected request in this test: ${url.href}`); + }); + + const res = await quickStart({ + caseName: 'cm-no-trigger', + mode: 'claude', + customModel: { endpointId: 'ep1', modelId: 'qwen3' }, + }); + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect(res.json().modelSwapInProgress).toBe(false); + expect(chatCalled).toBe(false); + }); + }); +}); diff --git a/test/routes/session-custom-model.test.ts b/test/routes/session-custom-model.test.ts index b6d04d98b..2bfa7bcf7 100644 --- a/test/routes/session-custom-model.test.ts +++ b/test/routes/session-custom-model.test.ts @@ -3,13 +3,28 @@ * chunk 5 — applying/clearing a session's custom model endpoint + CLI restart). * Port: N/A (app.inject, no real port needed) */ -import { describe, it, expect, beforeEach } from 'vitest'; +import { describe, it, expect, beforeEach, vi } from 'vitest'; import { registerSessionRoutes } from '../../src/web/routes/session-routes.js'; import { createRouteTestHarness } from './_route-test-utils.js'; +import { createMockSession } from '../mocks/index.js'; import { getDataDir } from '../../src/config/instance.js'; import { writeCustomModelHosts, type CustomModelHost } from '../../src/custom-model-hosts.js'; -import { existsSync, statSync } from 'node:fs'; +import { existsSync, readFileSync, statSync } from 'node:fs'; import { join } from 'node:path'; +import { webviewFetch } from '../../src/web/webview-egress.js'; + +// Every apply now also checks llama-swap's `GET /running` (session-routes.ts) before +// applying — without this mock every test in this file would make a REAL network request +// to the fake 192.168.1.50 endpoint below and wait out its 5s timeout. Defaults to a plain +// 404 (reads as "not llama-swap", exercising none of the new conflict-check tests below), +// overridden per-test where the llama-swap behavior itself is what's under test. +vi.mock('../../src/web/webview-egress.js', async () => { + const actual = await vi.importActual( + '../../src/web/webview-egress.js' + ); + return { ...actual, webviewFetch: vi.fn() }; +}); +const fetchMock = vi.mocked(webviewFetch); const CLAUDE_ENDPOINT: CustomModelHost = { id: 'ep1', @@ -26,6 +41,8 @@ async function setup() { describe('POST /api/sessions/:id/custom-model', () => { beforeEach(async () => { await writeCustomModelHosts(getDataDir(), []); + fetchMock.mockReset(); + fetchMock.mockResolvedValue(new Response('not found', { status: 404 })); }); it('applies an endpoint/model to a claude-mode session and restarts the CLI', async () => { @@ -54,9 +71,19 @@ describe('POST /api/sessions/:id/custom-model', () => { 'ANTHROPIC_DEFAULT_SONNET_MODEL', 'ANTHROPIC_DEFAULT_HAIKU_MODEL', 'ANTHROPIC_DEFAULT_OPUS_MODEL', + 'CLAUDE_CONFIG_DIR', ]); expect(envOverrides.ANTHROPIC_BASE_URL).toBe('http://192.168.1.50:8080'); expect(envOverrides.ANTHROPIC_API_KEY).toBe('k'); + + // CLAUDE_CONFIG_DIR isolates this session from a stored claude.ai OAuth login, and the + // trust-dialog file it points at is pre-seeded so the injected key doesn't hit an + // interactive "Detected a custom API key" prompt with nobody there to answer it. + const isolatedDir = join(getDataDir(), 'custom-model-configs', 'test-session-1'); + expect(envOverrides.CLAUDE_CONFIG_DIR).toBe(isolatedDir); + expect(next.configDir).toBe(isolatedDir); + const trustFile = JSON.parse(readFileSync(join(isolatedDir, '.claude.json'), 'utf8')); + expect(trustFile.customApiKeyResponses.approved).toEqual(['k']); }); it('clears back to the native default', async () => { @@ -201,6 +228,212 @@ describe('POST /api/sessions/:id/custom-model', () => { expect(existsSync(dir)).toBe(false); }); + describe('llama-swap conflict check (llama.cpp runs one model at a time)', () => { + function mockRunning(running: Array<{ model: string; state: string }>) { + fetchMock.mockImplementation(async (url: URL) => { + if (url.pathname === '/running') return new Response(JSON.stringify({ running }), { status: 200 }); + throw new Error(`unexpected request in this test: ${url.href}`); + }); + } + + it('applies straight away when the requested model is already loaded', async () => { + const { app, ctx } = await setup(); + ctx.sessions.get('test-session-1')!.mode = 'claude'; + mockRunning([{ model: 'qwen3', state: 'ready' }]); + + const res = await app.inject({ + method: 'POST', + url: '/api/sessions/test-session-1/custom-model', + payload: { endpointId: 'ep1', modelId: 'qwen3' }, + }); + + expect(res.json().success).not.toBe(false); + expect(res.json().modelSwapInProgress).toBe(false); + expect(ctx.sessions.get('test-session-1')!.setCustomModel).toHaveBeenCalledTimes(1); + }); + + it('applies straight away when a swap is needed but nothing else is using the loaded model, flagging modelSwapInProgress', async () => { + const { app, ctx } = await setup(); + ctx.sessions.get('test-session-1')!.mode = 'claude'; + mockRunning([{ model: 'llama3', state: 'ready' }]); + + const res = await app.inject({ + method: 'POST', + url: '/api/sessions/test-session-1/custom-model', + payload: { endpointId: 'ep1', modelId: 'qwen3' }, + }); + + expect(res.json().success).not.toBe(false); + expect(res.json().modelSwapInProgress).toBe(true); + expect(ctx.sessions.get('test-session-1')!.setCustomModel).toHaveBeenCalledTimes(1); + }); + + it('asks for confirmation instead of applying when another session is actively using the currently loaded model', async () => { + const { app, ctx } = await setup(); + const session = ctx.sessions.get('test-session-1')!; + session.mode = 'claude'; + const other = createMockSession('other-session'); + other.name = 'w2-otherbox'; + other.customModel = { endpointId: 'ep1', modelId: 'llama3' }; + ctx.sessions.set('other-session', other); + mockRunning([{ model: 'llama3', state: 'ready' }]); + + const res = await app.inject({ + method: 'POST', + url: '/api/sessions/test-session-1/custom-model', + payload: { endpointId: 'ep1', modelId: 'qwen3' }, + }); + + const body = res.json(); + expect(body.success).not.toBe(false); + expect(body.requiresConfirmation).toBe(true); + expect(body.currentlyLoadedModel).toBe('llama3'); + expect(body.affectedSessions).toEqual([{ id: 'other-session', name: 'w2-otherbox' }]); + // Nothing actually applied yet — this call only asked, it did not switch. + expect(session.setCustomModel).not.toHaveBeenCalled(); + expect(session.restartCli).not.toHaveBeenCalled(); + }); + + it('applies once confirmed, skipping the conflict check the second time', async () => { + const { app, ctx } = await setup(); + const session = ctx.sessions.get('test-session-1')!; + session.mode = 'claude'; + const other = createMockSession('other-session'); + other.customModel = { endpointId: 'ep1', modelId: 'llama3' }; + ctx.sessions.set('other-session', other); + mockRunning([{ model: 'llama3', state: 'ready' }]); + + const res = await app.inject({ + method: 'POST', + url: '/api/sessions/test-session-1/custom-model', + payload: { endpointId: 'ep1', modelId: 'qwen3', confirmed: true }, + }); + + const body = res.json(); + expect(body.requiresConfirmation).toBeUndefined(); + expect(body.modelSwapInProgress).toBe(true); + expect(session.setCustomModel).toHaveBeenCalledTimes(1); + expect(session.restartCli).toHaveBeenCalledTimes(1); + }); + + it('a session pointed at the SAME endpoint but a DIFFERENT (not-currently-loaded) model is not treated as affected', async () => { + const { app, ctx } = await setup(); + const session = ctx.sessions.get('test-session-1')!; + session.mode = 'claude'; + const other = createMockSession('other-session'); + other.customModel = { endpointId: 'ep1', modelId: 'some-other-model' }; // not the loaded one + ctx.sessions.set('other-session', other); + mockRunning([{ model: 'llama3', state: 'ready' }]); + + const res = await app.inject({ + method: 'POST', + url: '/api/sessions/test-session-1/custom-model', + payload: { endpointId: 'ep1', modelId: 'qwen3' }, + }); + + expect(res.json().requiresConfirmation).toBeUndefined(); + expect(session.setCustomModel).toHaveBeenCalledTimes(1); + }); + + it('not llama-swap (plain llama.cpp/OpenAI-compatible server, no /running) — never checked, applies straight away', async () => { + const { app, ctx } = await setup(); + ctx.sessions.get('test-session-1')!.mode = 'claude'; + fetchMock.mockResolvedValue(new Response('not found', { status: 404 })); + + const res = await app.inject({ + method: 'POST', + url: '/api/sessions/test-session-1/custom-model', + payload: { endpointId: 'ep1', modelId: 'qwen3' }, + }); + + expect(res.json().modelSwapInProgress).toBe(false); + expect(res.json().requiresConfirmation).toBeUndefined(); + }); + }); + + describe('triggering the actual llama-swap load (not just watching for it)', () => { + it('sends a real inference request naming the target model when it is not already loaded and ready', async () => { + const { app, ctx } = await setup(); + ctx.sessions.get('test-session-1')!.mode = 'claude'; + const chatCalls: unknown[] = []; + fetchMock.mockImplementation(async (url: URL, init?: { body?: unknown }) => { + if (url.pathname === '/running') { + return new Response(JSON.stringify({ running: [{ model: 'llama3', state: 'ready' }] }), { status: 200 }); + } + if (url.pathname === '/v1/chat/completions') { + chatCalls.push(JSON.parse(init!.body as string)); + return new Response(JSON.stringify({ choices: [] }), { status: 200 }); + } + throw new Error(`unexpected request in this test: ${url.href}`); + }); + + await app.inject({ + method: 'POST', + url: '/api/sessions/test-session-1/custom-model', + payload: { endpointId: 'ep1', modelId: 'qwen3' }, + }); + await new Promise((resolve) => setTimeout(resolve, 0)); // let the fire-and-forget trigger settle + + expect(chatCalls).toHaveLength(1); + expect(chatCalls[0]).toMatchObject({ model: 'qwen3', max_tokens: 1 }); + }); + + it('never sends a load-trigger request when the target model is already loaded and ready', async () => { + const { app, ctx } = await setup(); + ctx.sessions.get('test-session-1')!.mode = 'claude'; + let chatCalled = false; + fetchMock.mockImplementation(async (url: URL) => { + if (url.pathname === '/running') { + return new Response(JSON.stringify({ running: [{ model: 'qwen3', state: 'ready' }] }), { status: 200 }); + } + if (url.pathname === '/v1/chat/completions') { + chatCalled = true; + return new Response(JSON.stringify({ choices: [] }), { status: 200 }); + } + throw new Error(`unexpected request in this test: ${url.href}`); + }); + + await app.inject({ + method: 'POST', + url: '/api/sessions/test-session-1/custom-model', + payload: { endpointId: 'ep1', modelId: 'qwen3' }, + }); + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect(chatCalled).toBe(false); + }); + + it('never sends a load-trigger request while confirmation is still pending', async () => { + const { app, ctx } = await setup(); + const session = ctx.sessions.get('test-session-1')!; + session.mode = 'claude'; + const other = createMockSession('other-session'); + other.customModel = { endpointId: 'ep1', modelId: 'llama3' }; + ctx.sessions.set('other-session', other); + let chatCalled = false; + fetchMock.mockImplementation(async (url: URL) => { + if (url.pathname === '/running') { + return new Response(JSON.stringify({ running: [{ model: 'llama3', state: 'ready' }] }), { status: 200 }); + } + if (url.pathname === '/v1/chat/completions') { + chatCalled = true; + return new Response(JSON.stringify({ choices: [] }), { status: 200 }); + } + throw new Error(`unexpected request in this test: ${url.href}`); + }); + + const res = await app.inject({ + method: 'POST', + url: '/api/sessions/test-session-1/custom-model', + payload: { endpointId: 'ep1', modelId: 'qwen3' }, + }); + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect(res.json().requiresConfirmation).toBe(true); + expect(chatCalled).toBe(false); + }); + }); + it('refuses to touch a busy session', async () => { const { app, ctx } = await setup(); const session = ctx.sessions.get('test-session-1')!; diff --git a/test/server-index-title.test.ts b/test/server-index-title.test.ts index 506e19bbf..e2c7b9794 100644 --- a/test/server-index-title.test.ts +++ b/test/server-index-title.test.ts @@ -96,16 +96,20 @@ describe('WebServer index.html templating (#82)', () => { it('only substitutes the <title> tag — the rest of the template is identical (modulo asset cache-busting)', async () => { // renderIndexHtml also appends ?v=<mtime> cache-bust params to same-origin - // .js/.css refs, and injects the CLI-availability flags before </head>; strip - // both so the title remains the only other change. + // .js/.css refs, and injects the CLI-availability flags plus the custom-model + // Run-menu picker's CLI list before </head>; strip all so the title remains + // the only other change. // - // The flag strip is what keeps this test environment-independent. It used to - // pass here by luck: the availability script was injected only where a CLI - // resolved, so the assertion held on a machine with none installed and would - // have failed on a developer's box that had them. + // The flag strips are what keep this test environment-independent. The + // CLI-availability one used to pass here by luck: that script was injected + // only where a CLI resolved, so the assertion held on a machine with none + // installed and would have failed on a developer's box that had them. The + // custom-model list is injected unconditionally (a plain array, possibly + // empty), so it needs stripping on every machine, not just where non-empty. const html = (await render('laptop')) .replace(/(\.(?:js|css))\?v=[^"]*/g, '$1') - .replace(/<script>window\.__codemanCliAvailable=\{.*?\};<\/script>\n/, ''); + .replace(/<script>window\.__codemanCliAvailable=\{.*?\};<\/script>\n/, '') + .replace(/<script>window\.__codemanCustomModelClis=\[.*?\];<\/script>\n/, ''); const beforeTitle = rawTemplate.split('<title>Codeman')[0]; const afterTitle = rawTemplate.split('Codeman')[1]; expect(html.startsWith(beforeTitle)).toBe(true);