perf(cli): load command modules on demand (#2404)

This commit is contained in:
Akiiia
2026-11-13 08:38:41 +08:00
committed by GitHub
parent e24ccf5e50
commit 72b341fde1
4 changed files with 129 additions and 78 deletions
+47 -8
View File
@@ -1,25 +1,64 @@
import { describe, expect, it } from 'vitest'
import { describe, expect, it, vi } from 'vitest'
import { CREATABLE_AGENT_FLAVORS } from '@hapi/protocol'
import { resolveCommand } from './registry'
describe('command registry', () => {
it.each(CREATABLE_AGENT_FLAVORS)('dispatches %s explicitly with its arguments intact', (agent) => {
it.each(CREATABLE_AGENT_FLAVORS)('dispatches %s explicitly with its arguments intact', async (agent) => {
const commandArgs = ['--help', '-h', '--version', '--', 'claude', '--model', 'literal']
const args = [agent, ...commandArgs]
const resolved = resolveCommand(args)
const resolved = await resolveCommand(args)
expect(resolved?.command.name).toBe(agent)
expect(resolved?.context).toEqual({ args, subcommand: agent, commandArgs })
})
it.each([[], ['unknown'], ['--yolo'], ['--resume'], ['a prompt']])(
'does not fall back to Claude for %j', (...args) => {
expect(resolveCommand(args)).toBeNull()
'does not fall back to Claude for %j', async (...args) => {
expect(await resolveCommand(args)).toBeNull()
}
)
it('keeps the hub alias and Gemini tombstone', () => {
expect(resolveCommand(['server'])?.command.run).toBe(resolveCommand(['hub'])?.command.run)
expect(resolveCommand(['gemini'])?.command.name).toBe('gemini')
it('keeps the hub alias and Gemini tombstone', async () => {
const server = await resolveCommand(['server'])
const hub = await resolveCommand(['hub'])
expect(server?.command.name).toBe('server')
expect(server?.command.run).toBe(hub?.command.run)
expect((await resolveCommand(['gemini']))?.command.name).toBe('gemini')
})
it('evaluates command modules only when selected', async () => {
const evaluated: string[] = []
vi.resetModules()
vi.doMock('./mcp', async () => {
evaluated.push('mcp')
return vi.importActual<typeof import('./mcp')>('./mcp')
})
vi.doMock('./runner', async () => {
evaluated.push('runner')
return vi.importActual<typeof import('./runner')>('./runner')
})
vi.doMock('./resume', async () => {
evaluated.push('resume')
return vi.importActual<typeof import('./resume')>('./resume')
})
try {
const { resolveCommand } = await import('./registry')
expect(evaluated).toEqual([])
const mcp = await resolveCommand(['mcp'])
expect(evaluated).toEqual(['mcp'])
expect(mcp?.command).toBe((await import('./mcp')).mcpCommand)
const runner = await resolveCommand(['runner', 'status'])
expect(evaluated).toEqual(['mcp', 'runner'])
expect(runner?.command).toBe((await import('./runner')).runnerCommand)
} finally {
vi.doUnmock('./mcp')
vi.doUnmock('./runner')
vi.doUnmock('./resume')
vi.resetModules()
}
})
})
+34 -64
View File
@@ -1,30 +1,4 @@
import chalk from 'chalk'
import { agyCommand } from './agy'
import { authCommand } from './auth'
import { claudeCommand } from './claude'
import { codexCommand } from './codex'
import { dshCommand } from './dsh'
import { cursorCommand } from './cursor'
import { connectCommand } from './connect'
import { runnerCommand } from './runner'
import { resumeCommand } from './resume'
import { doctorCommand } from './doctor'
import { kimiCommand } from './kimi'
import { copilotCommand } from './copilot'
import { grokCommand } from './grok'
import { opencodeCommand } from './opencode'
import { piCommand } from './pi'
import { hookForwarderCommand } from './hookForwarder'
import { mcpCommand } from './mcp'
import { mcpProxyCommand } from './mcpProxy'
import { notifyCommand } from './notify'
import { hubCommand } from './hub'
import { pingPeerCommand } from './pingPeer'
import { inspectPeerCommand } from './inspectPeer'
import { spawnPeerCommand } from './spawnPeer'
import { usageCommand } from './usage'
import { setModeCommand } from './setMode'
import { jobCommand } from './job'
import type { CommandContext, CommandDefinition } from './types'
// Gemini CLI was sunset (Google stopped serving the consumer Gemini CLI on
@@ -42,46 +16,42 @@ const removedGeminiCommand: CommandDefinition = {
}
}
const COMMANDS: CommandDefinition[] = [
agyCommand,
authCommand,
claudeCommand,
connectCommand,
codexCommand,
dshCommand,
cursorCommand,
removedGeminiCommand,
grokCommand,
kimiCommand,
copilotCommand,
opencodeCommand,
piCommand,
mcpCommand,
mcpProxyCommand,
hubCommand,
{ ...hubCommand, name: 'server' },
hookForwarderCommand,
doctorCommand,
resumeCommand,
runnerCommand,
notifyCommand,
pingPeerCommand,
inspectPeerCommand,
spawnPeerCommand,
setModeCommand,
jobCommand,
usageCommand
]
const commandMap = new Map<string, () => Promise<CommandDefinition>>([
['agy', async () => (await import('./agy')).agyCommand],
['auth', async () => (await import('./auth')).authCommand],
['claude', async () => (await import('./claude')).claudeCommand],
['connect', async () => (await import('./connect')).connectCommand],
['codex', async () => (await import('./codex')).codexCommand],
['dsh', async () => (await import('./dsh')).dshCommand],
['cursor', async () => (await import('./cursor')).cursorCommand],
['gemini', async () => removedGeminiCommand],
['grok', async () => (await import('./grok')).grokCommand],
['kimi', async () => (await import('./kimi')).kimiCommand],
['copilot', async () => (await import('./copilot')).copilotCommand],
['opencode', async () => (await import('./opencode')).opencodeCommand],
['pi', async () => (await import('./pi')).piCommand],
['mcp', async () => (await import('./mcp')).mcpCommand],
['mcp-proxy', async () => (await import('./mcpProxy')).mcpProxyCommand],
['hub', async () => (await import('./hub')).hubCommand],
['server', async () => ({ ...(await import('./hub')).hubCommand, name: 'server' })],
['hook-forwarder', async () => (await import('./hookForwarder')).hookForwarderCommand],
['doctor', async () => (await import('./doctor')).doctorCommand],
['resume', async () => (await import('./resume')).resumeCommand],
['runner', async () => (await import('./runner')).runnerCommand],
['notify', async () => (await import('./notify')).notifyCommand],
['ping-peer', async () => (await import('./pingPeer')).pingPeerCommand],
['inspect-peer', async () => (await import('./inspectPeer')).inspectPeerCommand],
['spawn-peer', async () => (await import('./spawnPeer')).spawnPeerCommand],
['set-mode', async () => (await import('./setMode')).setModeCommand],
['job', async () => (await import('./job')).jobCommand],
['usage', async () => (await import('./usage')).usageCommand]
])
const commandMap = new Map<string, CommandDefinition>()
for (const command of COMMANDS) {
commandMap.set(command.name, command)
}
export function resolveCommand(args: string[]): { command: CommandDefinition; context: CommandContext } | null {
export async function resolveCommand(args: string[]): Promise<{ command: CommandDefinition; context: CommandContext } | null> {
const subcommand = args[0]
const command = subcommand ? commandMap.get(subcommand) : undefined
if (!command) return null
const loadCommand = subcommand ? commandMap.get(subcommand) : undefined
if (!loadCommand) return null
const command = await loadCommand()
return {
command,
+47 -5
View File
@@ -2,10 +2,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { AgentSelection } from '@/ui/selectAgent'
import type { CommandContext } from './types'
const { getCliArgsMock, resolveCommandMock, selectAgentMock, ensureRuntimeAssetsMock, runMock } = vi.hoisted(() => ({
const { getCliArgsMock, resolveCommandMock, selectAgentMock, ensureLoopbackProxyBypassMock, isBunCompiledMock, ensureRuntimeAssetsMock, runMock } = vi.hoisted(() => ({
getCliArgsMock: vi.fn<() => string[]>(),
resolveCommandMock: vi.fn(),
selectAgentMock: vi.fn<() => Promise<AgentSelection>>(),
ensureLoopbackProxyBypassMock: vi.fn(),
isBunCompiledMock: vi.fn(() => false),
ensureRuntimeAssetsMock: vi.fn(async () => {}),
runMock: vi.fn<(_: CommandContext) => Promise<void>>(async () => {})
}))
@@ -14,9 +16,9 @@ vi.mock('@/utils/cliArgs', () => ({ getCliArgs: getCliArgsMock }))
vi.mock('./registry', () => ({ resolveCommand: resolveCommandMock }))
vi.mock('@/ui/selectAgent', () => ({ selectAgent: selectAgentMock }))
vi.mock('@/runtime/assets', () => ({ ensureRuntimeAssets: ensureRuntimeAssetsMock }))
vi.mock('@/projectPath', () => ({ isBunCompiled: () => false }))
vi.mock('@/projectPath', () => ({ isBunCompiled: isBunCompiledMock }))
vi.mock('@/ui/logger', () => ({ logger: { debug: vi.fn() } }))
vi.mock('@/utils/proxyEnv', () => ({ ensureLoopbackProxyBypass: vi.fn() }))
vi.mock('@/utils/proxyEnv', () => ({ ensureLoopbackProxyBypass: ensureLoopbackProxyBypassMock }))
import { runCli } from './runCli'
@@ -32,7 +34,7 @@ describe('CLI entrypoint', () => {
Object.defineProperty(process.stdout, 'isTTY', { configurable: true, value: true })
vi.spyOn(console, 'log').mockImplementation(() => {})
vi.spyOn(console, 'error').mockImplementation(() => {})
resolveCommandMock.mockImplementation((args: string[]) => ({
resolveCommandMock.mockImplementation(async (args: string[]) => ({
command: { name: args[0], requiresRuntimeAssets: args[0] !== 'pi', run: runMock },
context: { args, subcommand: args[0], commandArgs: args.slice(1) }
}))
@@ -83,9 +85,49 @@ describe('CLI entrypoint', () => {
expect(console.log).not.toHaveBeenCalled()
})
it('finishes loading the command before preparing its runtime and running it', async () => {
const order: string[] = []
const originalDev = process.env.DEV
const args = ['codex']
getCliArgsMock.mockReturnValue(args)
process.env.DEV = 'true'
resolveCommandMock.mockImplementationOnce(async () => {
await Promise.resolve()
expect(process.env.DEV).toBe('true')
order.push('command')
return {
command: { name: 'codex', requiresRuntimeAssets: true, run: runMock },
context: { args, subcommand: 'codex', commandArgs: [] }
}
})
ensureLoopbackProxyBypassMock.mockImplementationOnce(() => { order.push('proxy') })
isBunCompiledMock.mockImplementationOnce(() => {
order.push('compiled')
return true
})
ensureRuntimeAssetsMock.mockImplementationOnce(async () => {
expect(process.env.DEV).toBe('false')
order.push('assets')
})
runMock.mockImplementationOnce(async () => { order.push('run') })
try {
await runCli()
expect(order).toEqual(['command', 'proxy', 'compiled', 'assets', 'run'])
} finally {
if (originalDev === undefined) delete process.env.DEV
else process.env.DEV = originalDev
resolveCommandMock.mockReset()
ensureLoopbackProxyBypassMock.mockReset()
isBunCompiledMock.mockReset()
ensureRuntimeAssetsMock.mockReset()
runMock.mockReset()
}
})
it.each(['unknown', '--yolo', '--resume', 'a prompt'])('rejects %s instead of starting Claude', async (arg) => {
getCliArgsMock.mockReturnValue([arg])
resolveCommandMock.mockReturnValue(null)
resolveCommandMock.mockResolvedValue(null)
await runCli()
expect(process.exitCode).toBe(1)
+1 -1
View File
@@ -34,7 +34,7 @@ export async function runCli(): Promise<void> {
}
const { resolveCommand } = await import('./registry')
const resolved = resolveCommand(args)
const resolved = await resolveCommand(args)
if (!resolved) {
console.error(`Unknown ${args[0].startsWith('-') ? 'option' : 'command'}: ${args[0]}`)
console.error('Run hapi to choose an agent, or use hapi <agent> [options]. See hapi --help.')