Merge branch 'main' into fix/default-theme-256

This commit is contained in:
Mark McLaughlin
2026-03-24 15:17:10 -07:00
committed by GitHub
25 changed files with 291 additions and 125 deletions
@@ -29,6 +29,7 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => {
await importOriginal<typeof import('@google/gemini-cli-core')>();
return {
...actual,
PRIORITY_YOLO_ALLOW_ALL: 998,
Config: vi.fn().mockImplementation((params) => {
const mockConfig = {
...params,
@@ -341,11 +342,11 @@ describe('loadConfig', () => {
);
});
it('should default enableAgents to false when not provided', async () => {
it('should default enableAgents to true when not provided', async () => {
await loadConfig(mockSettings, mockExtensionLoader, taskId);
expect(Config).toHaveBeenCalledWith(
expect.objectContaining({
enableAgents: false,
enableAgents: true,
}),
);
});
+1 -1
View File
@@ -128,7 +128,7 @@ export async function loadConfig(
interactive: !isHeadlessMode(),
enableInteractiveShell: !isHeadlessMode(),
ptyInfo: 'auto',
enableAgents: settings.experimental?.enableAgents ?? false,
enableAgents: settings.experimental?.enableAgents ?? true,
};
const fileService = new FileDiscoveryService(workspaceDir, {
@@ -400,7 +400,7 @@ describe('SettingsSchema', () => {
expect(setting).toBeDefined();
expect(setting.type).toBe('boolean');
expect(setting.category).toBe('Experimental');
expect(setting.default).toBe(false);
expect(setting.default).toBe(true);
expect(setting.requiresRestart).toBe(true);
expect(setting.showInDialog).toBe(false);
expect(setting.description).toBe('Enable local and remote subagents.');
+11 -1
View File
@@ -1208,6 +1208,16 @@ const SETTINGS_SCHEMA = {
'Disable user input on browser window during automation.',
showInDialog: false,
},
maxActionsPerTask: {
type: 'number',
label: 'Max Actions Per Task',
category: 'Advanced',
requiresRestart: false,
default: 100,
description:
'The maximum number of tool calls allowed per browser task. Enforcement is hard: the agent will be terminated when the limit is reached.',
showInDialog: false,
},
confirmSensitiveActions: {
type: 'boolean',
label: 'Confirm Sensitive Actions',
@@ -1932,7 +1942,7 @@ const SETTINGS_SCHEMA = {
label: 'Enable Agents',
category: 'Experimental',
requiresRestart: true,
default: false,
default: true,
description: 'Enable local and remote subagents.',
showInDialog: false,
},
+4 -1
View File
@@ -66,7 +66,10 @@ beforeEach(() => {
? stackLines.slice(lastReactFrameIndex + 1).join('\n')
: stackLines.slice(1).join('\n');
if (relevantStack.includes('OverflowContext.tsx')) {
if (
relevantStack.includes('OverflowContext.tsx') ||
relevantStack.includes('useTimedMessage.ts')
) {
return;
}
+9 -9
View File
@@ -617,7 +617,7 @@ kind: remote
name: oauth2-agent
agent_card_url: https://example.com/card
auth:
type: oauth2
type: oauth
client_id: $MY_OAUTH_CLIENT_ID
scopes:
- read
@@ -630,7 +630,7 @@ auth:
kind: 'remote',
name: 'oauth2-agent',
auth: {
type: 'oauth2',
type: 'oauth',
client_id: '$MY_OAUTH_CLIENT_ID',
scopes: ['read', 'write'],
},
@@ -643,7 +643,7 @@ kind: remote
name: oauth2-full-agent
agent_card_url: https://example.com/card
auth:
type: oauth2
type: oauth
client_id: my-client-id
client_secret: my-client-secret
scopes:
@@ -659,7 +659,7 @@ auth:
kind: 'remote',
name: 'oauth2-full-agent',
auth: {
type: 'oauth2',
type: 'oauth',
client_id: 'my-client-id',
client_secret: 'my-client-secret',
scopes: ['openid', 'profile'],
@@ -675,7 +675,7 @@ kind: remote
name: oauth2-minimal-agent
agent_card_url: https://example.com/card
auth:
type: oauth2
type: oauth
---
`);
const result = await parseAgentMarkdown(filePath);
@@ -684,7 +684,7 @@ auth:
kind: 'remote',
name: 'oauth2-minimal-agent',
auth: {
type: 'oauth2',
type: 'oauth',
},
});
});
@@ -695,7 +695,7 @@ kind: remote
name: invalid-oauth2-agent
agent_card_url: https://example.com/card
auth:
type: oauth2
type: oauth
client_id: my-client
authorization_url: not-a-valid-url
---
@@ -709,7 +709,7 @@ kind: remote
name: invalid-oauth2-agent
agent_card_url: https://example.com/card
auth:
type: oauth2
type: oauth
client_id: my-client
token_url: not-a-valid-url
---
@@ -723,7 +723,7 @@ auth:
name: 'oauth2-convert-agent',
agent_card_url: 'https://example.com/card',
auth: {
type: 'oauth2' as const,
type: 'oauth' as const,
client_id: '$MY_CLIENT_ID',
scopes: ['read'],
authorization_url: 'https://auth.example.com/authorize',
+3 -3
View File
@@ -63,7 +63,7 @@ interface FrontmatterLocalAgentDefinition
* Authentication configuration for remote agents in frontmatter format.
*/
interface FrontmatterAuthConfig {
type: 'apiKey' | 'http' | 'google-credentials' | 'oauth2';
type: 'apiKey' | 'http' | 'google-credentials' | 'oauth';
// API Key
key?: string;
name?: string;
@@ -205,7 +205,7 @@ const googleCredentialsAuthSchema = z.object({
*/
const oauth2AuthSchema = z.object({
...baseAuthFields,
type: z.literal('oauth2'),
type: z.literal('oauth'),
client_id: z.string().optional(),
client_secret: z.string().optional(),
scopes: z.array(z.string()).optional(),
@@ -471,7 +471,7 @@ function convertFrontmatterAuthToConfig(
}
}
case 'oauth2':
case 'oauth':
return {
...base,
type: 'oauth2',
@@ -112,6 +112,7 @@ Some errors are unrecoverable and retrying will never help. When you see ANY of
- "Could not connect to Chrome" or "Failed to connect to Chrome" or "Timed out connecting to Chrome" Include the full error message with its remediation steps in your summary verbatim. Do NOT paraphrase or omit instructions.
- "Browser closed" or "Target closed" or "Session closed" The browser process has terminated. Include the error and tell the user to try again.
- "net::ERR_" network errors on the SAME URL after 2 retries the site is unreachable. Report the URL and error.
- "reached maximum action limit" You have performed too many actions in this task. Stop immediately and report this limit to the user.
- Any error that appears IDENTICALLY 3+ times in a row it will not resolve by retrying.
Do NOT keep retrying terminal errors. Report them with actionable remediation steps and exit immediately.
@@ -697,4 +697,28 @@ describe('BrowserManager', () => {
expect(injectAutomationOverlay).not.toHaveBeenCalled();
});
});
describe('Rate limiting', () => {
it('should terminate task when maxActionsPerTask is reached', async () => {
const limitedConfig = makeFakeConfig({
agents: {
browser: {
maxActionsPerTask: 3,
},
},
});
const manager = new BrowserManager(limitedConfig);
// First 3 calls should succeed
await manager.callTool('take_snapshot', {});
await manager.callTool('take_snapshot', { some: 'args' });
await manager.callTool('take_snapshot', { other: 'args' });
await manager.callTool('take_snapshot', { other: 'new args' });
// 4th call should throw
await expect(manager.callTool('take_snapshot', {})).rejects.toThrow(
/maximum action limit \(3\)/,
);
});
});
});
@@ -97,6 +97,10 @@ export class BrowserManager {
private mcpTransport: StdioClientTransport | undefined;
private discoveredTools: McpTool[] = [];
/** State for action rate limiting */
private actionCounter = 0;
private readonly maxActionsPerTask: number;
/**
* Whether to inject the automation overlay.
* Always false in headless mode (no visible window to decorate).
@@ -108,6 +112,8 @@ export class BrowserManager {
const browserConfig = config.getBrowserAgentConfig();
this.shouldInjectOverlay = !browserConfig?.customConfig?.headless;
this.shouldDisableInput = config.shouldDisableBrowserUserInput();
this.maxActionsPerTask =
browserConfig?.customConfig.maxActionsPerTask ?? 100;
}
/**
@@ -151,6 +157,16 @@ export class BrowserManager {
throw signal.reason ?? new Error('Operation cancelled');
}
// Hard enforcement of per-action rate limit
if (this.actionCounter > this.maxActionsPerTask) {
const error = new Error(
`Browser agent reached maximum action limit (${this.maxActionsPerTask}). ` +
`Task terminated to prevent runaway execution. To config the limit, use maxActionsPerTask in the settings.`,
);
throw error;
}
this.actionCounter++;
const errorMessage = this.checkNavigationRestrictions(toolName, args);
if (errorMessage) {
return {
+16
View File
@@ -1474,6 +1474,22 @@ describe('Server Config (config.ts)', () => {
expect(browserConfig.customConfig.visualModel).toBe(
'custom-visual-model',
);
expect(browserConfig.customConfig.maxActionsPerTask).toBe(100); // default
});
it('should return custom maxActionsPerTask', () => {
const params: ConfigParameters = {
...baseParams,
agents: {
browser: {
maxActionsPerTask: 50,
},
},
};
const config = new Config(params);
const browserConfig = config.getBrowserAgentConfig();
expect(browserConfig.customConfig.maxActionsPerTask).toBe(50);
});
it('should apply defaults for partial custom config', () => {
+4 -1
View File
@@ -331,6 +331,8 @@ export interface BrowserAgentCustomConfig {
allowedDomains?: string[];
/** Disable user input on the browser window during automation. Default: true in non-headless mode */
disableUserInput?: boolean;
/** Maximum number of actions (tool calls) allowed per task. Default: 100 */
maxActionsPerTask?: number;
/** Whether to confirm sensitive actions (e.g., fill_form, evaluate_script). */
confirmSensitiveActions?: boolean;
/** Whether to block file uploads. */
@@ -1027,7 +1029,7 @@ export class Config implements McpContext, AgentLoopContext {
this.model = params.model;
this.disableLoopDetection = params.disableLoopDetection ?? false;
this._activeModel = params.model;
this.enableAgents = params.enableAgents ?? false;
this.enableAgents = params.enableAgents ?? true;
this.agents = params.agents ?? {};
this.disableLLMCorrection = params.disableLLMCorrection ?? true;
this.planEnabled = params.plan ?? true;
@@ -3194,6 +3196,7 @@ export class Config implements McpContext, AgentLoopContext {
visualModel: customConfig.visualModel,
allowedDomains: customConfig.allowedDomains,
disableUserInput: customConfig.disableUserInput,
maxActionsPerTask: customConfig.maxActionsPerTask ?? 100,
confirmSensitiveActions: customConfig.confirmSensitiveActions,
blockFileUploads: customConfig.blockFileUploads,
},
+5 -1
View File
@@ -88,7 +88,11 @@ export * from './utils/approvalModeUtils.js';
export * from './utils/fileDiffUtils.js';
export * from './utils/retry.js';
export * from './utils/shell-utils.js';
export { PolicyDecision, ApprovalMode } from './policy/types.js';
export {
PolicyDecision,
ApprovalMode,
PRIORITY_YOLO_ALLOW_ALL,
} from './policy/types.js';
export * from './utils/tool-utils.js';
export * from './utils/terminalSerializer.js';
export * from './utils/systemEncoding.js';
+4 -2
View File
@@ -2184,7 +2184,8 @@ export class ApprovalModeSwitchEvent implements BaseTelemetryEvent {
toOpenTelemetryAttributes(config: Config): LogAttributes {
return {
...getCommonAttributes(config),
event_name: EVENT_APPROVAL_MODE_SWITCH,
'event.name': EVENT_APPROVAL_MODE_SWITCH,
'event.timestamp': this['event.timestamp'],
from_mode: this.from_mode,
to_mode: this.to_mode,
};
@@ -2214,7 +2215,8 @@ export class ApprovalModeDurationEvent implements BaseTelemetryEvent {
toOpenTelemetryAttributes(config: Config): LogAttributes {
return {
...getCommonAttributes(config),
event_name: EVENT_APPROVAL_MODE_DURATION,
'event.name': EVENT_APPROVAL_MODE_DURATION,
'event.timestamp': this['event.timestamp'],
mode: this.mode,
duration_ms: this.duration_ms,
};
@@ -147,6 +147,51 @@ describe('McpClientManager', () => {
expect(mockedMcpClient.discoverInto).not.toHaveBeenCalled();
});
it('should NOT set COMPLETED prematurely when startConfiguredMcpServers finishes before parallel extensions', async () => {
mockConfig.getMcpServers.mockReturnValue({});
const manager = setupManager(new McpClientManager('0.0.1', mockConfig));
let resolveExtension: (value: void) => void;
const extensionPromise = new Promise<void>((resolve) => {
resolveExtension = resolve;
});
mockedMcpClient.connect.mockImplementation(async () => {
await extensionPromise;
});
const extensionStartPromise = manager.startExtension({
name: 'test-extension',
mcpServers: {
'extension-server': { command: 'node' },
},
isActive: true,
version: '1.0.0',
path: '/some-path',
contextFiles: [],
id: '123',
});
// Wait for the state to become IN_PROGRESS (since maybeDiscoverMcpServer is async)
await vi.waitFor(() => {
if (manager.getDiscoveryState() !== MCPDiscoveryState.IN_PROGRESS) {
throw new Error('Discovery state is not IN_PROGRESS');
}
});
expect(manager.getDiscoveryState()).toBe(MCPDiscoveryState.IN_PROGRESS);
await manager.startConfiguredMcpServers();
// discoveryState should still be IN_PROGRESS because the extension is still starting
expect(manager.getDiscoveryState()).toBe(MCPDiscoveryState.IN_PROGRESS);
resolveExtension!(undefined);
await extensionStartPromise;
expect(manager.getDiscoveryState()).toBe(MCPDiscoveryState.COMPLETED);
});
it('should mark discovery completed when all configured servers are blocked', async () => {
mockConfig.getMcpServers.mockReturnValue({
'test-server': { command: 'node' },
@@ -554,8 +554,10 @@ export class McpClientManager {
);
if (Object.keys(servers).length === 0) {
this.discoveryState = MCPDiscoveryState.COMPLETED;
this.eventEmitter?.emit('mcp-client-update', this.clients);
if (!this.discoveryPromise) {
this.discoveryState = MCPDiscoveryState.COMPLETED;
this.eventEmitter?.emit('mcp-client-update', this.clients);
}
return;
}
@@ -574,7 +576,10 @@ export class McpClientManager {
// If every configured server was skipped (for example because all are
// disabled by user settings), no discovery promise is created. In that
// case we must still mark discovery complete or the UI will wait forever.
if (this.discoveryState === MCPDiscoveryState.IN_PROGRESS) {
if (
this.discoveryState === MCPDiscoveryState.IN_PROGRESS &&
!this.discoveryPromise
) {
this.discoveryState = MCPDiscoveryState.COMPLETED;
this.eventEmitter?.emit('mcp-client-update', this.clients);
}
@@ -0,0 +1,72 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Represents a test agent used in evaluations and tests.
*/
export interface TestAgent {
/** The unique name of the agent. */
readonly name: string;
/** The full YAML/Markdown definition of the agent. */
readonly definition: string;
/** The standard path where this agent should be saved in a test project. */
readonly path: string;
/** A helper to spread this agent directly into a 'files' object for evalTest. */
readonly asFile: () => Record<string, string>;
}
/**
* Helper to create a TestAgent with consistent formatting and pathing.
*/
function createAgent(options: {
name: string;
description: string;
tools: string[];
body: string;
}): TestAgent {
const definition = `---
name: ${options.name}
description: ${options.description}
tools:
${options.tools.map((t) => ` - ${t}`).join('\n')}
---
${options.body}
`;
const path = `.gemini/agents/${options.name}.md`;
return {
name: options.name,
definition,
path,
asFile: () => ({ [path]: definition }),
};
}
/**
* A collection of predefined test agents for use in evaluations and tests.
*/
export const TEST_AGENTS = {
/**
* An agent with expertise in updating documentation.
*/
DOCS_AGENT: createAgent({
name: 'docs-agent',
description: 'An agent with expertise in updating documentation.',
tools: ['read_file', 'write_file'],
body: 'You are the docs agent. Update documentation clearly and accurately.',
}),
/**
* An agent with expertise in writing and updating tests.
*/
TESTING_AGENT: createAgent({
name: 'testing-agent',
description: 'An agent with expertise in writing and updating tests.',
tools: ['read_file', 'write_file'],
body: 'You are the test agent. Add or update tests.',
}),
} as const;
+2 -1
View File
@@ -5,6 +5,7 @@
*/
export * from './file-system-test-helpers.js';
export * from './test-rig.js';
export * from './fixtures/agents.js';
export * from './mock-utils.js';
export * from './test-mcp-server.js';
export * from './test-rig.js';