File size: 8,915 Bytes
52efc7b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | /**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { handleAtCommand } from './atCommandProcessor.js';
import type {
Config,
AgentDefinition,
MessageBus,
} from '@google/gemini-cli-core';
import {
FileDiscoveryService,
GlobTool,
ReadManyFilesTool,
StandardFileSystemService,
ToolRegistry,
COMMON_IGNORE_PATTERNS,
ApprovalMode,
} from '@google/gemini-cli-core';
import * as os from 'node:os';
import type { UseHistoryManagerReturn } from './useHistoryManager.js';
import * as fsPromises from 'node:fs/promises';
import * as path from 'node:path';
describe('handleAtCommand with Agents', () => {
let testRootDir: string;
let mockConfig: Config;
const mockAddItem: UseHistoryManagerReturn['addItem'] = vi.fn();
const mockOnDebugMessage: (message: string) => void = vi.fn();
let abortController: AbortController;
beforeEach(async () => {
vi.resetAllMocks();
testRootDir = await fsPromises.realpath(
await fsPromises.mkdtemp(path.join(os.tmpdir(), 'agent-test-')),
);
abortController = new AbortController();
const getToolRegistry = vi.fn();
const mockMessageBus = {
publish: vi.fn(),
subscribe: vi.fn(),
unsubscribe: vi.fn(),
} as unknown as MessageBus;
const mockAgentRegistry = {
getDefinition: vi.fn((name: string) => {
if (name === 'CodebaseInvestigator') {
return {
name: 'CodebaseInvestigator',
description: 'Investigates codebase',
kind: 'local',
} as AgentDefinition;
}
return undefined;
}),
};
mockConfig = {
getToolRegistry,
getTargetDir: () => testRootDir,
isSandboxed: () => false,
getExcludeTools: vi.fn(),
getFileService: () => new FileDiscoveryService(testRootDir),
getFileFilteringRespectGitIgnore: () => true,
getFileFilteringRespectGeminiIgnore: () => true,
getFileFilteringOptions: () => ({
respectGitIgnore: true,
respectGeminiIgnore: true,
}),
getFileSystemService: () => new StandardFileSystemService(),
getEnableRecursiveFileSearch: vi.fn(() => true),
getWorkspaceContext: () => ({
isPathWithinWorkspace: (p: string) =>
p.startsWith(testRootDir) || p.startsWith('/private' + testRootDir),
getDirectories: () => [testRootDir],
}),
storage: {
getProjectTempDir: () => path.join(os.tmpdir(), 'gemini-cli-temp'),
},
isPathAllowed(this: Config, absolutePath: string): boolean {
if (this.interactive && path.isAbsolute(absolutePath)) {
return true;
}
const workspaceContext = this.getWorkspaceContext();
if (workspaceContext.isPathWithinWorkspace(absolutePath)) {
return true;
}
const projectTempDir = this.storage.getProjectTempDir();
const resolvedProjectTempDir = path.resolve(projectTempDir);
return (
absolutePath.startsWith(resolvedProjectTempDir + path.sep) ||
absolutePath === resolvedProjectTempDir
);
},
validatePathAccess(this: Config, absolutePath: string): string | null {
if (this.isPathAllowed(absolutePath)) {
return null;
}
const workspaceDirs = this.getWorkspaceContext().getDirectories();
const projectTempDir = this.storage.getProjectTempDir();
return `Path validation failed: Attempted path "${absolutePath}" resolves outside the allowed workspace directories: ${workspaceDirs.join(', ')} or the project temp directory: ${projectTempDir}`;
},
getMcpServers: () => ({}),
getMcpServerCommand: () => undefined,
getPromptRegistry: () => ({
getPromptsByServer: () => [],
}),
getDebugMode: () => false,
getWorkingDir: () => '/working/dir',
getFileExclusions: () => ({
getCoreIgnorePatterns: () => COMMON_IGNORE_PATTERNS,
getDefaultExcludePatterns: () => [],
getGlobExcludes: () => [],
buildExcludePatterns: () => [],
getReadManyFilesExcludes: () => [],
}),
getUsageStatisticsEnabled: () => false,
getEnableExtensionReloading: () => false,
getResourceRegistry: () => ({
findResourceByUri: () => undefined,
getAllResources: () => [],
}),
getMcpClientManager: () => ({
getClient: () => undefined,
}),
getMessageBus: () => mockMessageBus,
interactive: true,
getAgentRegistry: () => mockAgentRegistry,
getApprovalMode: () => ApprovalMode.DEFAULT,
} as unknown as Config;
const registry = new ToolRegistry(mockConfig, mockMessageBus);
registry.registerTool(new ReadManyFilesTool(mockConfig, mockMessageBus));
registry.registerTool(new GlobTool(mockConfig, mockMessageBus));
getToolRegistry.mockReturnValue(registry);
});
afterEach(async () => {
abortController.abort();
await fsPromises.rm(testRootDir, { recursive: true, force: true });
});
it('should detect agent reference and add nudge message', async () => {
const query = 'Please help me @CodebaseInvestigator';
const result = await handleAtCommand({
query,
config: mockConfig,
addItem: mockAddItem,
onDebugMessage: mockOnDebugMessage,
messageId: 123,
signal: abortController.signal,
});
expect(result.processedQuery).toBeDefined();
const parts = result.processedQuery;
if (!Array.isArray(parts)) {
throw new Error('processedQuery should be an array');
}
// Check if the query text is preserved
const firstPart = parts[0];
if (
typeof firstPart === 'object' &&
firstPart !== null &&
'text' in firstPart
) {
expect((firstPart as { text: string }).text).toContain(
'Please help me @CodebaseInvestigator',
);
} else {
throw new Error('First part should be a text part');
}
// Check if the nudge message is added
const nudgePart = parts.find(
(p) =>
typeof p === 'object' &&
p !== null &&
'text' in p &&
(p as { text: string }).text.includes('<system_note>'),
);
expect(nudgePart).toBeDefined();
if (nudgePart && typeof nudgePart === 'object' && 'text' in nudgePart) {
expect((nudgePart as { text: string }).text).toContain(
'The user has explicitly selected the following agent(s): CodebaseInvestigator',
);
}
});
it('should handle multiple agents', async () => {
// Mock another agent
const mockAgentRegistry = mockConfig.getAgentRegistry() as {
getDefinition: (name: string) => AgentDefinition | undefined;
};
mockAgentRegistry.getDefinition = vi.fn((name: string) => {
if (name === 'CodebaseInvestigator' || name === 'AnotherAgent') {
return { name, description: 'desc', kind: 'local' } as AgentDefinition;
}
return undefined;
});
const query = '@CodebaseInvestigator and @AnotherAgent';
const result = await handleAtCommand({
query,
config: mockConfig,
addItem: mockAddItem,
onDebugMessage: mockOnDebugMessage,
messageId: 124,
signal: abortController.signal,
});
const parts = result.processedQuery;
if (!Array.isArray(parts)) {
throw new Error('processedQuery should be an array');
}
const nudgePart = parts.find(
(p) =>
typeof p === 'object' &&
p !== null &&
'text' in p &&
(p as { text: string }).text.includes('<system_note>'),
);
expect(nudgePart).toBeDefined();
if (nudgePart && typeof nudgePart === 'object' && 'text' in nudgePart) {
expect((nudgePart as { text: string }).text).toContain(
'CodebaseInvestigator, AnotherAgent',
);
}
});
it('should not treat non-agents as agents', async () => {
const query = '@UnknownAgent';
// This should fail to resolve and fallback or error depending on file search
// Since it's not a file, handleAtCommand logic for files will run.
// It will likely log debug message about not finding file/glob.
// But critical for this test: it should NOT add the agent nudge.
const result = await handleAtCommand({
query,
config: mockConfig,
addItem: mockAddItem,
onDebugMessage: mockOnDebugMessage,
messageId: 125,
signal: abortController.signal,
});
const parts = result.processedQuery;
if (!Array.isArray(parts)) {
throw new Error('processedQuery should be an array');
}
const nudgePart = parts.find(
(p) =>
typeof p === 'object' &&
p !== null &&
'text' in p &&
(p as { text: string }).text.includes('<system_note>'),
);
expect(nudgePart).toBeUndefined();
});
});
|