Files
Codeman/test/fixtures/mock-openai-server.ts
T
Codeman maintainer 942bf37e48 fix(custom-model): unset injected env on clear, resume on restart, select the model for pi/omp/grok
Custom Model Endpoint Profiles (#393) let a session point its CLI at a
custom OpenAI-compatible endpoint by injecting env vars or a config file
and restarting the CLI in place. Review of the apply path found four
things, two of them destructive. This lands all four plus the smaller
items from the same review.

1. Clearing a selection did not clear it. The injected vars reach the CLI
   via `tmux setenv`, which persists at the tmux-session level and is
   inherited by `respawn-pane` (measured: `setenv FOO bar` survived two
   successive `respawn-pane -k`), so deleting the keys from the session's
   envOverrides relaunched the CLI still pointed at the old endpoint, and
   for the configDir kinds at a HOME/CODEX_HOME/GROK_HOME that had just
   been deleted. `Session.setCustomModel()` now reports the removed keys,
   queues them (`_pendingEnvUnsets`), and `RespawnPaneOptions.unsetEnvKeys`
   carries them into `applyEnvOverrides()`, which `setenv -u`s them before
   re-applying the live overrides, on the same path that already unsets
   the legacy CLAUDE_CODE_EFFORT_LEVEL. Verified on a private tmux socket
   that `setenv -u HOME` hands the next respawn the global HOME back.

2. Applying a model to a local claude session killed the pane. The
   relaunch was `claude --session-id <id>` and Claude refuses an id that
   already has a transcript, and unlike the dead-pane respawn this one
   kills a working pane first. `restartCli()` now pins the live
   conversation id as the resume id for that respawn when the CLI's launch
   declares a `fallback` chain, which renders the same
   `--resume <id> || --session-id <id>` shape the docker and remote pane
   commands use. Gated on the registry shape, not the CLI id: an entry
   whose resume id is minted by the CLI itself never declares that chain.

3. pi, omp and grok wrote their config file and then launched without the
   `--model` that selects it, so the file was ignored. The registry entry
   now declares `customModelInjection.launchModel` (`custom/{modelId}` for
   pi and omp, grok's `[model.codeman-custom]` block name), the builder
   renders it, and `_withCustomModelLaunchModel()` applies it onto the
   respawn options through `legacyConfigField`, leaving the stored
   <Mode>Config untouched so a clear falls back to the user's own model.
   A model id the CLI's `model` token pattern cannot carry is refused
   with a 400 rather than silently dropped by the argv engine.

4. Remote (SSH) and Docker sessions reported `restarted: true` and changed
   nothing: their `restartCli()` reattaches the durable tmux rather than
   relaunching the agent, and the env lands on the local pane. Both are
   refused with a 400 until those paths are plumbed.

Smaller items from the same review:

- The selection survives a Codeman restart as the disk-only `__customModel`
  bookkeeping (endpoint, model, injected key NAMES, config dir, launch
  model; never the values, which carry the API key). Recovery re-derives
  the values from the endpoint store through the same apply path the route
  uses and keeps the bookkeeping even when the endpoint is gone, so a
  later clear still has keys to unset.
- Discovery goes through `webviewFetch()`, so the RESOLVED address is
  judged by the same egress guard the web-tab proxy uses, and `baseUrl`
  reuses `webviewUrlSchema` (http(s) only, no embedded credentials,
  link-local and cloud-metadata addresses refused). undici's `fetch failed`
  wrapper is unwrapped so the user sees the ECONNREFUSED underneath.
- `custom-model-hosts.json` is written 0600 via tmp+rename, the per-session
  config dir 0700/0600 (pi and omp embed the key literally), and that dir
  is removed with the session.
- `PR.md` is gone from the repo root and the design doc moved to
  `docs/custom-model-endpoints-plan.md` with the LAN address and the
  personal name scrubbed; every reference follows. The guide's `authStyle`
  text matches the shipped schema (`bearer | api-key`, default `bearer`)
  and says that `customModelEndpointsEnabled` is read by nothing until
  the picker lands.
- `config/tsconfig.scripts.json` typechecks `scripts/test-local-llm-harnesses.ts`
  (four real type errors fixed). It is not yet wired into `npm run typecheck`
  because that line differs on master; adding `&& tsc -p config/tsconfig.scripts.json`
  there is the one-line follow-up.

Tests: `test/session-custom-model-restart.test.ts` drives a real Session and
fails on the unfixed code for items 1 to 3; the route suite covers item 4
and the pattern refusal; `test/tmux-manager.test.ts` pins that the unsets
run before the overrides and that a shell-metachar key never reaches tmux.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 23:46:28 +02:00

119 lines
4.0 KiB
TypeScript

/**
* @fileoverview In-process fake OpenAI/Anthropic-compatible HTTP server for the
* Custom Model Endpoint Profiles contract tests (docs/custom-model-endpoints-plan.md chunk 7).
*
* No external deps — plain `node:http`. Captures every request it receives
* (method, path, headers, parsed JSON body) so a test can assert the injected
* base URL / API key / model actually reached the right place, with the right
* auth header, in the shape a real llama.cpp/Azure/etc. endpoint would see it.
*
* Serves the request shapes this feature's recipes produce: OpenAI-style
* `POST /v1/chat/completions` (opencode/pi/grok/omp/gemini's compat
* endpoint), Anthropic-style `POST /v1/messages` (claude's ANTHROPIC_BASE_URL
* traffic), OpenAI's newer `POST /v1/responses` (codex's actual wire protocol
* as of Feb 2026 — it dropped chat-completions support), plus `GET /v1/models`
* for the discovery route's own tests.
*/
import { createServer, type IncomingMessage, type Server } from 'node:http';
import { AddressInfo } from 'node:net';
export interface CapturedRequest {
method: string;
path: string;
headers: Record<string, string | string[] | undefined>;
body: unknown;
}
export interface MockOpenAiServer {
baseUrl: string;
requests: CapturedRequest[];
close(): Promise<void>;
}
function readJsonBody(req: IncomingMessage): Promise<unknown> {
return new Promise((resolve) => {
const chunks: Buffer[] = [];
req.on('data', (c) => chunks.push(c));
req.on('end', () => {
const raw = Buffer.concat(chunks).toString('utf8');
if (!raw) return resolve(undefined);
try {
resolve(JSON.parse(raw));
} catch {
resolve(raw);
}
});
});
}
/** Starts the mock server on a random free port and resolves once it's listening. */
export async function startMockOpenAiServer(): Promise<MockOpenAiServer> {
const requests: CapturedRequest[] = [];
const server: Server = createServer((req, res) => {
void (async () => {
const body = await readJsonBody(req);
const path = (req.url ?? '').split('?')[0];
requests.push({ method: req.method ?? 'GET', path, headers: req.headers, body });
res.setHeader('content-type', 'application/json');
if (path === '/v1/models' && req.method === 'GET') {
res.writeHead(200);
res.end(JSON.stringify({ data: [{ id: 'qwen3' }, { id: 'llama3' }] }));
return;
}
if (path === '/v1/chat/completions' && req.method === 'POST') {
res.writeHead(200);
res.end(
JSON.stringify({
id: 'mock-completion',
choices: [{ index: 0, message: { role: 'assistant', content: 'hello world' } }],
})
);
return;
}
if (path === '/v1/messages' && req.method === 'POST') {
res.writeHead(200);
res.end(
JSON.stringify({
id: 'mock-message',
role: 'assistant',
content: [{ type: 'text', text: 'hello world' }],
})
);
return;
}
// Codex's real wire protocol (verified against a live binary: it dropped
// wire_api="chat" support in Feb 2026, so its config.toml always says
// wire_api="responses") — a different shape from OpenAI's chat-completions.
if (path === '/v1/responses' && req.method === 'POST') {
res.writeHead(200);
res.end(
JSON.stringify({
id: 'mock-response',
output: [{ type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'hello world' }] }],
})
);
return;
}
res.writeHead(404);
res.end(JSON.stringify({ error: 'not found in mock server', path }));
})();
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address() as AddressInfo;
return {
baseUrl: `http://127.0.0.1:${port}`,
requests,
close: () => new Promise<void>((resolve, reject) => server.close((err) => (err ? reject(err) : resolve()))),
};
}