diff --git a/cli/src/agent/sessionConfigRpc.test.ts b/cli/src/agent/sessionConfigRpc.test.ts index ba462d51..b1adb933 100644 --- a/cli/src/agent/sessionConfigRpc.test.ts +++ b/cli/src/agent/sessionConfigRpc.test.ts @@ -71,6 +71,23 @@ describe('sessionConfigRpc', () => { expect(onAfterApply).not.toHaveBeenCalled() }) + it('acknowledges the normalized model and effort returned by the agent', async () => { + const harness = createRpcHarness() + const onAfterApply = vi.fn() + registerSessionConfigRpc({ + rpcHandlerManager: harness.rpcHandlerManager, + flavor: 'agy', + modelMode: 'nullable', + effortMode: 'nullable', + onApply: async () => ({ model: 'gemini-4-argon', effort: 'high' }), + onAfterApply, + }) + + await expect(harness.getHandler()({ model: 'gemini-4-argon-medium', effort: 'high' })) + .resolves.toEqual({ applied: { model: 'gemini-4-argon', effort: 'high' } }) + expect(onAfterApply).toHaveBeenCalledOnce() + }) + it('ignores model config for agents that do not support model changes when configured to ignore', async () => { const harness = createRpcHarness() const onApply = vi.fn() diff --git a/cli/src/agent/sessionConfigRpc.ts b/cli/src/agent/sessionConfigRpc.ts index 9c558193..3e20ff0d 100644 --- a/cli/src/agent/sessionConfigRpc.ts +++ b/cli/src/agent/sessionConfigRpc.ts @@ -18,7 +18,7 @@ type RegisterSessionConfigRpcOptions Record - onApply: (config: SessionConfigState) => void | Promise + onApply: (config: SessionConfigState) => void | SessionConfigState | Promise> onAfterApply?: () => void | Promise } @@ -110,7 +110,10 @@ export function registerSessionConfigRpc } } - await onApply(next) + const normalized = await onApply(next) + if (normalized) { + Object.assign(applied, normalized) + } await onAfterApply?.() return { diff --git a/cli/src/agy/headless/agyHeadlessDriver.test.ts b/cli/src/agy/headless/agyHeadlessDriver.test.ts index a5c27a7a..e8bbc287 100644 --- a/cli/src/agy/headless/agyHeadlessDriver.test.ts +++ b/cli/src/agy/headless/agyHeadlessDriver.test.ts @@ -107,7 +107,7 @@ describe('buildAgyHeadlessArgs', () => { const args = buildAgyHeadlessArgs({ prompt: 'hi', conversationId: 'conv-1', - model: 'gemini-3.5-flash-medium', + model: 'gemini-3.5-flash', permissionMode: 'always-proceed', mode: 'plan', effort: 'high', @@ -115,7 +115,7 @@ describe('buildAgyHeadlessArgs', () => { expect(args).toContain('--conversation'); expect(args).toContain('conv-1'); expect(args).toContain('--model'); - expect(args).toContain('gemini-3.5-flash-medium'); + expect(args).toContain('gemini-3.5-flash'); expect(args).toContain('--mode'); expect(args).toContain('plan'); expect(args).toContain('--effort'); @@ -127,9 +127,46 @@ describe('buildAgyHeadlessArgs', () => { const args = buildAgyHeadlessArgs({ prompt: 'hi', permissionMode: 'request-review' }); expect(args).not.toContain('--dangerously-skip-permissions'); }); + + it('rejects a conflicting unnormalized variant instead of spawning an invalid selection', () => { + expect(() => buildAgyHeadlessArgs({ + prompt: 'hi', permissionMode: 'request-review', model: 'gemini-4-argon-medium', effort: 'high', + })).toThrow('conflicts with effort high'); + }); + + it('avoids redundant effort flags for an exact variant', () => { + const args = buildAgyHeadlessArgs({ + prompt: 'hi', permissionMode: 'request-review', model: 'gemini-4-argon-medium', effort: 'medium', + }); + expect(args).toContain('gemini-4-argon-medium'); + expect(args).not.toContain('--effort'); + }); + + it.each(['xhigh', 'max'] as const)('passes native %s effort', (effort) => { + const args = buildAgyHeadlessArgs({ + prompt: 'hi', permissionMode: 'request-review', model: 'gemini-4-argon', effort, + }); + expect(args[args.indexOf('--effort') + 1]).toBe(effort); + }); }); describe('AgyHeadlessDriver', () => { + it('restores a conflicting legacy selection without spawning or retrying', async () => { + const { session, queue, client } = createSession(); + const spawnAgy = vi.fn(); + const driver = new AgyHeadlessDriver({ session, spawnAgy }); + queue.push('hello', { permissionMode: 'request-review', model: 'gemini-4-argon-medium', effort: 'high' }, 'local-1'); + queue.close(); + await driver.launch(); + session.stopKeepAlive(); + expect(spawnAgy).not.toHaveBeenCalled(); + expect(client.emitMessagesConsumed).toHaveBeenCalledWith(['local-1']); + expect(client.sendSessionEvent).toHaveBeenCalledWith({ type: 'abort-restore', text: 'hello' }); + expect(client.sendSessionEvent).toHaveBeenCalledWith({ + type: 'error', message: expect.stringContaining('conflicts with effort high'), + }); + }); + it('maps a full NDJSON turn onto the transcript-entry channel and adopts the conversation id', async () => { const { session, queue, client, sent } = createSession(); const driver = new AgyHeadlessDriver({ @@ -685,14 +722,19 @@ describe('AgyHeadlessDriver', () => { expect(plannerEntries.map((e) => e!.content)).toEqual(['Let me check', 'Done: listed']); }); - it('carries the queued model (display label) on emitted planner entries', async () => { + it.each([ + { model: 'gemini-3.5-flash-medium', effort: undefined, label: 'Gemini 3.5 Flash (Medium)' }, + { model: 'gemini-3.5-flash', effort: 'high', label: 'Gemini 3.5 Flash (High)' }, + { model: 'gemini-4-argon', effort: 'high', label: 'gemini-4-argon-high' }, + { model: 'custom-high', effort: 'medium', label: 'custom-high' }, + ])('carries the queued model (display label) on emitted planner entries: $model / $effort', async ({ model, effort, label }) => { const { session, queue, sent } = createSession(); const driver = new AgyHeadlessDriver({ session, spawnAgy: () => fakeAgyProcess(FULL_TURN), }); - queue.push('hello', { permissionMode: 'request-review', model: 'gemini-3.5-flash-medium' }, 'local-1'); + queue.push('hello', { permissionMode: 'request-review', model, effort }, 'local-1'); const launchPromise = driver.launch(); await new Promise((r) => setTimeout(r, 500)); queue.close(); @@ -705,7 +747,7 @@ describe('AgyHeadlessDriver', () => { expect(plannerEntries.length).toBeGreaterThan(0); // Display label, not the raw wire id. for (const entry of plannerEntries) { - expect(entry!.model).toBe('Gemini 3.5 Flash (Medium)'); + expect(entry!.model).toBe(label); } }); diff --git a/cli/src/agy/headless/agyHeadlessDriver.ts b/cli/src/agy/headless/agyHeadlessDriver.ts index 17720e23..68ae3b96 100644 --- a/cli/src/agy/headless/agyHeadlessDriver.ts +++ b/cli/src/agy/headless/agyHeadlessDriver.ts @@ -15,7 +15,7 @@ import { createNativeSessionTitleMetadataSync } from '@/agent/nativeSessionTitle import { readAgyConversationTitle } from '../utils/agySessionTitle'; import { resolveAgyTurnModels } from '../utils/agyConversationModel'; import { killProcessByChildProcess } from '@/utils/process'; -import { AGY_MODEL_LABELS } from '@hapi/protocol'; +import { AGY_EFFORT_LEVELS, AGY_MODEL_LABELS, splitAgyModelSelection, type AgyEffortLevel } from '@hapi/protocol'; import { getAgentLaunchCommand } from '@/agent/agentLaunchCommand'; const AGY_PRINT_TIMEOUT = '30m'; @@ -43,8 +43,12 @@ export function buildAgyHeadlessArgs(opts: { model?: string; permissionMode: PermissionMode; mode?: 'accept-edits' | 'plan'; - effort?: 'low' | 'medium' | 'high'; + effort?: AgyEffortLevel; }): string[] { + const selection = splitAgyModelSelection(opts.model); + if (selection.effort && opts.effort && selection.effort !== opts.effort) { + throw new Error(`Antigravity model ${opts.model} conflicts with effort ${opts.effort}`); + } const args = ['-p', opts.prompt, '--output-format', 'stream-json']; if (opts.conversationId) { args.push('--conversation', opts.conversationId); @@ -55,7 +59,7 @@ export function buildAgyHeadlessArgs(opts: { if (opts.mode) { args.push('--mode', opts.mode); } - if (opts.effort) { + if (opts.effort && !selection.effort) { args.push('--effort', opts.effort); } args.push('--print-timeout', AGY_PRINT_TIMEOUT); @@ -391,18 +395,34 @@ export class AgyHeadlessDriver extends RemoteLauncherBase { const sessionEffort = mode.effort ?? undefined; // Snapshot the model at turn start: a mid-response switch must not change // attribution within one turn. + const variantModel = sessionModel && sessionEffort && !splitAgyModelSelection(sessionModel).effort + ? `${sessionModel}-${sessionEffort}` + : sessionModel; + const variantLabel = variantModel ? AGY_MODEL_LABELS[variantModel as keyof typeof AGY_MODEL_LABELS] : undefined; const turnModel = typeof sessionModel === 'string' && sessionModel - ? AGY_MODEL_LABELS[sessionModel as keyof typeof AGY_MODEL_LABELS] ?? sessionModel + ? variantLabel ?? AGY_MODEL_LABELS[sessionModel as keyof typeof AGY_MODEL_LABELS] + ?? (splitAgyModelSelection(variantModel).effort ? variantModel : sessionModel) : undefined; - const args = buildAgyHeadlessArgs({ - prompt, - conversationId: this.conversationId ?? undefined, - model: sessionModel, - permissionMode: mode.permissionMode, - effort: sessionEffort === 'low' || sessionEffort === 'medium' || sessionEffort === 'high' - ? sessionEffort - : undefined, - }); + let args: string[]; + try { + args = buildAgyHeadlessArgs({ + prompt, + conversationId: this.conversationId ?? undefined, + model: sessionModel, + permissionMode: mode.permissionMode, + effort: (AGY_EFFORT_LEVELS as readonly unknown[]).includes(sessionEffort) + ? sessionEffort as AgyEffortLevel + : undefined, + }); + } catch (error) { + // Invalid legacy config must not lose a dequeued delivery or retry + // the same deterministic failure. Restore it for the user to resend. + if (localIds.length > 0) this.session.client.emitMessagesConsumed(localIds); + this.session.client.sendSessionEvent({ type: 'error', message: error instanceof Error ? error.message : String(error) }); + this.session.client.sendSessionEvent({ type: 'abort-restore', text: prompt }); + signal.removeEventListener('abort', onAbort); + return true; + } // Never persist the user's prompt to the log (HAPI debug logs can be // forwarded under remote-debug configuration); keep the spawn shape. const safeArgs = args.map((arg, index) => (args[index - 1] === '-p' ? '' : arg)); diff --git a/cli/src/agy/runAgy.test.ts b/cli/src/agy/runAgy.test.ts new file mode 100644 index 00000000..504293a4 --- /dev/null +++ b/cli/src/agy/runAgy.test.ts @@ -0,0 +1,178 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { RPC_METHODS } from '@hapi/protocol/rpcMethods' +import type { MessageQueue2 } from '@/utils/MessageQueue2' +import type { AgyMode } from './types' + +const mocks = vi.hoisted(() => ({ + loop: vi.fn(), + bootstrap: vi.fn(), + existing: vi.fn(), + listModels: vi.fn(), + registerHandler: vi.fn(), + onUserMessage: vi.fn(), + receiveUserMessage: vi.fn(), + cleanup: vi.fn(), + markCrash: vi.fn(), +})) + +vi.mock('./loop', () => ({ agyLoop: mocks.loop })) +vi.mock('@/agent/sessionFactory', () => ({ bootstrapSession: mocks.bootstrap, bootstrapExistingSession: mocks.existing })) +vi.mock('@/modules/common/agyModels', () => ({ listAgyModels: mocks.listModels })) +vi.mock('@/agent/runnerLifecycle', () => ({ + createRunnerLifecycle: () => ({ + registerProcessHandlers: vi.fn(), cleanupAndExit: mocks.cleanup, markCrash: mocks.markCrash, setSessionEndReason: vi.fn(), + }), + createModeChangeHandler: () => vi.fn(), +})) +vi.mock('@/claude/registerKillSessionHandler', () => ({ registerKillSessionHandler: vi.fn() })) +vi.mock('@/agent/localHandoff', () => ({ registerLocalHandoffHandler: vi.fn() })) + +import { runAgy } from './runAgy' + +const catalog = [ + { modelId: 'gemini-4-argon-medium' }, + { modelId: 'gemini-4-argon-high' }, + { modelId: 'gemini-4-argon-max' }, + { modelId: 'gpt-oss-120b-medium' }, +] + +function getConfigHandler() { + return mocks.registerHandler.mock.calls.find(([method]) => method === RPC_METHODS.SetSessionConfig)![1] as + (config: { model?: string | null; effort?: string | null }) => Promise +} + +describe('runAgy model and effort config', () => { + afterEach(() => { + expect(mocks.markCrash).not.toHaveBeenCalled() + }) + beforeEach(() => { + vi.resetAllMocks() + type Delivery = { message: { content: { text: string } }; localId?: string } + const pending: Delivery[] = [] + let onMessage: ((message: Delivery['message'], localId?: string) => void) | undefined + // Match ApiSessionClient's existing pre-handler buffering contract. + mocks.onUserMessage.mockImplementation((handler) => { + onMessage = handler + for (const delivery of pending.splice(0)) handler(delivery.message, delivery.localId) + }) + mocks.receiveUserMessage.mockImplementation((text: string, localId?: string) => { + const message = { content: { text } } + if (onMessage) onMessage(message, localId) + else pending.push({ message, localId }) + }) + const bootstrap = { + api: {}, + session: { + onUserMessage: mocks.onUserMessage, + onCancelQueuedMessage: vi.fn(), + rpcHandlerManager: { registerHandler: mocks.registerHandler }, + }, + } + mocks.bootstrap.mockResolvedValue(bootstrap) + mocks.existing.mockResolvedValue(bootstrap) + mocks.listModels.mockResolvedValue({ success: true, availableModels: catalog }) + }) + + it.each([false, true])('normalizes launch/resume selection (existing=%s)', async (existing) => { + await runAgy({ + model: 'gemini-4-argon-medium', effort: 'high', workingDirectory: '/tmp', + ...(existing ? { existingSessionId: 'hub-session', resumeSessionId: 'brain-session' } : {}), + }) + expect(mocks.loop).toHaveBeenCalledWith(expect.objectContaining({ model: 'gemini-4-argon', effort: 'high' })) + if (!existing) { + expect(mocks.bootstrap).toHaveBeenCalledWith(expect.objectContaining({ model: 'gemini-4-argon-medium', effort: 'high' })) + } + }) + + it.each([false, true])('bootstraps before a slow catalog, buffers early input, and orders RPC after initialization (existing=%s)', async (existing) => { + let resolveCatalog!: (response: { success: true; availableModels: typeof catalog }) => void + mocks.listModels.mockReturnValueOnce(new Promise((resolve) => { resolveCatalog = resolve })) + let rpcApplied = false + let rpc: Promise + mocks.loop.mockImplementation(async ({ messageQueue }: { messageQueue: MessageQueue2 }) => { + expect((await messageQueue.waitForMessagesAndGetAsString())?.mode) + .toMatchObject({ model: 'gemini-4-argon', effort: 'high' }) + await rpc + mocks.receiveUserMessage('after config', 'second') + expect((await messageQueue.waitForMessagesAndGetAsString())?.mode) + .toMatchObject({ model: 'gemini-4-argon', effort: 'max' }) + }) + + const running = runAgy({ + model: 'gemini-4-argon-medium', effort: 'high', workingDirectory: '/tmp', + ...(existing ? { existingSessionId: 'hub-session', resumeSessionId: 'brain-session' } : {}), + }) + await vi.waitFor(() => expect(mocks.listModels).toHaveBeenCalledOnce()) + expect(existing ? mocks.existing : mocks.bootstrap).toHaveBeenCalledOnce() + expect(mocks.loop).not.toHaveBeenCalled() + expect(mocks.onUserMessage).not.toHaveBeenCalled() + mocks.receiveUserMessage('early prompt', 'first') + rpc = getConfigHandler()({ effort: 'max' }).then((result) => { + rpcApplied = true + return result + }) + await Promise.resolve() + expect(rpcApplied).toBe(false) + expect(mocks.listModels).toHaveBeenCalledOnce() + + resolveCatalog({ success: true, availableModels: catalog }) + await running + await expect(rpc).resolves.toEqual({ applied: { model: 'gemini-4-argon', effort: 'max' } }) + expect(mocks.cleanup).toHaveBeenCalledOnce() + }) + + it.each([undefined, 'auto', 'default'])('does not probe the catalog for default model %s', async (model) => { + await runAgy({ model, effort: 'high', workingDirectory: '/tmp' }) + expect(mocks.listModels).not.toHaveBeenCalled() + expect(mocks.loop).toHaveBeenCalledWith(expect.objectContaining({ model: undefined, effort: 'high' })) + }) + + it('cleans up a bootstrapped session if catalog initialization rejects', async () => { + mocks.listModels.mockRejectedValueOnce(new Error('catalog unavailable')) + await runAgy({ model: 'gemini-4-argon-medium', workingDirectory: '/tmp' }) + expect(mocks.bootstrap).toHaveBeenCalledOnce() + expect(mocks.loop).not.toHaveBeenCalled() + expect(mocks.cleanup).toHaveBeenCalledOnce() + expect(mocks.markCrash).toHaveBeenCalledWith(expect.objectContaining({ message: 'catalog unavailable' })) + mocks.markCrash.mockClear() + }) + + it('applies RPC effort, acknowledges normalization, and preserves earlier queue snapshots', async () => { + mocks.loop.mockImplementation(async ({ messageQueue }: { messageQueue: MessageQueue2 }) => { + const send = mocks.onUserMessage.mock.calls[0]![0] + const handler = getConfigHandler() + send({ content: { text: 'before' } }, 'first') + await expect(handler({ effort: 'max' })).resolves.toEqual({ + applied: { model: 'gemini-4-argon', effort: 'max' }, + }) + send({ content: { text: 'after' } }, 'second') + expect((await messageQueue.waitForMessagesAndGetAsString())?.mode) + .toMatchObject({ model: 'gemini-4-argon', effort: 'medium' }) + expect((await messageQueue.waitForMessagesAndGetAsString())?.mode) + .toMatchObject({ model: 'gemini-4-argon', effort: 'max' }) + + await expect(handler({ model: 'gemini-4-argon-high' })).resolves.toEqual({ + applied: { model: 'gemini-4-argon', effort: 'high' }, + }) + await expect(handler({ model: 'gemini-4-argon-high', effort: null })).resolves.toEqual({ + applied: { model: 'gemini-4-argon', effort: null }, + }) + await expect(handler({ model: 'gpt-oss-120b-medium' })).resolves.toEqual({ + applied: { model: 'gpt-oss-120b-medium', effort: null }, + }) + }) + await runAgy({ model: 'gemini-4-argon-medium', workingDirectory: '/tmp' }) + expect(mocks.cleanup).toHaveBeenCalledOnce() + }) + + it('rejects an invalid RPC effort before changing runtime state', async () => { + mocks.loop.mockImplementation(async ({ messageQueue }: { messageQueue: MessageQueue2 }) => { + await expect(getConfigHandler()({ model: 'gpt-oss-120b-medium', effort: 'extreme' })) + .rejects.toThrow('Invalid Antigravity effort') + mocks.onUserMessage.mock.calls[0]![0]({ content: { text: 'still original' } }, 'first') + expect((await messageQueue.waitForMessagesAndGetAsString())?.mode) + .toMatchObject({ model: 'gemini-4-argon', effort: 'medium' }) + }) + await runAgy({ model: 'gemini-4-argon-medium', workingDirectory: '/tmp' }) + }) +}) diff --git a/cli/src/agy/runAgy.ts b/cli/src/agy/runAgy.ts index a0b14f03..35c4f8e1 100644 --- a/cli/src/agy/runAgy.ts +++ b/cli/src/agy/runAgy.ts @@ -13,6 +13,9 @@ import { registerSessionConfigRpc } from '@/agent/sessionConfigRpc'; import { formatMessageWithAttachments } from '@/utils/attachmentFormatter'; import { getInvokedCwd } from '@/utils/invokedCwd'; import type { SessionEffort, SessionModel } from '@/api/types'; +import { splitAgyModelSelection } from '@hapi/protocol'; +import { listAgyModels } from '@/modules/common/agyModels'; +import { normalizeAgyModelSelection } from './utils/agyModelSelection'; export async function runAgy(opts: { startedBy?: 'runner' | 'terminal'; @@ -56,7 +59,7 @@ export async function runAgy(opts: { tag: `__hapi_agy_${randomUUID()}`, agentState: initialState, model: initialModel ?? undefined, - effort: opts.effort ?? undefined, + effort: opts.effort, reservedSessionId: opts.reservedSessionId }); const { api, session } = bootstrap; @@ -69,7 +72,7 @@ export async function runAgy(opts: { let currentPermissionMode: PermissionMode = opts.permissionMode ?? 'request-review'; let sessionModel: SessionModel = initialModel; - let sessionEffort: SessionEffort | undefined = opts.effort ?? undefined; + let sessionEffort: SessionEffort = opts.effort ?? null; const sessionWrapperRef: { current: any | null } = { current: null }; @@ -88,6 +91,18 @@ export async function runAgy(opts: { let crashed = false; try { + // Bootstrap must report to the runner before a potentially slow catalog + // probe. ApiSessionClient buffers early messages until onUserMessage is + // registered below, after the launch selection has been normalized. + const initialized = (async () => { + const catalog = splitAgyModelSelection(initialModel).model + ? await listAgyModels() + : undefined; + const selection = normalizeAgyModelSelection(initialModel, opts.effort, catalog?.availableModels ?? []); + sessionModel = selection.model; + sessionEffort = selection.effort; + })(); + const syncSessionMode = () => { const sessionInstance = sessionWrapperRef.current; if (!sessionInstance) return; @@ -98,19 +113,6 @@ export async function runAgy(opts: { logger.debug(`[agy] Synced session config: permissionMode=${currentPermissionMode}, model=${sessionModel ?? '(default)'}`); }; - session.onUserMessage((message, localId) => { - const formattedText = formatMessageWithAttachments(message.content.text, message.content.attachments); - // Snapshot the spawn config at ENQUEUE time: a prompt queued while the - // session runs on model A must not run on B if the user switches the - // live session model before dequeue. - const mode: AgyMode = { - permissionMode: currentPermissionMode, - model: sessionModel, - effort: sessionEffort, - }; - messageQueue.push(formattedText, mode, localId); - }); - session.onCancelQueuedMessage((localId) => { // A batch held in the driver's retry backoff is outside MessageQueue2; // the driver-owned cancel handles it (returns true when removed). @@ -128,17 +130,48 @@ export async function runAgy(opts: { rpcHandlerManager: session.rpcHandlerManager, flavor: 'agy', modelMode: 'nullable', + effortMode: 'nullable', onApply: async (config) => { + // A config request received during startup must apply after the + // initial selection, rather than be overwritten when probing ends. + await initialized; + let selection; + if (config.model !== undefined || config.effort !== undefined) { + const models = await listAgyModels(); + const model = config.model === undefined ? sessionModel : config.model; + const effort = config.effort !== undefined + ? config.effort + : config.model !== undefined && splitAgyModelSelection(model).effort + ? undefined + : sessionEffort; + selection = normalizeAgyModelSelection(model, effort, models.availableModels ?? []); + } if (config.permissionMode !== undefined) { currentPermissionMode = config.permissionMode; } - if (config.model !== undefined) { - sessionModel = config.model; + if (selection) { + sessionModel = selection.model; + sessionEffort = selection.effort; } + return selection; }, onAfterApply: syncSessionMode }); + await initialized; + + session.onUserMessage((message, localId) => { + const formattedText = formatMessageWithAttachments(message.content.text, message.content.attachments); + // Snapshot config when buffered/new messages enter the queue, so a + // later model or effort switch cannot change an already queued turn. + const mode: AgyMode = { + permissionMode: currentPermissionMode, + model: sessionModel, + effort: sessionEffort, + }; + messageQueue.push(formattedText, mode, localId); + }); + await agyLoop({ path: workingDirectory, startingMode, diff --git a/cli/src/agy/utils/agyModelSelection.test.ts b/cli/src/agy/utils/agyModelSelection.test.ts new file mode 100644 index 00000000..da73be5e --- /dev/null +++ b/cli/src/agy/utils/agyModelSelection.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from 'vitest' +import { normalizeAgyModelSelection } from './agyModelSelection' + +const catalog = [ + { modelId: 'gemini-4-argon-medium', name: 'Gemini 4 Argon (Medium)' }, + { modelId: 'gemini-4-argon-high', name: 'Gemini 4 Argon (High)' }, + { modelId: 'gemini-4-argon-xhigh', name: 'Gemini 4 Argon (Xhigh)' }, + { modelId: 'gemini-4-argon-max', name: 'Gemini 4 Argon (Max)' }, + { modelId: 'gpt-oss-120b-medium', name: 'GPT-OSS 120B (Medium)' }, + { modelId: 'claude-opus-4-6-thinking', name: 'Claude Opus 4.6 (Thinking)' }, +] + +describe('normalizeAgyModelSelection', () => { + it('normalizes a launch/resume variant and lets an explicit effort override its suffix', () => { + expect(normalizeAgyModelSelection('gemini-4-argon-medium', 'high', catalog)) + .toEqual({ model: 'gemini-4-argon', effort: 'high' }) + expect(normalizeAgyModelSelection('gemini-4-argon-medium', undefined, catalog)) + .toEqual({ model: 'gemini-4-argon', effort: 'medium' }) + }) + + it('distinguishes explicit default effort from an omitted effort', () => { + expect(normalizeAgyModelSelection('gemini-4-argon-medium', null, catalog)) + .toEqual({ model: 'gemini-4-argon', effort: null }) + }) + + it.each(['xhigh', 'max'])('accepts the native %s effort when the catalog offers it', (effort) => { + expect(normalizeAgyModelSelection('gemini-4-argon', effort, catalog)) + .toEqual({ model: 'gemini-4-argon', effort }) + }) + + it('rejects unsupported or invalid effort levels', () => { + expect(() => normalizeAgyModelSelection('gemini-4-argon', 'low', catalog)) + .toThrow('does not support effort low') + expect(() => normalizeAgyModelSelection(null, 'extreme', catalog)) + .toThrow('Invalid Antigravity effort') + }) + + it.each(['gpt-oss-120b-medium', 'claude-opus-4-6-thinking'])( + 'keeps fixed model %s intact and clears a stale effort', (model) => { + expect(normalizeAgyModelSelection(model, 'high', catalog)).toEqual({ model, effort: null }) + }, + ) + + it('preserves custom names without guessing that their suffix is an effort', () => { + expect(normalizeAgyModelSelection('custom-high', 'medium', [])) + .toEqual({ model: 'custom-high', effort: 'medium' }) + }) + + it('keeps an unknown native wire id when its configurable base is not in the catalog', () => { + expect(normalizeAgyModelSelection('gemini-future-medium', undefined, [])) + .toEqual({ model: 'gemini-future-medium', effort: null }) + expect(() => normalizeAgyModelSelection('gemini-future-medium', 'high', [])) + .toThrow('refresh the Antigravity model catalog first') + expect(() => normalizeAgyModelSelection('gemini-future-medium', null, [])) + .toThrow('refresh the Antigravity model catalog first') + }) + + it('supports an effort with the native default model', () => { + expect(normalizeAgyModelSelection(undefined, 'high', catalog)).toEqual({ model: null, effort: 'high' }) + }) +}) diff --git a/cli/src/agy/utils/agyModelSelection.ts b/cli/src/agy/utils/agyModelSelection.ts new file mode 100644 index 00000000..23122ef4 --- /dev/null +++ b/cli/src/agy/utils/agyModelSelection.ts @@ -0,0 +1,49 @@ +import { + AGY_EFFORT_LEVELS, + getAgyModelChoices, + splitAgyModelSelection, + type AgyEffortLevel, + type AgyModelSummary, +} from '@hapi/protocol' + +export type AgyModelSelection = { model: string | null; effort: AgyEffortLevel | null } + +/** Normalize launch/resume and RPC config against the catalog, before it is queued. */ +export function normalizeAgyModelSelection( + model: string | null | undefined, + effort: string | null | undefined, + catalog: readonly AgyModelSummary[], +): AgyModelSelection { + if (effort != null && !(AGY_EFFORT_LEVELS as readonly string[]).includes(effort)) { + throw new Error(`Invalid Antigravity effort: ${effort}`) + } + const split = splitAgyModelSelection(model) + const choices = getAgyModelChoices(catalog) + const originalModel = model?.trim() || null + const choice = choices.find((candidate) => candidate.modelId === originalModel) + ?? choices.find((candidate) => candidate.modelId === split.model) + + // A catalog entry with no variants is a fixed model. Do not turn its name + // into a base model that agy may not support, or carry a previous model's effort. + if (choice && choice.supportedEfforts.length === 0) { + return { model: choice.modelId, effort: null } + } + const selectedEffort = effort === undefined ? split.effort : effort as AgyEffortLevel | null + if (choice) { + if (selectedEffort && !choice.supportedEfforts.includes(selectedEffort)) { + throw new Error(`Antigravity model ${choice.modelId} does not support effort ${selectedEffort}`) + } + return { model: choice.modelId, effort: selectedEffort } + } + + // An unavailable/stale catalog cannot prove a native suffix model has a + // configurable base. Keep its exact wire id unless the requested effort + // would conflict; custom model names are never rewritten by suffix guessing. + if (split.effort) { + if (effort !== undefined && effort !== split.effort) { + throw new Error(`Cannot change effort for ${originalModel}: refresh the Antigravity model catalog first`) + } + return { model: originalModel, effort: null } + } + return { model: split.model, effort: selectedEffort } +} diff --git a/cli/src/api/apiSession.test.ts b/cli/src/api/apiSession.test.ts index a53e9511..a885e884 100644 --- a/cli/src/api/apiSession.test.ts +++ b/cli/src/api/apiSession.test.ts @@ -170,6 +170,70 @@ function triggerIncomingUserMessage( }) } +describe('ApiSessionClient input buffered during initialization', () => { + function message(text: string, localId: string, seq: number) { + return { + id: `message-${seq}`, seq, localId, + content: { role: 'user', content: { type: 'text', text }, meta: { sentFrom: 'webapp' } }, + } + } + + it.each([false, true])('cancels buffered input before a user-message handler is ready (callback=%s)', async (withCallback) => { + socketHarness.sockets.length = 0 + const client = new ApiSessionClient('token', createSession({ namespace: 'default' })) + const socket = socketHarness.sockets[0]! + const update = socket.listeners.get('update')![0]! + const cancel = vi.fn(() => false) + if (withCallback) client.onCancelQueuedMessage(cancel) + await update({ body: { t: 'new-message', message: message('cancel me', 'local-1', 1) } }) + await update({ body: { t: 'new-message', message: message('keep me', 'local-2', 2) } }) + const ack = vi.fn() + + await update({ body: { t: 'cancel-queued-message', localId: 'local-1' } }, ack) + expect(ack).toHaveBeenCalledWith({ removed: true, inFlight: false, indeterminate: false, consumed: false }) + expect(cancel).not.toHaveBeenCalled() + const onMessage = vi.fn() + client.onUserMessage(onMessage) + expect(onMessage).toHaveBeenCalledTimes(1) + expect(onMessage).toHaveBeenCalledWith(expect.objectContaining({ content: { type: 'text', text: 'keep me' } }), 'local-2') + client.close() + }) + + it.each([false, true])('replaces buffered input on retry without flushing twice (callback=%s)', async (withCallback) => { + socketHarness.sockets.length = 0 + const client = new ApiSessionClient('token', createSession({ namespace: 'default' })) + const socket = socketHarness.sockets[0]! + const update = socket.listeners.get('update')![0]! + const cancel = vi.fn(() => 'consumed' as const) + if (withCallback) client.onCancelQueuedMessage(cancel) + await update({ body: { t: 'new-message', message: message('original', 'local-1', 1) } }) + const ack = vi.fn() + await update({ body: { t: 'retry-queued-message', localId: 'local-1', message: message('replacement', 'local-1', 1) } }, ack) + expect(ack).toHaveBeenCalledWith({ removed: false, accepted: true }) + expect(cancel).not.toHaveBeenCalled() + const onMessage = vi.fn() + client.onUserMessage(onMessage) + expect(onMessage).toHaveBeenCalledTimes(1) + expect(onMessage).toHaveBeenCalledWith(expect.objectContaining({ content: { type: 'text', text: 'replacement' } }), 'local-1') + client.close() + }) + + it.each(['in-flight', 'consumed', 'indeterminate'] as const)('keeps %s cancellation semantics after input leaves the buffer', async (result) => { + socketHarness.sockets.length = 0 + const client = new ApiSessionClient('token', createSession({ namespace: 'default' })) + const update = socketHarness.sockets[0]!.listeners.get('update')![0]! + const cancel = vi.fn(async () => result) + client.onCancelQueuedMessage(cancel) + const ack = vi.fn() + await update({ body: { t: 'cancel-queued-message', localId: 'local-1' } }, ack) + expect(cancel).toHaveBeenCalledWith('local-1') + expect(ack).toHaveBeenCalledWith({ + removed: false, inFlight: result === 'in-flight', indeterminate: result === 'indeterminate', consumed: result === 'consumed', + }) + client.close() + }) +}) + describe('ApiSessionClient lazy materialization', () => { it('does not connect or materialize without a real user message', async () => { socketHarness.sockets.length = 0 diff --git a/cli/src/api/apiSession.ts b/cli/src/api/apiSession.ts index c7f368a3..872937e1 100644 --- a/cli/src/api/apiSession.ts +++ b/cli/src/api/apiSession.ts @@ -467,8 +467,8 @@ export class ApiSessionClient extends EventEmitter { // Explicit user retry: release any held in-memory // reservation and bypass the normal message-id dedup. let accepted = true - if (data.body.localId && this.cancelQueuedMessageCallback) { - const cancellation = this.cancelQueuedMessageCallback(data.body.localId) + if (data.body.localId) { + const cancellation = this.cancelQueuedMessage(data.body.localId) const cancelled = cancellation instanceof Promise ? await cancellation : cancellation accepted = cancelled !== 'in-flight' && cancelled !== 'consumed' if (cancelled === 'indeterminate') { @@ -487,8 +487,8 @@ export class ApiSessionClient extends EventEmitter { } if (data.body.t === 'cancel-queued-message') { - const cancellation = (data.body.localId && this.cancelQueuedMessageCallback) - ? this.cancelQueuedMessageCallback(data.body.localId) + const cancellation = data.body.localId + ? this.cancelQueuedMessage(data.body.localId) : false const result = cancellation instanceof Promise ? await cancellation : cancellation // 'in-flight' = the row is inside an async steer: not @@ -737,6 +737,15 @@ export class ApiSessionClient extends EventEmitter { this.retryQueuedMessageCallback = callback } + private cancelQueuedMessage(localId: string): QueueCancelResult | Promise { + const remaining = this.pendingMessages.filter((pending) => pending.localId !== localId) + if (remaining.length !== this.pendingMessages.length) { + this.pendingMessages = remaining + return true + } + return this.cancelQueuedMessageCallback?.(localId) ?? false + } + private enqueueUserMessage(message: UserMessage, localId?: string): void { if (this.pendingMessageCallback) { this.pendingMessageCallback(message, localId) diff --git a/docs/api/client-contract/rest.md b/docs/api/client-contract/rest.md index 989577eb..683f16d9 100644 --- a/docs/api/client-contract/rest.md +++ b/docs/api/client-contract/rest.md @@ -117,8 +117,8 @@ Source: `hub/src/web/routes/sessions.ts`; flavor gates in `shared/src/modes.ts` | Method & path | Request | Applies to | |---|---|---| | `POST /api/sessions/:id/permission-mode` | `{mode: PermissionMode}` | All flavors except `pi` and `dsh` (per-flavor allowed sets in `modes.ts`) | -| `POST /api/sessions/:id/model` | `{model: string \| {provider, modelId} \| null}` | Flavors with `supportsModelChange` (not `dsh`); remote-only for codex/cursor/grok | -| `POST /api/sessions/:id/effort` | `{effort: string \| null}` | claude, grok, pi (`supportsEffort`) | +| `POST /api/sessions/:id/model` | `{model: string \| {provider, modelId} \| null, effort?: string \| null}` | Flavors with `supportsModelChange` (not `dsh`); remote-only for codex/cursor/grok. Only claude and agy accept `effort` with a model change. | +| `POST /api/sessions/:id/effort` | `{effort: string \| null}` | agy, claude, grok, pi (`supportsEffort`) | | `POST /api/sessions/:id/model-reasoning-effort` | `{modelReasoningEffort: string \| null}` | codex, opencode (remote-only) | | `POST /api/sessions/:id/service-tier` | `{serviceTier: 'fast' \| 'standard'}` | codex (remote-only) | | `POST /api/sessions/:id/collaboration-mode` | `{mode: 'default' \| 'plan'}` | codex (remote-only) | diff --git a/docs/guide/agents.md b/docs/guide/agents.md index 4beb36da..c9a33c97 100644 --- a/docs/guide/agents.md +++ b/docs/guide/agents.md @@ -309,6 +309,14 @@ the prompt is loaded by DSH through its own `skill` tool and catalog. - **Kimi** (`hapi kimi`) — Moonshot AI's Kimi CLI over ACP (`kimi acp`). [MoonshotAI/kimi-cli](https://github.com/MoonshotAI/kimi-cli) - **OpenCode** (`hapi opencode`) — the open-source OpenCode agent over ACP (`opencode acp`). [opencode.ai](https://opencode.ai) - **Antigravity** (`hapi agy`) — Google's Antigravity CLI (`agy`), driven headlessly via print mode: every turn spawns `agy -p --conversation --output-format stream-json`, and NDJSON events (init / step_update / result) are streamed into the chat. There is no PTY/TUI wrapper and no hook-based permission bridge: permission handling uses agy's own `settings.json` allow/deny rules (`request-review`) or `--dangerously-skip-permissions` (`always-proceed`). Tool calls that lack an allow-rule are auto-denied by agy and surfaced as a chat hint. MCP servers are configured the standard agy way — in the user's global `~/.gemini/config/mcp_config.json` or a workspace `.agents/mcp_config.json` — and are loaded natively by agy in headless mode (no HAPI injection). Remote-only — there is no local terminal input path. [Google Antigravity](https://antigravity.google) + + In the web model picker, models with multiple effort variants appear once, + with a separate effort selector showing the levels in the machine's catalog. + For example, choose **Gemini 4 Argon** and **High**, or launch with + `hapi agy --model gemini-4-argon --effort high`. Models with only one listed + variant keep their original name and have no effort selector. Model and effort + changes apply to subsequently sent messages; queued messages keep their settings. + - **Pi** (`hapi pi`) — the Pi coding agent running as `pi --mode rpc` (JSON-line RPC over piped stdio); remote-control only, no local TUI input path. [earendil-works/pi](https://github.com/earendil-works/pi) HAPI translates a subset of Pi's TUI slash commands to native Pi RPC calls, so they work from the web chat as well: diff --git a/hub/src/web/routes/sessions.test.ts b/hub/src/web/routes/sessions.test.ts index 50e07914..0eaff805 100644 --- a/hub/src/web/routes/sessions.test.ts +++ b/hub/src/web/routes/sessions.test.ts @@ -829,6 +829,23 @@ describe('sessions routes', () => { ]) }) + it.each(['high', null])('applies an Antigravity model and effort %s atomically', async (effort) => { + const { app, applySessionConfigCalls } = createApp(createSession({ + metadata: { path: '/tmp/project', host: 'localhost', flavor: 'agy' } + })) + + const response = await app.request('/api/sessions/session-1/model', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ model: 'gemini-4-argon', effort }) + }) + + expect(response.status).toBe(200) + expect(applySessionConfigCalls).toEqual([ + ['session-1', { model: 'gemini-4-argon', effort }] + ]) + }) + it('rejects an effort sent with a model change for Pi, which applies the two separately', async () => { const session = createSession({ metadata: { path: '/tmp/project', host: 'localhost', flavor: 'pi' } @@ -1027,6 +1044,22 @@ describe('sessions routes', () => { expect(applySessionConfigCalls).toEqual([]) }) + it('applies effort changes for Antigravity sessions', async () => { + const { app, applySessionConfigCalls } = createApp(createSession({ + metadata: { path: '/tmp/project', host: 'localhost', flavor: 'agy' } + })) + const response = await app.request('/api/sessions/session-1/effort', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ effort: 'high' }) + }) + + expect(response.status).toBe(200) + expect(applySessionConfigCalls).toEqual([ + ['session-1', { effort: 'high' }] + ]) + }) + it('applies effort changes for Claude sessions', async () => { const session = createSession({ metadata: { diff --git a/hub/src/web/routes/sessions.ts b/hub/src/web/routes/sessions.ts index 95dc2279..7c91fdb7 100644 --- a/hub/src/web/routes/sessions.ts +++ b/hub/src/web/routes/sessions.ts @@ -697,12 +697,11 @@ export function createSessionsRoutes(getSyncEngine: () => SyncEngine | null): Ho } } - // Only Claude applies a model and an effort as one config change; Pi - // commits the model before setting its thinking level, so a failure in - // between would leave half of the request applied. + // Pi commits the model before setting its thinking level, so a failure + // in between would leave half of the request applied. const { model, effort } = parsed.data - if (effort !== undefined && flavor !== 'claude') { - return c.json({ error: 'Effort can only be sent with a model change for Claude sessions' }, 400) + if (effort !== undefined && flavor !== 'claude' && flavor !== 'agy') { + return c.json({ error: 'Effort can only be sent with a model change for Claude and Antigravity sessions' }, 400) } try { diff --git a/shared/src/agentConfig.test.ts b/shared/src/agentConfig.test.ts index 3fc8e0a3..9e31bbf8 100644 --- a/shared/src/agentConfig.test.ts +++ b/shared/src/agentConfig.test.ts @@ -7,6 +7,11 @@ import { } from './agentConfig' describe('agent config descriptors', () => { + test('exposes model-dependent Antigravity effort at creation and during a session', () => { + expect(getAgentConfigDescriptor('agy').fields).toContainEqual({ + id: 'effort', section: 'effort', kind: 'select', optionSource: 'model', availability: 'both' + }) + }) test('exposes the three primary fields with their intended placements', () => { const descriptor = getAgentConfigDescriptor('codex') expect(descriptor.fields.map((field) => [field.id, field.section])).toEqual([ diff --git a/shared/src/agentConfig.ts b/shared/src/agentConfig.ts index 4db886a8..db7afced 100644 --- a/shared/src/agentConfig.ts +++ b/shared/src/agentConfig.ts @@ -57,7 +57,11 @@ function fields(...fields: AgentConfigFieldDescriptor[]): AgentConfigFieldDescri } const BUILTIN_DESCRIPTORS: Record = { - agy: fields({ ...MODEL, optionSource: 'machine' }, PERMISSION), + agy: fields( + { ...MODEL, optionSource: 'machine' }, + { id: 'effort', section: 'effort', kind: 'select', optionSource: 'model', availability: 'both' }, + PERMISSION + ), claude: fields(MODEL, { id: 'effort', section: 'effort', kind: 'select', optionSource: 'static', availability: 'both' }, PERMISSION), codex: fields( { ...MODEL, optionSource: 'machine' }, diff --git a/shared/src/agyModels.test.ts b/shared/src/agyModels.test.ts new file mode 100644 index 00000000..6fb3ca18 --- /dev/null +++ b/shared/src/agyModels.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, test } from 'bun:test' +import { AGY_EFFORT_LEVELS, getAgyModelChoices, splitAgyModelSelection } from './agyModels' + +describe('splitAgyModelSelection', () => { + test('separates native model variants including newer effort levels', () => { + for (const effort of AGY_EFFORT_LEVELS) { + expect(splitAgyModelSelection(`gemini-4-argon-${effort}`)).toEqual({ model: 'gemini-4-argon', effort }) + } + expect(splitAgyModelSelection(' claude-opus-5-5-high ')).toEqual({ model: 'claude-opus-5-5', effort: 'high' }) + }) + + test('preserves base ids, thinking variants and custom model names', () => { + for (const model of ['gemini-4-argon', 'claude-opus-4-6-thinking', 'custom-high', 'provider/custom-low']) { + expect(splitAgyModelSelection(model)).toEqual({ model, effort: null }) + } + }) + + test('normalizes default selections to no explicit model', () => { + for (const model of [null, undefined, '', ' ', 'auto', 'default']) { + expect(splitAgyModelSelection(model)).toEqual({ model: null, effort: null }) + } + }) +}) + +describe('getAgyModelChoices', () => { + test('groups available variants in catalog order and sorts only supported efforts', () => { + expect(getAgyModelChoices([ + { modelId: 'gemini-4-argon-high', name: 'Gemini 4 Argon (High)' }, + { modelId: 'claude-opus-5-5-max', name: 'Claude Opus 5.5 (Max)' }, + { modelId: 'gemini-4-argon-low', name: 'Gemini 4 Argon (Low)' }, + { modelId: 'gemini-4-argon-high', name: 'Gemini 4 Argon (High)' }, + { modelId: 'claude-opus-5-5-xhigh', name: 'Claude Opus 5.5 (XHigh)' } + ])).toEqual([ + { modelId: 'gemini-4-argon', name: 'Gemini 4 Argon', supportedEfforts: ['low', 'high'] }, + { modelId: 'claude-opus-5-5', name: 'Claude Opus 5.5', supportedEfforts: ['xhigh', 'max'] } + ]) + }) + + test('keeps single variants, thinking models and custom models unchanged', () => { + expect(getAgyModelChoices([ + { modelId: 'gpt-oss-120b-medium', name: 'GPT-OSS 120B (Medium)' }, + { modelId: 'gpt-oss-120b-medium', name: 'GPT-OSS 120B (Medium)' }, + { modelId: 'claude-opus-4-6-thinking', name: 'Claude Opus 4.6 (Thinking)' }, + { modelId: 'custom-high', name: 'Custom (High)' }, + { modelId: 'custom-low', name: 'Custom (Low)' } + ])).toEqual([ + { modelId: 'gpt-oss-120b-medium', name: 'GPT-OSS 120B (Medium)', supportedEfforts: [] }, + { modelId: 'claude-opus-4-6-thinking', name: 'Claude Opus 4.6 (Thinking)', supportedEfforts: [] }, + { modelId: 'custom-high', name: 'Custom (High)', supportedEfforts: [] }, + { modelId: 'custom-low', name: 'Custom (Low)', supportedEfforts: [] } + ]) + }) + + test('uses base ids as names when the catalog has no labels', () => { + expect(getAgyModelChoices([ + { modelId: 'gemini-4-argon-medium' }, + { modelId: 'gemini-4-argon-high' }, + { modelId: 'custom' } + ])).toEqual([ + { modelId: 'gemini-4-argon', name: 'gemini-4-argon', supportedEfforts: ['medium', 'high'] }, + { modelId: 'custom', name: 'custom', supportedEfforts: [] } + ]) + }) + + test('returns no choices for an empty catalog', () => { + expect(getAgyModelChoices([])).toEqual([]) + }) +}) diff --git a/shared/src/agyModels.ts b/shared/src/agyModels.ts new file mode 100644 index 00000000..4a9054cf --- /dev/null +++ b/shared/src/agyModels.ts @@ -0,0 +1,56 @@ +import type { AgyModelSummary } from './apiTypes' + +export const AGY_EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'] as const +export type AgyEffortLevel = typeof AGY_EFFORT_LEVELS[number] + +export type AgyModelChoice = { + modelId: string + name: string + supportedEfforts: AgyEffortLevel[] +} + +export function splitAgyModelSelection(model: string | null | undefined): { + model: string | null + effort: AgyEffortLevel | null +} { + const value = model?.trim() + if (!value || value === 'auto' || value === 'default') { + return { model: null, effort: null } + } + // Custom names can end in words such as "high" without being effort variants. + const match = /^(gemini-.+|claude-.+|gpt-oss-.+)-(low|medium|high|xhigh|max)$/.exec(value) + return match + ? { model: match[1]!, effort: match[2] as AgyEffortLevel } + : { model: value, effort: null } +} + +export function getAgyModelChoices(catalog: readonly AgyModelSummary[]): AgyModelChoice[] { + const effortsByModel = new Map>() + for (const entry of catalog) { + const { model, effort } = splitAgyModelSelection(entry.modelId) + if (!model || !effort) continue + const efforts = effortsByModel.get(model) ?? new Set() + efforts.add(effort) + effortsByModel.set(model, efforts) + } + + const choices = new Map() + for (const entry of catalog) { + const { model, effort } = splitAgyModelSelection(entry.modelId) + if (!model) continue + const efforts = effortsByModel.get(model) + // A single variant (e.g. GPT-OSS Medium) does not establish adjustable effort. + const adjustable = efforts !== undefined && efforts.size > 1 + const modelId = adjustable ? model : entry.modelId + if (choices.has(modelId)) continue + const name = adjustable && effort + ? (entry.name?.replace(new RegExp(`\\s*\\(${effort}\\)$`, 'i'), '') ?? model) + : (entry.name ?? entry.modelId) + choices.set(modelId, { + modelId, + name, + supportedEfforts: adjustable ? AGY_EFFORT_LEVELS.filter((level) => efforts.has(level)) : [] + }) + } + return [...choices.values()] +} diff --git a/shared/src/flavors.test.ts b/shared/src/flavors.test.ts index b3556ead..f0f5f1e2 100644 --- a/shared/src/flavors.test.ts +++ b/shared/src/flavors.test.ts @@ -10,9 +10,9 @@ import { } from './flavors' describe('hasCapability', () => { - test('agy supports model-change but not effort', () => { + test('agy supports model-change and effort', () => { expect(hasCapability('agy', Capabilities.ModelChange)).toBe(true) - expect(hasCapability('agy', Capabilities.Effort)).toBe(false) + expect(hasCapability('agy', Capabilities.Effort)).toBe(true) }) test('claude supports model-change', () => { @@ -143,6 +143,7 @@ describe('convenience functions', () => { }) test('supportsEffort matches hasCapability', () => { + expect(supportsEffort('agy')).toBe(true) expect(supportsEffort('claude')).toBe(true) expect(supportsEffort('codex')).toBe(false) expect(supportsEffort('gemini')).toBe(false) diff --git a/shared/src/flavors.ts b/shared/src/flavors.ts index 98ba2953..191261c3 100644 --- a/shared/src/flavors.ts +++ b/shared/src/flavors.ts @@ -10,7 +10,7 @@ export type Capability = typeof Capabilities[keyof typeof Capabilities] // --- Per-flavor capability sets --- const FLAVOR_CAPS: Record> = { - agy: new Set([Capabilities.ModelChange]), + agy: new Set([Capabilities.ModelChange, Capabilities.Effort]), claude: new Set([Capabilities.ModelChange, Capabilities.Effort]), gemini: new Set([Capabilities.ModelChange]), kimi: new Set([Capabilities.ModelChange]), diff --git a/shared/src/index.ts b/shared/src/index.ts index f0528dbe..f15f4198 100644 --- a/shared/src/index.ts +++ b/shared/src/index.ts @@ -8,6 +8,7 @@ export * from './conversationHistory' export * from './effort' export * from './flavors' export * from './models' +export * from './agyModels' export * from './modes' export * from './resume' export * from './rpcMethods' diff --git a/web/src/components/AssistantChat/HappyComposer.modelEffortButtons.test.tsx b/web/src/components/AssistantChat/HappyComposer.modelEffortButtons.test.tsx index cb92327e..5ee404e1 100644 --- a/web/src/components/AssistantChat/HappyComposer.modelEffortButtons.test.tsx +++ b/web/src/components/AssistantChat/HappyComposer.modelEffortButtons.test.tsx @@ -157,6 +157,33 @@ describe('HappyComposer generic model/effort value buttons', () => { expect(screen.getByRole('button', { name: 'Settings' })).toBeTruthy() }) + it('shows the AGY model family and its available effort as separate controls', () => { + const onEffortChange = vi.fn() + renderComposer('agy', { + model: 'gemini-4-argon', effort: 'medium', + availableModelOptions: [{ value: 'gemini-4-argon', label: 'Gemini 4 Argon' }], + availableEffortOptions: [{ value: 'medium', name: 'Medium' }, { value: 'high', name: 'High' }], + onEffortChange, + }) + expect(screen.getByRole('button', { name: 'Gemini 4 Argon' })).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: 'Medium' })) + expect(screen.queryByRole('button', { name: 'Low' })).toBeNull() + fireEvent.click(screen.getByRole('button', { name: 'High' })) + expect(onEffortChange).toHaveBeenCalledWith('high') + }) + + it('hides effort for a fixed AGY model even if a stale effort is stored', () => { + renderComposer('agy', { + model: 'gpt-oss-120b-medium', effort: 'high', + availableModelOptions: [{ value: 'gpt-oss-120b-medium', label: 'GPT-OSS 120B (Medium)' }], + availableEffortOptions: [], + }) + expect(screen.getByRole('button', { name: 'GPT-OSS 120B (Medium)' })).toBeTruthy() + expect(screen.queryByRole('button', { name: 'High' })).toBeNull() + fireEvent.click(screen.getByRole('button', { name: 'Settings' })) + expect(screen.queryByText('Effort')).toBeNull() + }) + it('heads grouped model rows with their group name once', () => { renderComposer('claude', { model: 'opus', diff --git a/web/src/components/AssistantChat/HappyComposer.tsx b/web/src/components/AssistantChat/HappyComposer.tsx index f389904b..3907e18b 100644 --- a/web/src/components/AssistantChat/HappyComposer.tsx +++ b/web/src/components/AssistantChat/HappyComposer.tsx @@ -1142,7 +1142,7 @@ export function HappyComposer(props: { const claudeEffortOptions = useMemo( () => agentFlavor === 'pi' ? getPiThinkingLevelOptions(effort, selectedPiModel?.thinkingLevelMap) - : agentFlavor === 'grok' && availableEffortOptions && availableEffortOptions.length > 0 + : (agentFlavor === 'grok' || agentFlavor === 'agy') && availableEffortOptions && availableEffortOptions.length > 0 ? [ { value: null, label: 'Default' }, ...availableEffortOptions.map((option) => ({ @@ -1728,7 +1728,8 @@ export function HappyComposer(props: { // fallback levels would mutate a set_thinking_level the model may reject. const piEffortUnavailable = agentFlavor === 'pi' && (!selectedPiModel || selectedPiModel.reasoning === false) - const showEffortSettings = Boolean(onEffortChange && supportsEffort(agentFlavor) && !piEffortUnavailable) + const showEffortSettings = Boolean(onEffortChange && supportsEffort(agentFlavor) && !piEffortUnavailable + && (agentFlavor !== 'agy' || availableEffortOptions?.length)) const showFastModeSettings = Boolean(onServiceTierChange) const showModelAreaSettings = showModelSettings || showModelEffortSettings || showModelReasoningEffortSettings || showEffortSettings const showOtherSettings = showFastModeSettings || showCollaborationSettings || showCopilotAgentModeSettings @@ -1814,6 +1815,7 @@ export function HappyComposer(props: { const effortValueLabel = useMemo(() => { if (isNarrowViewport) return undefined if (!onEffortChange || !supportsEffort(agentFlavor)) return undefined + if (agentFlavor === 'agy' && !availableEffortOptions?.length) return undefined // Pi: without a resolved catalog entry there is no capability map to // derive levels from; hide the button until the selected model is known. if (agentFlavor === 'pi') { @@ -1827,7 +1829,7 @@ export function HappyComposer(props: { } const option = claudeEffortOptions.find((candidate) => candidate.value === effort) return option?.label ?? (effort ? effort : undefined) - }, [isNarrowViewport, onEffortChange, agentFlavor, selectedPiModel, effort, claudeEffortOptions]) + }, [isNarrowViewport, onEffortChange, agentFlavor, selectedPiModel, effort, claudeEffortOptions, availableEffortOptions]) // Wrapper for DOM onClick consumers: never leak the MouseEvent into the // `section` parameter (the gear must always open the full sheet). diff --git a/web/src/components/AssistantChat/modelOptions.ts b/web/src/components/AssistantChat/modelOptions.ts index 2ddebc14..aaa8d6f8 100644 --- a/web/src/components/AssistantChat/modelOptions.ts +++ b/web/src/components/AssistantChat/modelOptions.ts @@ -1,4 +1,4 @@ -import { getAgyModelLabel, getClaudeModelChoices, getClaudeModelLabel } from '@hapi/protocol' +import { getAgyModelChoices, getAgyModelLabel, getClaudeModelChoices, getClaudeModelLabel } from '@hapi/protocol' import type { ClaudeModelSummary } from '@hapi/protocol/apiTypes' import { MODEL_OPTIONS } from '@/components/NewSession/types' import { CURSOR_AUTO_MODEL_LABEL } from '@/lib/cursorModelOptions' @@ -111,10 +111,9 @@ function getAgyModelOptions(currentModel?: string | null, customOptions?: ModelO const machineOptions = (customOptions ?? []).filter((option) => Boolean(option.value)) const options = machineOptions.length > 0 ? machineOptions - : MODEL_OPTIONS.agy.filter((m) => m.value !== 'auto').map((m) => ({ - value: m.value, - label: m.label - })) + : getAgyModelChoices(MODEL_OPTIONS.agy.filter((m) => m.value !== 'auto').map((m) => ({ + modelId: m.value, name: m.label + }))).map((m) => ({ value: m.modelId, label: m.name })) // A session can be running a model the machine no longer lists. It stays // selectable; the lookup only keeps a known preset readable. return withCurrentModelOption(options, currentModel, getAgyModelLabel) diff --git a/web/src/components/NewSession/EffortField.test.tsx b/web/src/components/NewSession/EffortField.test.tsx index 3aa270d4..d464c6c1 100644 --- a/web/src/components/NewSession/EffortField.test.tsx +++ b/web/src/components/NewSession/EffortField.test.tsx @@ -118,7 +118,18 @@ describe('EffortField', () => { expect(values).not.toContain('max') }) - it('renders nothing for agents without an effort field', () => { + it('shows only the selected AGY family efforts and forwards a change', () => { + const onChange = vi.fn() + const { container } = render() + const select = container.querySelector('select') as HTMLSelectElement + expect(Array.from(select.options).map((option) => option.value)).toEqual(['auto', 'medium', 'high']) + fireEvent.change(select, { target: { value: 'high' } }) + expect(onChange).toHaveBeenCalledWith('high') + }) + + it('hides AGY effort until the selected model has adjustable levels', () => { const { container } = render( ) diff --git a/web/src/components/NewSession/EffortField.tsx b/web/src/components/NewSession/EffortField.tsx index b5d674eb..78a16f77 100644 --- a/web/src/components/NewSession/EffortField.tsx +++ b/web/src/components/NewSession/EffortField.tsx @@ -17,6 +17,7 @@ export type EffortFieldProps = { isDisabled: boolean /** Model-dependent launch-effort options (Grok). */ grokOptions?: Array<{ value: string; label: string }> + agyOptions?: Array<{ value: string; label: string }> /** Launch-effort options the selected Claude model accepts; undefined = every level. */ claudeOptions?: Array<{ value: string; label: string }> /** Model-dependent reasoning-effort options (Codex). */ @@ -49,7 +50,10 @@ export function EffortField(props: EffortFieldProps) { const isReasoningEffort = props.agent === 'codex' || props.agent === 'opencode' let options: Array<{ value: string; label: string }> - if (props.agent === 'grok') { + if (props.agent === 'agy') { + if (!props.agyOptions?.length) return null + options = [{ value: 'auto', label: t('newSession.model.default') }, ...props.agyOptions] + } else if (props.agent === 'grok') { options = props.grokOptions ?? GROK_EFFORT_OPTIONS } else if (props.agent === 'pi') { if (props.piSelectedModel?.reasoning === false) { diff --git a/web/src/components/NewSession/index.test.tsx b/web/src/components/NewSession/index.test.tsx index 89fd0da7..ccc22dfb 100644 --- a/web/src/components/NewSession/index.test.tsx +++ b/web/src/components/NewSession/index.test.tsx @@ -264,16 +264,26 @@ vi.mock('./OpencodeModelSelector', () => ({ ) })) vi.mock('./AgyModelSelector', () => ({ - AgyModelSelector: (props: { selectedModel: string | null; onModelChange: (model: string | null) => void }) => ( + AgyModelSelector: (props: { selectedModel: string | null; availableModels: Array<{ modelId: string; name?: string }>; onModelChange: (model: string | null) => void }) => ( + <> + + ) })) vi.mock('./EffortField', () => ({ - EffortField: (props: { effort: string; reasoningEffort: string; opencodeVariantOptions?: string[] | null; onReasoningEffortChange: (v: string) => void }) => ( + EffortField: (props: { effort: string; reasoningEffort: string; agyOptions?: Array<{ value: string; label: string }>; onEffortChange: (value: string) => void; opencodeVariantOptions?: string[] | null; onReasoningEffortChange: (v: string) => void }) => ( <>
{props.effort}
+ {props.agyOptions?.length ? : null}
{props.opencodeVariantOptions?.join(',') ?? 'static'}