mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-18 03:27:08 +00:00
fix(claude): stop locking Claude sessions to three hard-coded model aliases (#1948)
* feat(shared): derive Claude model choices from the CLI catalog The choices are the rows of the claude CLI's own /model picker, in its order and with its display names. The stored value is what claude --model receives: an alias is resolved again each time the session's claude process starts, a full id stays on its model, so following and staying need no new field. Effort support is read per model so a model switch can drop an effort level the next model does not offer. * feat(cli): discover Claude models from the CLI's initialize response A machine RPC starts claude in stream-json mode, sends only an initialize control request and reads the models it reports, so no turn runs and no transcript is written. claude --print runs a directory's project hooks and .mcp.json servers without a trust prompt, so the probe starts from the home directory with user settings only, no MCP servers and hooks disabled. Successful catalogs are cached per claude executable for five minutes and concurrent requests share one probe; failures are not cached. * feat(hub): expose the Claude model catalog per machine GET /machines/:id/claude-models forwards to the runner's listClaudeModels RPC. A runner that predates the handler answers with the stable rpc_target_missing code so clients can keep their built-in list. * feat(web): offer the machine's Claude models in the model pickers The composer and the create-session form list the rows the machine's claude CLI shows in its own /model picker, as it shows them. Built-in presets the catalog does not list remain selectable after it. Until the catalog arrives, or on a runner without discovery, the built-in presets are shown as before. A saved Claude model is no longer reset to Default when the built-in list lacks it; the create-session form keeps it and marks it as no longer listed when the catalog dropped it. * feat(hub,web): keep Claude effort within what the selected model offers For Claude sessions the model endpoint accepts an optional effort, so a model switch and the effort it keeps reach the session as one config change. Other flavors are refused: Pi, for one, commits the model before its thinking level. When the machine's catalog says the next Claude model does not offer the current effort, the composer clears it in that same request. The create-session form drops such an effort however the model was set, including a restored preference or draft. Effort choices in both places narrow to the selected model's levels; without a catalog every level stays available as before. * fix(web): retry Claude model discovery after a failed probe The machine answers a failed probe with success:false over HTTP 200. The query cached that as an answer for its stale time, so a user who signed in and reopened a picker within a minute still saw only the built-in models. A failed probe is now a query error, which is not kept, and the next picker to mount asks the machine again. * fix(web): list only the Claude CLI's models once its catalog is known The built-in presets were kept after the catalog so that a partial list could not hide Opus. The catalog is the CLI's own /model list, though, not a partial one, and the presets added entries the CLI does not show (Sonnet 1M, Opus 1M, Fable 1M). With a catalog the list is now exactly its rows; a saved model it does not list stays as the current model, and New Session marks it as no longer listed. Without a catalog the built-in presets are shown as before. * fix(shared,web): list earlier Claude versions under Other models Claude Code's model sheet shows each family's newest model first and every earlier version under an "Other models" heading. The CLI's catalog lists models in that order but does not say where the split is, so the first row of each family is taken as its newest and later rows of the same family as earlier versions. The composer's model list and New Session's model select now show the same two groups, keeping the CLI order within each. Nothing is folded: every row stays one click away, as it does in Claude Code. * test(web): pin that Claude 1M variants come from the CLI catalog Claude Code 2.1.105, 2.1.200, 2.1.240 and 2.1.274 list a 1M choice as its own catalog row (opus[1m], claude-fable-5[1m]); 2.1.303 and 2.1.310 list none, and on 2.1.310 opus and sonnet run with a 1M context window. The catalog-only list therefore offers a 1M variant exactly when the CLI does. Pin that and record why the built-in [1m] presets are not appended.
This commit is contained in:
@@ -0,0 +1,298 @@
|
||||
import { EventEmitter } from 'node:events'
|
||||
import { homedir } from 'node:os'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { spawnMock, killMock, claudePathMock } = vi.hoisted(() => ({
|
||||
spawnMock: vi.fn(),
|
||||
killMock: vi.fn(),
|
||||
claudePathMock: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('node:child_process', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('node:child_process')>()
|
||||
return { ...actual, spawn: spawnMock }
|
||||
})
|
||||
|
||||
vi.mock('../../utils/process', () => ({
|
||||
killProcessByChildProcess: killMock,
|
||||
}))
|
||||
|
||||
vi.mock('@/claude/sdk/utils', () => ({
|
||||
getDefaultClaudeCodePath: claudePathMock,
|
||||
}))
|
||||
|
||||
import {
|
||||
_resetClaudeModelsCacheForTests,
|
||||
listClaudeModels,
|
||||
parseClaudeModelsProbeLine,
|
||||
} from './claudeModels'
|
||||
|
||||
const PROBE_REQUEST_ID = 'hapi-claude-models-probe'
|
||||
|
||||
class FakeChild extends EventEmitter {
|
||||
stdout = new EventEmitter()
|
||||
stderr = new EventEmitter()
|
||||
stdin = Object.assign(new EventEmitter(), { write: vi.fn() })
|
||||
pid: number | undefined = 4242
|
||||
|
||||
respond(models: unknown): void {
|
||||
this.stdout.emit('data', `${JSON.stringify({
|
||||
type: 'control_response',
|
||||
response: { subtype: 'success', request_id: PROBE_REQUEST_ID, response: { models } },
|
||||
})}\n`)
|
||||
}
|
||||
}
|
||||
|
||||
function successLine(models: unknown, requestId = PROBE_REQUEST_ID): string {
|
||||
return JSON.stringify({
|
||||
type: 'control_response',
|
||||
response: { subtype: 'success', request_id: requestId, response: { models } },
|
||||
})
|
||||
}
|
||||
|
||||
const OPUS_ROW = {
|
||||
value: 'opus',
|
||||
resolvedModel: 'claude-opus-5-5',
|
||||
displayName: 'Opus 5.5',
|
||||
description: 'For complex work',
|
||||
supportsEffort: true,
|
||||
supportedEffortLevels: ['low', 'high'],
|
||||
supportsFastMode: true,
|
||||
}
|
||||
|
||||
let children: FakeChild[]
|
||||
|
||||
function lastChild(): FakeChild {
|
||||
const child = children.at(-1)
|
||||
if (!child) throw new Error('probe was not spawned')
|
||||
return child
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
_resetClaudeModelsCacheForTests()
|
||||
children = []
|
||||
spawnMock.mockReset()
|
||||
spawnMock.mockImplementation(() => {
|
||||
const child = new FakeChild()
|
||||
children.push(child)
|
||||
return child
|
||||
})
|
||||
killMock.mockReset()
|
||||
killMock.mockResolvedValue(true)
|
||||
claudePathMock.mockReset()
|
||||
claudePathMock.mockReturnValue('/usr/local/bin/claude')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('parseClaudeModelsProbeLine', () => {
|
||||
it('keeps only the fields HAPI uses and folds effort support into levels', () => {
|
||||
const result = parseClaudeModelsProbeLine(successLine([
|
||||
OPUS_ROW,
|
||||
{ value: 'haiku', resolvedModel: 'claude-haiku-4-5', displayName: 'Haiku 4.5' },
|
||||
{ value: 'legacy', supportsEffort: null },
|
||||
]))
|
||||
|
||||
expect(result).toEqual({
|
||||
kind: 'models',
|
||||
models: [
|
||||
{ value: 'opus', displayName: 'Opus 5.5', effortLevels: ['low', 'high'] },
|
||||
{ value: 'haiku', displayName: 'Haiku 4.5', effortLevels: [] },
|
||||
{ value: 'legacy', effortLevels: [] },
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
it('leaves effort support unknown when the CLI reports it for no model at all', () => {
|
||||
const result = parseClaudeModelsProbeLine(successLine([
|
||||
{ value: 'opus', resolvedModel: 'claude-opus-5-5' },
|
||||
]))
|
||||
|
||||
expect(result).toEqual({ kind: 'models', models: [{ value: 'opus' }] })
|
||||
})
|
||||
|
||||
it('leaves the levels unknown when the CLI supports effort but lists no levels', () => {
|
||||
const result = parseClaudeModelsProbeLine(successLine([
|
||||
{ value: 'opus', supportsEffort: true },
|
||||
]))
|
||||
|
||||
expect(result).toEqual({ kind: 'models', models: [{ value: 'opus' }] })
|
||||
})
|
||||
|
||||
it('trusts supportsEffort over a level list the row still carries', () => {
|
||||
const result = parseClaudeModelsProbeLine(successLine([
|
||||
{ value: 'haiku', supportsEffort: false, supportedEffortLevels: ['low'] },
|
||||
]))
|
||||
|
||||
expect(result).toEqual({ kind: 'models', models: [{ value: 'haiku', effortLevels: [] }] })
|
||||
})
|
||||
|
||||
it('drops rows without a usable value and non-string fields', () => {
|
||||
const result = parseClaudeModelsProbeLine(successLine([
|
||||
{ value: '' },
|
||||
{ displayName: 'No value' },
|
||||
'opus',
|
||||
{ value: 'sonnet', displayName: 42, supportsEffort: true, supportedEffortLevels: ['low', 7] },
|
||||
]))
|
||||
|
||||
expect(result).toEqual({ kind: 'models', models: [{ value: 'sonnet', effortLevels: ['low'] }] })
|
||||
})
|
||||
|
||||
it('reports an explicit control error with the CLI message', () => {
|
||||
const line = JSON.stringify({
|
||||
type: 'control_response',
|
||||
response: { subtype: 'error', request_id: PROBE_REQUEST_ID, error: 'Not logged in' },
|
||||
})
|
||||
|
||||
expect(parseClaudeModelsProbeLine(line)).toEqual({ kind: 'error', error: 'Not logged in' })
|
||||
})
|
||||
|
||||
it('ignores hook events, other requests and non-JSON output', () => {
|
||||
expect(parseClaudeModelsProbeLine(JSON.stringify({ type: 'system', subtype: 'hook_started' }))).toBeNull()
|
||||
expect(parseClaudeModelsProbeLine(successLine([OPUS_ROW], 'someone-else'))).toBeNull()
|
||||
expect(parseClaudeModelsProbeLine('Welcome to Claude Code')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('listClaudeModels', () => {
|
||||
it('spawns the session executable isolated from project settings, hooks and MCP servers', async () => {
|
||||
const pending = listClaudeModels()
|
||||
lastChild().respond([OPUS_ROW])
|
||||
await pending
|
||||
|
||||
const [command, args, options] = spawnMock.mock.calls[0] as [string, string[], { cwd: string }]
|
||||
expect(command).toBe('/usr/local/bin/claude')
|
||||
expect(args).toEqual(expect.arrayContaining(['--print', '--strict-mcp-config']))
|
||||
expect(args[args.indexOf('--setting-sources') + 1]).toBe('user')
|
||||
expect(JSON.parse(args[args.indexOf('--settings') + 1] ?? 'null')).toEqual({ disableAllHooks: true })
|
||||
expect(args[args.indexOf('--input-format') + 1]).toBe('stream-json')
|
||||
expect(args[args.indexOf('--output-format') + 1]).toBe('stream-json')
|
||||
expect(options.cwd).toBe(homedir())
|
||||
})
|
||||
|
||||
it('asks for the catalog with an initialize control request and no prompt', async () => {
|
||||
const pending = listClaudeModels()
|
||||
const child = lastChild()
|
||||
child.respond([OPUS_ROW])
|
||||
await pending
|
||||
|
||||
expect(child.stdin.write).toHaveBeenCalledTimes(1)
|
||||
expect(JSON.parse(String(child.stdin.write.mock.calls[0]?.[0]))).toEqual({
|
||||
type: 'control_request',
|
||||
request_id: PROBE_REQUEST_ID,
|
||||
request: { subtype: 'initialize' },
|
||||
})
|
||||
})
|
||||
|
||||
it('returns the catalog and stops the probe process', async () => {
|
||||
const pending = listClaudeModels()
|
||||
lastChild().respond([OPUS_ROW])
|
||||
|
||||
await expect(pending).resolves.toMatchObject({
|
||||
success: true,
|
||||
availableModels: [{ value: 'opus', displayName: 'Opus 5.5' }],
|
||||
})
|
||||
expect(killMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('shares one probe between concurrent requests', async () => {
|
||||
const first = listClaudeModels()
|
||||
const second = listClaudeModels()
|
||||
lastChild().respond([OPUS_ROW])
|
||||
|
||||
await expect(Promise.all([first, second])).resolves.toHaveLength(2)
|
||||
expect(spawnMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('serves a cached catalog for five minutes, then probes again', async () => {
|
||||
vi.useFakeTimers()
|
||||
const first = listClaudeModels()
|
||||
lastChild().respond([OPUS_ROW])
|
||||
await first
|
||||
|
||||
vi.advanceTimersByTime(5 * 60_000 - 1)
|
||||
await listClaudeModels()
|
||||
expect(spawnMock).toHaveBeenCalledTimes(1)
|
||||
|
||||
vi.advanceTimersByTime(1)
|
||||
const refreshed = listClaudeModels()
|
||||
lastChild().respond([OPUS_ROW])
|
||||
await refreshed
|
||||
expect(spawnMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('keeps a separate cache per claude executable', async () => {
|
||||
const first = listClaudeModels()
|
||||
lastChild().respond([OPUS_ROW])
|
||||
await first
|
||||
|
||||
claudePathMock.mockReturnValue('/opt/other/claude')
|
||||
const second = listClaudeModels()
|
||||
lastChild().respond([OPUS_ROW])
|
||||
await second
|
||||
|
||||
expect(spawnMock).toHaveBeenCalledTimes(2)
|
||||
expect(spawnMock.mock.calls[1]?.[0]).toBe('/opt/other/claude')
|
||||
})
|
||||
|
||||
it('does not cache a failure, so the next request probes again', async () => {
|
||||
const failed = listClaudeModels()
|
||||
lastChild().emit('error', new Error('spawn claude ENOENT'))
|
||||
await expect(failed).rejects.toThrow('spawn claude ENOENT')
|
||||
|
||||
const retried = listClaudeModels()
|
||||
lastChild().respond([OPUS_ROW])
|
||||
await expect(retried).resolves.toMatchObject({ success: true })
|
||||
expect(spawnMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('rejects an empty catalog instead of caching it', async () => {
|
||||
const pending = listClaudeModels()
|
||||
lastChild().respond([])
|
||||
await expect(pending).rejects.toThrow('no models')
|
||||
|
||||
const retried = listClaudeModels()
|
||||
lastChild().respond([OPUS_ROW])
|
||||
await retried
|
||||
expect(spawnMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('surfaces the CLI error and exit output when it quits before answering', async () => {
|
||||
const pending = listClaudeModels()
|
||||
const child = lastChild()
|
||||
child.stderr.emit('data', 'Invalid API key')
|
||||
child.emit('close', 1)
|
||||
|
||||
await expect(pending).rejects.toThrow('Invalid API key')
|
||||
})
|
||||
|
||||
it('times out a probe that never answers and stops it', async () => {
|
||||
vi.useFakeTimers()
|
||||
const pending = listClaudeModels()
|
||||
const assertion = expect(pending).rejects.toThrow('timed out')
|
||||
|
||||
await vi.advanceTimersByTimeAsync(15_000)
|
||||
await assertion
|
||||
expect(killMock).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports a missing claude executable without spawning', async () => {
|
||||
claudePathMock.mockImplementation(() => {
|
||||
throw new Error('Claude Code CLI not found on PATH')
|
||||
})
|
||||
|
||||
await expect(listClaudeModels()).rejects.toThrow('Claude Code CLI not found on PATH')
|
||||
expect(spawnMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not let a stdin write failure escape as an unhandled error', async () => {
|
||||
const pending = listClaudeModels()
|
||||
const child = lastChild()
|
||||
|
||||
expect(() => child.stdin.emit('error', new Error('write EPIPE'))).not.toThrow()
|
||||
child.emit('close', null)
|
||||
await expect(pending).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,241 @@
|
||||
import { spawn } from 'node:child_process'
|
||||
import { homedir } from 'node:os'
|
||||
import type { ClaudeModelSummary, ClaudeModelsResponse } from '@hapi/protocol/apiTypes'
|
||||
import { getDefaultClaudeCodePath } from '@/claude/sdk/utils'
|
||||
import { withBunRuntimeEnv } from '@/utils/bunRuntime'
|
||||
import { killProcessByChildProcess } from '../../utils/process'
|
||||
import { getErrorMessage } from './rpcResponses'
|
||||
|
||||
export type ListClaudeModelsRequest = Record<string, never>
|
||||
|
||||
export type ListClaudeModelsResponse = ClaudeModelsResponse
|
||||
|
||||
interface CacheEntry {
|
||||
expiresAt: number
|
||||
response: ListClaudeModelsResponse
|
||||
}
|
||||
|
||||
// The catalog changes rarely (a CLI update, a different login, an alias the
|
||||
// service moves to a newer model) and each probe starts a full claude process
|
||||
// (~0.75s), so a successful answer is kept for a few minutes. Failures are not
|
||||
// cached: a user who just logged in should not wait out the TTL.
|
||||
const CACHE_TTL_MS = 5 * 60_000
|
||||
const PROBE_TIMEOUT_MS = 15_000
|
||||
const PROBE_REQUEST_ID = 'hapi-claude-models-probe'
|
||||
const cache = new Map<string, CacheEntry>()
|
||||
const inflight = new Map<string, Promise<ListClaudeModelsResponse>>()
|
||||
|
||||
/**
|
||||
* Machine-level discovery of the models the `claude` CLI offers, read from the
|
||||
* `models` field of its `initialize` control response. No prompt is sent, so
|
||||
* the probe starts no turn and writes no transcript.
|
||||
*
|
||||
* `claude --print` loads the working directory's `.claude/settings*.json` and
|
||||
* `.mcp.json` without a workspace trust prompt, so any project hook or MCP
|
||||
* server there would run. The probe therefore runs from the home directory
|
||||
* and loads only user settings, no MCP servers, and no hooks at all (the
|
||||
* user's own hooks would otherwise fire on every catalog refresh).
|
||||
*
|
||||
* User settings stay loaded so the probe sees the same `env` a session does
|
||||
* (e.g. `ANTHROPIC_DEFAULT_OPUS_MODEL` changes what `opus` resolves to).
|
||||
* Project settings that redefine model aliases are ignored here, so in such
|
||||
* a directory the catalog can differ from what the session resolves.
|
||||
*/
|
||||
const CLAUDE_MODELS_PROBE_ARGS = [
|
||||
'--print',
|
||||
'--input-format', 'stream-json',
|
||||
'--output-format', 'stream-json',
|
||||
'--verbose',
|
||||
'--setting-sources', 'user',
|
||||
'--strict-mcp-config',
|
||||
'--settings', JSON.stringify({ disableAllHooks: true }),
|
||||
] as const
|
||||
|
||||
export type ClaudeModelsProbeLineResult =
|
||||
| { kind: 'models'; models: ClaudeModelSummary[] }
|
||||
| { kind: 'error'; error: string }
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | null {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
? value as Record<string, unknown>
|
||||
: null
|
||||
}
|
||||
|
||||
function optionalString(value: unknown): string | undefined {
|
||||
return typeof value === 'string' && value.trim() ? value : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* A row without `supportsEffort` (or with `null`) has no effort control, but
|
||||
* only when the CLI reports effort support at all: a CLI that predates the
|
||||
* field would otherwise hide effort for every model. A model that supports
|
||||
* effort without listing levels keeps them unknown.
|
||||
*/
|
||||
function parseClaudeCatalog(rawModels: unknown): ClaudeModelSummary[] {
|
||||
if (!Array.isArray(rawModels)) {
|
||||
return []
|
||||
}
|
||||
const rows = rawModels.map(asRecord).filter((row): row is Record<string, unknown> => row !== null)
|
||||
const reportsEffortSupport = rows.some((row) => 'supportsEffort' in row)
|
||||
const models: ClaudeModelSummary[] = []
|
||||
for (const row of rows) {
|
||||
const value = optionalString(row.value)
|
||||
if (!value) {
|
||||
continue
|
||||
}
|
||||
const model: ClaudeModelSummary = { value }
|
||||
const displayName = optionalString(row.displayName)
|
||||
if (displayName) model.displayName = displayName
|
||||
if (reportsEffortSupport && row.supportsEffort !== true) {
|
||||
model.effortLevels = []
|
||||
} else if (Array.isArray(row.supportedEffortLevels)) {
|
||||
model.effortLevels = row.supportedEffortLevels.filter((level): level is string => typeof level === 'string')
|
||||
}
|
||||
models.push(model)
|
||||
}
|
||||
return models
|
||||
}
|
||||
|
||||
/** Scans one stdout line for the answer to the probe's initialize request. */
|
||||
export function parseClaudeModelsProbeLine(line: string): ClaudeModelsProbeLineResult | null {
|
||||
const trimmed = line.trim()
|
||||
if (!trimmed.startsWith('{')) return null
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(trimmed)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
const message = asRecord(parsed)
|
||||
if (message?.type !== 'control_response') return null
|
||||
const response = asRecord(message.response)
|
||||
if (response?.request_id !== PROBE_REQUEST_ID) return null
|
||||
if (response.subtype !== 'success') {
|
||||
return { kind: 'error', error: optionalString(response.error) ?? 'Claude rejected the model probe request' }
|
||||
}
|
||||
return { kind: 'models', models: parseClaudeCatalog(asRecord(response.response)?.models) }
|
||||
}
|
||||
|
||||
function runClaudeModelsProbe(executable: string): Promise<ListClaudeModelsResponse> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(executable, [...CLAUDE_MODELS_PROBE_ARGS], {
|
||||
cwd: homedir(),
|
||||
env: withBunRuntimeEnv(process.env, { allowBunBeBun: false }),
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
// getDefaultClaudeCodePath resolves an absolute path (claude.exe on
|
||||
// Windows), matching how sessions spawn it.
|
||||
shell: false,
|
||||
windowsHide: process.platform === 'win32',
|
||||
})
|
||||
let stdoutBuffer = ''
|
||||
let stderr = ''
|
||||
let settled = false
|
||||
|
||||
// The claude process stays up waiting for input, so every outcome
|
||||
// stops it before the caller sees a result.
|
||||
const finish = (settle: () => void) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timeout)
|
||||
void (async () => {
|
||||
if (!child.pid) {
|
||||
settle()
|
||||
return
|
||||
}
|
||||
let stopped = false
|
||||
try {
|
||||
stopped = await killProcessByChildProcess(child, false)
|
||||
|| await killProcessByChildProcess(child, true)
|
||||
} catch {
|
||||
stopped = false
|
||||
}
|
||||
if (!stopped) {
|
||||
reject(new Error(`Claude model probe could not be stopped (pid ${child.pid})`))
|
||||
return
|
||||
}
|
||||
settle()
|
||||
})()
|
||||
}
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
finish(() => reject(new Error('Claude model discovery timed out')))
|
||||
}, PROBE_TIMEOUT_MS)
|
||||
|
||||
child.stdout?.on('data', (chunk) => {
|
||||
stdoutBuffer += chunk.toString()
|
||||
let newlineIndex = stdoutBuffer.indexOf('\n')
|
||||
while (newlineIndex !== -1 && !settled) {
|
||||
const line = stdoutBuffer.slice(0, newlineIndex)
|
||||
stdoutBuffer = stdoutBuffer.slice(newlineIndex + 1)
|
||||
newlineIndex = stdoutBuffer.indexOf('\n')
|
||||
const result = parseClaudeModelsProbeLine(line)
|
||||
if (result === null) continue
|
||||
if (result.kind === 'error') {
|
||||
finish(() => reject(new Error(result.error)))
|
||||
return
|
||||
}
|
||||
if (result.models.length === 0) {
|
||||
finish(() => reject(new Error('Claude reported no models')))
|
||||
return
|
||||
}
|
||||
finish(() => resolve({ success: true, availableModels: result.models }))
|
||||
return
|
||||
}
|
||||
})
|
||||
child.stderr?.on('data', (chunk) => {
|
||||
stderr += chunk.toString()
|
||||
})
|
||||
child.on('error', (error) => {
|
||||
finish(() => reject(error))
|
||||
})
|
||||
child.on('close', (code) => {
|
||||
finish(() => reject(new Error(
|
||||
stderr.trim() || `claude exited with code ${code ?? 'unknown'} before answering the model probe`
|
||||
)))
|
||||
})
|
||||
// An early exit surfaces through 'close', not as an unhandled EPIPE.
|
||||
child.stdin?.on('error', () => { /* handled via close */ })
|
||||
child.stdin?.write(`${JSON.stringify({
|
||||
type: 'control_request',
|
||||
request_id: PROBE_REQUEST_ID,
|
||||
request: { subtype: 'initialize' },
|
||||
})}\n`)
|
||||
})
|
||||
}
|
||||
|
||||
/** Clear the module-level probe cache and in-flight map between tests. */
|
||||
export function _resetClaudeModelsCacheForTests(): void {
|
||||
cache.clear()
|
||||
inflight.clear()
|
||||
}
|
||||
|
||||
/** Throws on failure; the RPC handler turns that into an error response. */
|
||||
export async function listClaudeModels(): Promise<ListClaudeModelsResponse> {
|
||||
// Keyed by executable: HAPI_CLAUDE_PATH can point a runner at a different
|
||||
// claude install, whose catalog is its own.
|
||||
const executable = getDefaultClaudeCodePath()
|
||||
const now = Date.now()
|
||||
const cached = cache.get(executable)
|
||||
if (cached && cached.expiresAt > now) {
|
||||
return cached.response
|
||||
}
|
||||
|
||||
const existing = inflight.get(executable)
|
||||
if (existing) {
|
||||
return existing
|
||||
}
|
||||
|
||||
const pending = runClaudeModelsProbe(executable)
|
||||
.then((response) => {
|
||||
cache.set(executable, { expiresAt: Date.now() + CACHE_TTL_MS, response })
|
||||
return response
|
||||
})
|
||||
.catch((error) => {
|
||||
throw new Error(getErrorMessage(error, 'Failed to list Claude models'))
|
||||
})
|
||||
.finally(() => {
|
||||
inflight.delete(executable)
|
||||
})
|
||||
inflight.set(executable, pending)
|
||||
return pending
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { RPC_METHODS } from '@hapi/protocol/rpcMethods'
|
||||
import { RpcHandlerManager } from '@/api/rpc/RpcHandlerManager'
|
||||
|
||||
const { listClaudeModelsMock } = vi.hoisted(() => ({
|
||||
listClaudeModelsMock: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../claudeModels', () => ({
|
||||
listClaudeModels: listClaudeModelsMock,
|
||||
}))
|
||||
|
||||
import { registerClaudeModelHandlers } from './claudeModels'
|
||||
|
||||
describe('listClaudeModels machine RPC handler', () => {
|
||||
let rpc: RpcHandlerManager
|
||||
|
||||
beforeEach(() => {
|
||||
listClaudeModelsMock.mockReset()
|
||||
rpc = new RpcHandlerManager({ scopePrefix: 'machine-test' })
|
||||
registerClaudeModelHandlers(rpc)
|
||||
})
|
||||
|
||||
async function listViaRpc(): Promise<unknown> {
|
||||
const raw = await rpc.handleRequest({
|
||||
method: `machine-test:${RPC_METHODS.ListClaudeModels}`,
|
||||
params: '{}'
|
||||
})
|
||||
return JSON.parse(raw)
|
||||
}
|
||||
|
||||
it('returns the discovered catalog', async () => {
|
||||
listClaudeModelsMock.mockResolvedValue({
|
||||
success: true,
|
||||
availableModels: [{ value: 'opus' }]
|
||||
})
|
||||
|
||||
await expect(listViaRpc()).resolves.toEqual({
|
||||
success: true,
|
||||
availableModels: [{ value: 'opus' }]
|
||||
})
|
||||
})
|
||||
|
||||
it('answers a failed probe with an error response instead of throwing', async () => {
|
||||
listClaudeModelsMock.mockRejectedValue(new Error('Claude model discovery timed out'))
|
||||
|
||||
await expect(listViaRpc()).resolves.toEqual({
|
||||
success: false,
|
||||
error: 'Claude model discovery timed out'
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,25 @@
|
||||
import { logger } from '@/ui/logger';
|
||||
import { RPC_METHODS } from '@hapi/protocol/rpcMethods';
|
||||
import type { RpcHandlerManager } from '@/api/rpc/RpcHandlerManager';
|
||||
import {
|
||||
listClaudeModels,
|
||||
type ListClaudeModelsRequest,
|
||||
type ListClaudeModelsResponse
|
||||
} from '../claudeModels';
|
||||
import { getErrorMessage, rpcError } from '../rpcResponses';
|
||||
|
||||
export function registerClaudeModelHandlers(rpcHandlerManager: RpcHandlerManager): void {
|
||||
rpcHandlerManager.registerHandler<ListClaudeModelsRequest, ListClaudeModelsResponse>(
|
||||
RPC_METHODS.ListClaudeModels,
|
||||
async () => {
|
||||
logger.debug('List Claude models request');
|
||||
|
||||
try {
|
||||
return await listClaudeModels();
|
||||
} catch (error) {
|
||||
logger.debug('Failed to list Claude models:', error);
|
||||
return rpcError(getErrorMessage(error, 'Failed to list Claude models'));
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { RpcHandlerManager } from '@/api/rpc/RpcHandlerManager'
|
||||
import { registerAgyModelHandlers } from './handlers/agyModels'
|
||||
import { registerBashHandlers } from './handlers/bash'
|
||||
import { registerClaudeModelHandlers } from './handlers/claudeModels'
|
||||
import { registerCodexModelHandlers } from './handlers/codexModels'
|
||||
import { registerCursorModelHandlers } from './handlers/cursorModels'
|
||||
import { registerOpencodeModelHandlers } from './handlers/opencodeModels'
|
||||
@@ -21,6 +22,7 @@ import { registerUploadHandlers } from './handlers/uploads'
|
||||
export function registerCommonHandlers(rpcHandlerManager: RpcHandlerManager, workingDirectory: string): void {
|
||||
registerAgyModelHandlers(rpcHandlerManager)
|
||||
registerBashHandlers(rpcHandlerManager, workingDirectory)
|
||||
registerClaudeModelHandlers(rpcHandlerManager)
|
||||
registerCodexModelHandlers(rpcHandlerManager)
|
||||
registerCursorModelHandlers(rpcHandlerManager)
|
||||
registerOpencodeModelHandlers(rpcHandlerManager)
|
||||
|
||||
Reference in New Issue
Block a user