Merge pull request #514 from irisitymichaelgrundberg/feat/claude-session-model

feat(sessions): accept a per-session Claude model on POST /api/sessions
This commit is contained in:
Codeman maintainer
2026-10-04 23:24:43 +02:00
12 changed files with 242 additions and 11 deletions
+13
View File
@@ -55,6 +55,19 @@ describe('claude', () => {
);
});
it('renders a model as the quoted value of --model, even one that opens with a dash', () => {
// POST /api/sessions admits a leading '-' in `model`. It still lands as the option's
// value: quoted here, and Claude's option parser takes the word after `--model` as its
// value whatever it starts with, so it can never become a flag of its own.
expect(claude({ model: 'claude-fable-5-1' })).toBe(
'claude --dangerously-skip-permissions --session-id "0f9c2b14-1111-2222-3333-444455556666" --model "claude-fable-5-1"'
);
expect(claude({ model: '--dangerously-skip-permissions' })).toBe(
'claude --dangerously-skip-permissions --session-id "0f9c2b14-1111-2222-3333-444455556666" ' +
'--model "--dangerously-skip-permissions"'
);
});
it('resumes through a shell fallback to a fresh session', () => {
// The ` || ` is emitted by the ENGINE, not by config — no registry field can hold shell
// text. This pin is what proves the fallback chain still renders as one command line.
@@ -0,0 +1,112 @@
/**
* @fileoverview `model` on POST /api/sessions — a Claude model for one session only.
*
* Claude's model reaches disk only through `modelOverride`, which writes it into the
* case's `.claude/settings.local.json` for every later run there. `model` is the
* per-session counterpart: it goes out as `claude --model <id>`, wins over the app-wide
* default, and writes nothing. What the tests read is the model the session hands the
* mux when it starts, which is what becomes the `--model` flag.
*
* Uses app.inject(), so no real HTTP port is needed.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import Fastify, { type FastifyInstance } from 'fastify';
import fastifyCookie from '@fastify/cookie';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { createMockRouteContext, type MockRouteContext } from '../mocks/index.js';
import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
import { registerSessionRoutes } from '../../src/web/routes/session-routes.js';
interface Harness {
app: FastifyInstance;
ctx: MockRouteContext;
}
async function createHarness(): Promise<Harness> {
const app = Fastify({ logger: false });
await app.register(fastifyCookie);
const ctx = createMockRouteContext();
registerSessionRoutes(app, ctx);
installRouteErrorHandler(app);
await app.ready();
return { app, ctx };
}
describe('POST /api/sessions model', () => {
let workingDir: string;
let harness: Harness;
beforeEach(async () => {
workingDir = await mkdtemp(join(tmpdir(), 'codeman-session-model-'));
harness = await createHarness();
});
afterEach(async () => {
await harness.app.close();
await rm(workingDir, { recursive: true, force: true });
});
/** Creates a session and starts it, then returns the model it handed the mux. */
async function launchedModel(payload: Record<string, unknown>): Promise<unknown> {
const res = await harness.app.inject({ method: 'POST', url: '/api/sessions', payload: { workingDir, ...payload } });
expect(res.statusCode).toBe(200);
const parsed = JSON.parse(res.body);
const id = (parsed.data?.session ?? parsed.session).id as string;
await harness.app.inject({ method: 'POST', url: `/api/sessions/${id}/interactive`, payload: {} });
const calls = harness.ctx.mux.createSession.mock.calls;
expect(calls.length).toBeGreaterThan(0);
return (calls[calls.length - 1][0] as { model?: string }).model;
}
it('launches a Claude session on the model the caller names', async () => {
expect(await launchedModel({ mode: 'claude', model: 'claude-fable-5-1' })).toBe('claude-fable-5-1');
});
it('wins over the app-wide default model', async () => {
harness.ctx.getModelConfig.mockResolvedValue({ defaultModel: 'sonnet' });
expect(await launchedModel({ mode: 'claude', model: 'opus' })).toBe('opus');
});
it('leaves the app-wide default in charge when the caller names none', async () => {
harness.ctx.getModelConfig.mockResolvedValue({ defaultModel: 'sonnet' });
expect(await launchedModel({ mode: 'claude' })).toBe('sonnet');
});
it('launches on `model` while `modelOverride` alone reaches the case file', async () => {
// Sent together, each lands where it belongs: the persistent default in the case's
// settings.local.json, and this session's model on its launch line. A route that wrote
// `model` to disk would put 'opus' in the file; one that ignored it would launch 'sonnet'.
expect(await launchedModel({ mode: 'claude', model: 'opus', modelOverride: 'sonnet' })).toBe('opus');
const settings = JSON.parse(await readFile(join(workingDir, '.claude', 'settings.local.json'), 'utf8'));
expect(settings.model).toBe('sonnet');
});
it('reads an empty model as no model, as modelOverride does', async () => {
harness.ctx.getModelConfig.mockResolvedValue({ defaultModel: 'sonnet' });
expect(await launchedModel({ mode: 'claude', model: '' })).toBe('sonnet');
});
it('refuses a model for a CLI that takes its model in its own config object', async () => {
const res = await harness.app.inject({
method: 'POST',
url: '/api/sessions',
payload: { workingDir, mode: 'codex', model: 'gpt-5' },
});
const parsed = JSON.parse(res.body);
expect(parsed.success).toBe(false);
expect(parsed.errorCode).toBe('INVALID_INPUT');
expect(harness.ctx.sessions.size).toBe(1); // only the session the mock context starts with
});
it('rejects a model with characters the launch pattern refuses', async () => {
const res = await harness.app.inject({
method: 'POST',
url: '/api/sessions',
payload: { workingDir, mode: 'claude', model: 'opus; rm -rf ~' },
});
expect(res.statusCode).toBe(400);
});
});
+71
View File
@@ -0,0 +1,71 @@
/**
* @fileoverview A session's launch model survives recovery.
*
* `Session._model` is what becomes `claude --model <id>`: the caller's per-session `model`
* from POST /api/sessions, or the app-wide default. It lives in memory, so it reaches a
* relaunch after a Codeman restart or a reboot restore only if `toState()` persists it and
* both recovery constructors hand it back. Without that, a recovered session silently
* relaunches on the account default.
*
* `restoreMuxSessions()` (server.ts) cannot be reached under vitest, where
* `reconcileSessions()` reports every pane alive, and the reboot-restore route rejects every
* workspace before building a Session in its route tests. The two constructors are therefore
* pinned by a source check, the same way `test/remote-wake.test.ts` pins its wiring, and the
* round trip itself is driven through a real `Session` against the in-memory tmux layer.
*/
import { mkdirSync, readFileSync, rmSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { Session } from '../src/session.js';
import { TmuxManager } from '../src/tmux-manager.js';
const SRC = fileURLToPath(new URL('../src', import.meta.url));
describe('the launch model survives recovery', () => {
const workingDir = join(homedir(), 'codeman-cases', 'session-model-recovery');
const sessions: Session[] = [];
afterEach(() => {
for (const s of sessions.splice(0)) s.stop();
rmSync(workingDir, { recursive: true, force: true });
});
it('persists the model in the session state', () => {
const session = new Session({ workingDir: '/tmp', mode: 'claude', model: 'claude-fable-5-1' });
sessions.push(session);
expect(session.toState().model).toBe('claude-fable-5-1');
});
it('relaunches a session rebuilt from that state on the same model', async () => {
mkdirSync(workingDir, { recursive: true });
const original = new Session({ workingDir, mode: 'claude', model: 'claude-fable-5-1' });
sessions.push(original);
const state = original.toState();
// Rebuilt the way both recovery paths build one, from the persisted record.
const mux = new TmuxManager();
const createSession = vi.spyOn(mux, 'createSession');
const rebuilt = new Session({
id: state.id,
workingDir,
mode: state.mode,
mux,
useMux: true,
model: state.model,
});
sessions.push(rebuilt);
await rebuilt.startInteractive();
expect(createSession).toHaveBeenCalledWith(expect.objectContaining({ model: 'claude-fable-5-1' }));
});
it('is handed back by both recovery constructors', () => {
const server = readFileSync(join(SRC, 'web', 'server.ts'), 'utf-8');
const reboot = readFileSync(join(SRC, 'web', 'routes', 'reboot-restore-routes.ts'), 'utf-8');
expect(server).toMatch(/model:\s*savedState\?\.model,/);
expect(reboot).toMatch(/model:\s*saved\.model,/);
});
});