File size: 10,115 Bytes
7a1ad33 | 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 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 | /**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { vi } from 'vitest';
import { AgentChatHistory } from '../../core/agentChatHistory.js';
import { ContextManager } from '../contextManager.js';
import { randomUUID } from 'node:crypto';
export { deriveStableId } from '../../utils/cryptoUtils.js';
import { ContextTracer } from '../tracer.js';
import { ContextEnvironmentImpl } from '../pipeline/environmentImpl.js';
import { ContextEventBus } from '../eventBus.js';
import { PipelineOrchestrator } from '../pipeline/orchestrator.js';
import {
type ConcreteNode,
type ToolExecution,
NodeType,
} from '../graph/types.js';
import type { ContextEnvironment } from '../pipeline/environment.js';
import type { Config } from '../../config/config.js';
import type {
BaseLlmClient,
GenerateContentOptions,
} from '../../core/baseLlmClient.js';
import type { Content, GenerateContentResponse } from '@google/genai';
import { InboxSnapshotImpl } from '../pipeline/inbox.js';
import type { InboxMessage, ProcessArgs } from '../pipeline.js';
import type { ContextProfile } from '../config/profiles.js';
import type { Mock } from 'vitest';
import { ContextWorkingBufferImpl } from '../pipeline/contextWorkingBuffer.js';
import { testTruncateProfile } from './testProfile.js';
import { StaticTokenCalculator } from '../utils/contextTokenCalculator.js';
import { NodeBehaviorRegistry } from '../graph/behaviorRegistry.js';
import { registerBuiltInBehaviors } from '../graph/builtinBehaviors.js';
/**
* Creates a valid mock GenerateContentResponse with the provided text.
* Used to avoid having to manually construct the deeply nested candidate/content/part structure.
*/
export const createMockGenerateContentResponse = (
text: string,
): GenerateContentResponse =>
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
({
candidates: [{ content: { role: 'model', parts: [{ text }] }, index: 0 }],
}) as GenerateContentResponse;
export function createDummyNode(
turnId: string,
type: NodeType,
_tokens = 100,
overrides?: Partial<ConcreteNode>,
id?: string,
): ConcreteNode {
const role =
type === NodeType.USER_PROMPT ||
type === NodeType.SYSTEM_EVENT ||
type === NodeType.SNAPSHOT ||
type === NodeType.ROLLING_SUMMARY
? 'user'
: 'model';
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
return {
id: id || randomUUID(),
turnId,
type,
timestamp: Date.now(),
role,
payload: { text: `Dummy ${type}` },
...overrides,
} as unknown as ConcreteNode;
}
export function createDummyToolNode(
turnId: string,
_intentTokens = 100,
_obsTokens = 200,
overrides?: Partial<ToolExecution>,
id?: string,
): ToolExecution {
// We don't distinguish between call and response here, but ToolExecution nodes in 1:1 map to ONE part.
// Tests using this usually want to simulate a tool interaction.
// For simplicity, we'll make this a 'model' tool call by default.
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
return {
id: id || randomUUID(),
turnId,
type: NodeType.TOOL_EXECUTION,
timestamp: Date.now(),
role: 'model',
payload: {
functionCall: {
name: 'dummy_tool',
args: { action: 'test' },
id: id || 'dummy_id',
},
},
...overrides,
} as unknown as ToolExecution;
}
export interface MockLlmClient extends BaseLlmClient {
generateContent: Mock;
countTokens: Mock;
}
export function createMockLlmClient(
responses?: Array<string | GenerateContentResponse>,
): MockLlmClient {
const generateContentMock = vi
.fn()
.mockImplementation((options: GenerateContentOptions) => {
// Array-based logic for backwards compatibility, if provided
if (responses && responses.length > 0) {
const callCount = generateContentMock.mock.calls.length - 1;
const idx =
callCount < responses.length ? callCount : responses.length - 1;
const res = responses[idx];
return Promise.resolve(
typeof res === 'string'
? createMockGenerateContentResponse(res)
: res,
);
}
const lastContent = options.contents[options.contents.length - 1];
const lastPart = lastContent?.parts?.[lastContent.parts.length - 1];
const lastPartString = JSON.stringify(lastPart ?? {});
const contentSample = `${lastPartString.slice(0, 10)}...${lastPartString.slice(-10)}`;
return Promise.resolve(
createMockGenerateContentResponse(
`Mock response from: ${options.role}, for: ${contentSample}`,
),
);
});
const generateJsonMock = vi.fn().mockImplementation(async () => {
let mockStr = '';
if (responses && responses.length > 0) {
const callCount = generateJsonMock.mock.calls.length - 1;
const idx =
callCount < responses.length ? callCount : responses.length - 1;
const res = responses[idx];
if (typeof res === 'string') {
mockStr = res;
}
}
return {
active_tasks: [],
discovered_facts: [],
constraints_and_preferences: [],
chronological_summary: mockStr,
};
});
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
return {
generateContent: generateContentMock,
generateJson: generateJsonMock,
countTokens: vi.fn().mockResolvedValue({ totalTokens: 100 }),
} as unknown as MockLlmClient;
}
export function createMockEnvironment(
overrides?: Partial<ContextEnvironment>,
): ContextEnvironment {
const llmClient = createMockLlmClient(['Mock LLM summary response']);
const tracer = new ContextTracer({
targetDir: '/tmp',
sessionId: 'mock-session',
});
const eventBus = new ContextEventBus();
const behaviorRegistry = new NodeBehaviorRegistry();
registerBuiltInBehaviors(behaviorRegistry);
const calculator = new StaticTokenCalculator(1, behaviorRegistry);
let env = new ContextEnvironmentImpl(
() => llmClient as BaseLlmClient,
'mock-session',
'mock-prompt-id',
'/tmp/.gemini/trace',
'/tmp/.gemini/tool-outputs',
tracer,
1,
eventBus,
calculator,
behaviorRegistry,
);
if (overrides) {
if (overrides.llmClient) {
env = new ContextEnvironmentImpl(
() => overrides.llmClient!,
env.sessionId,
env.promptId,
env.traceDir,
env.projectTempDir,
env.tracer,
env.charsPerToken,
env.eventBus,
calculator,
behaviorRegistry,
);
}
const { llmClient: _llmClient, ...restOverrides } = overrides;
Object.assign(env, restOverrides);
}
return env;
}
/**
* Creates a block of synthetic conversation history designed to consume a specific number of tokens.
* Assumes roughly 4 characters per token for standard English text.
*/
export function createMockProcessArgs(
targets: ConcreteNode[],
bufferNodes: ConcreteNode[] = [],
inboxMessages: InboxMessage[] = [],
): ProcessArgs {
return {
targets,
buffer: ContextWorkingBufferImpl.initialize(
bufferNodes.length ? bufferNodes : targets,
),
inbox: new InboxSnapshotImpl(inboxMessages),
};
}
export function createSyntheticHistory(
numTurns: number,
tokensPerTurn: number,
): Content[] {
const history: Content[] = [];
const charsPerTurn = tokensPerTurn * 1;
for (let i = 0; i < numTurns; i++) {
history.push({
role: 'user',
parts: [{ text: `User turn ${i}. ` + 'A'.repeat(charsPerTurn) }],
});
history.push({
role: 'model',
parts: [{ text: `Model response ${i}. ` + 'B'.repeat(charsPerTurn) }],
});
}
return history;
}
/**
* Creates a fully mocked Config object tailored for Context Component testing.
*/
export function createMockContextConfig(
overrides?: Record<string, unknown>,
llmClientOverride?: unknown,
): Config {
const defaultConfig = {
isContextManagementEnabled: vi.fn().mockReturnValue(true),
storage: {
getProjectTempDir: vi.fn().mockReturnValue('/tmp/gemini-test'),
},
getBaseLlmClient: vi.fn().mockReturnValue(
llmClientOverride || {
generateContent: vi.fn().mockResolvedValue({
text: '<mocked_snapshot>Synthesized state</mocked_snapshot>',
}),
},
),
getUsageStatisticsEnabled: vi.fn().mockReturnValue(false),
getTargetDir: vi.fn().mockReturnValue('/tmp'),
getSessionId: vi.fn().mockReturnValue('test-session'),
getExperimentalContextManagementConfig: vi.fn().mockReturnValue(undefined),
};
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
return { ...defaultConfig, ...overrides } as unknown as Config;
}
/**
* Wires up a full ContextManager component with an AgentChatHistory and active background async pipelines.
*/
export function setupContextComponentTest(
config: Config,
sidecarOverride?: ContextProfile,
): { chatHistory: AgentChatHistory; contextManager: ContextManager } {
const chatHistory = new AgentChatHistory();
const sidecar = sidecarOverride || testTruncateProfile;
const tracer = new ContextTracer({
targetDir: '/tmp',
sessionId: 'test-session',
});
const eventBus = new ContextEventBus();
const behaviorRegistry = new NodeBehaviorRegistry();
registerBuiltInBehaviors(behaviorRegistry);
const calculator = new StaticTokenCalculator(1, behaviorRegistry);
const env = new ContextEnvironmentImpl(
() => config.getBaseLlmClient(),
'test prompt-id',
'test-session',
'/tmp',
'/tmp/gemini-test',
tracer,
1,
eventBus,
calculator,
behaviorRegistry,
);
const orchestrator = new PipelineOrchestrator(
sidecar.buildPipelines(env),
sidecar.buildAsyncPipelines(env),
env,
tracer,
);
const contextManager = new ContextManager(
sidecar,
env,
tracer,
orchestrator,
chatHistory,
calculator,
);
// The async async pipeline is now internally managed by ContextManager
return { chatHistory, contextManager };
}
|