add more test
This commit is contained in:
parent
4b18cfe3f3
commit
2fe5bee96f
@ -417,7 +417,7 @@ export class GeminiClient {
|
||||
options?: { isContinuation: boolean },
|
||||
turns: number = MAX_TURNS,
|
||||
): AsyncGenerator<ServerGeminiStreamEvent, Turn> {
|
||||
// Fire BeforeAgent hook through MessageBus (only if hooks are enabled)
|
||||
// Fire UserPromptSubmit hook through MessageBus (only if hooks are enabled)
|
||||
const hooksEnabled = this.config.getEnableHooks();
|
||||
const messageBus = this.config.getMessageBus();
|
||||
if (hooksEnabled && messageBus) {
|
||||
@ -591,7 +591,7 @@ export class GeminiClient {
|
||||
return turn;
|
||||
}
|
||||
}
|
||||
// Fire AfterAgent hook through MessageBus (only if hooks are enabled)
|
||||
// Fire Stop hook through MessageBus (only if hooks are enabled)
|
||||
// This must be done before any early returns to ensure hooks are always triggered
|
||||
if (hooksEnabled && messageBus && !turn.pendingToolCalls.length) {
|
||||
// Get response text from the chat history
|
||||
|
||||
@ -309,5 +309,58 @@ describe('HookPlanner', () => {
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
});
|
||||
|
||||
it('should fallback to exact match when regex is invalid', () => {
|
||||
const entry: HookRegistryEntry = {
|
||||
config: { type: HookType.Command, command: 'echo test' },
|
||||
source: HooksConfigSource.Project,
|
||||
eventName: HookEventName.PreToolUse,
|
||||
matcher: '[invalid(regex', // Invalid regex
|
||||
enabled: true,
|
||||
};
|
||||
vi.mocked(mockRegistry.getHooksForEvent).mockReturnValue([entry]);
|
||||
|
||||
// Should fallback to exact match - should NOT match 'bash'
|
||||
const result = planner.createExecutionPlan(HookEventName.PreToolUse, {
|
||||
toolName: 'bash',
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('should match using fallback exact match when regex is invalid', () => {
|
||||
const entry: HookRegistryEntry = {
|
||||
config: { type: HookType.Command, command: 'echo test' },
|
||||
source: HooksConfigSource.Project,
|
||||
eventName: HookEventName.PreToolUse,
|
||||
matcher: '[invalid(regex', // Invalid regex
|
||||
enabled: true,
|
||||
};
|
||||
vi.mocked(mockRegistry.getHooksForEvent).mockReturnValue([entry]);
|
||||
|
||||
// Should fallback to exact match - should match '[invalid(regex'
|
||||
const result = planner.createExecutionPlan(HookEventName.PreToolUse, {
|
||||
toolName: '[invalid(regex',
|
||||
});
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
});
|
||||
|
||||
it('should handle complex invalid regex gracefully', () => {
|
||||
const entry: HookRegistryEntry = {
|
||||
config: { type: HookType.Command, command: 'echo test' },
|
||||
source: HooksConfigSource.Project,
|
||||
eventName: HookEventName.PreToolUse,
|
||||
matcher: '(unclosed',
|
||||
enabled: true,
|
||||
};
|
||||
vi.mocked(mockRegistry.getHooksForEvent).mockReturnValue([entry]);
|
||||
|
||||
const result = planner.createExecutionPlan(HookEventName.PreToolUse, {
|
||||
toolName: 'bash',
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@ -7,6 +7,9 @@
|
||||
import type { HookRegistry, HookRegistryEntry } from './hookRegistry.js';
|
||||
import type { HookExecutionPlan } from './types.js';
|
||||
import { getHookKey, type HookEventName } from './types.js';
|
||||
import { createDebugLogger } from '../utils/debugLogger.js';
|
||||
|
||||
const debugLogger = createDebugLogger('TRUSTED_HOOKS');
|
||||
|
||||
/**
|
||||
* Hook planner that selects matching hooks and creates execution plans
|
||||
@ -98,8 +101,11 @@ export class HookPlanner {
|
||||
// Attempt to treat the matcher as a regular expression.
|
||||
const regex = new RegExp(matcher);
|
||||
return regex.test(toolName);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
// If it's not a valid regex, treat it as a literal string for an exact match.
|
||||
debugLogger.warn(
|
||||
`Invalid regex in hook matcher "${matcher}" for tool "${toolName}", falling back to exact match: ${error}`,
|
||||
);
|
||||
return matcher === toolName;
|
||||
}
|
||||
}
|
||||
|
||||
@ -448,4 +448,237 @@ describe('HookRunner', () => {
|
||||
expect(onHookEnd).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('output truncation', () => {
|
||||
it('should truncate stdout when exceeding MAX_OUTPUT_LENGTH', async () => {
|
||||
// Create a process that outputs more than 1MB of data
|
||||
const largeOutput = 'x'.repeat(2 * 1024 * 1024); // 2MB
|
||||
const mockProcess = createMockProcess(0, largeOutput);
|
||||
mockSpawn.mockImplementation(() => mockProcess);
|
||||
|
||||
const hookConfig: HookConfig = {
|
||||
type: HookType.Command,
|
||||
command: 'echo large',
|
||||
source: HooksConfigSource.Project,
|
||||
};
|
||||
const input = createMockInput();
|
||||
|
||||
const result = await hookRunner.executeHook(
|
||||
hookConfig,
|
||||
HookEventName.PreToolUse,
|
||||
input,
|
||||
);
|
||||
|
||||
// stdout should be truncated to MAX_OUTPUT_LENGTH (1MB)
|
||||
expect(result.stdout?.length).toBeLessThanOrEqual(1024 * 1024);
|
||||
});
|
||||
|
||||
it('should truncate stderr when exceeding MAX_OUTPUT_LENGTH', async () => {
|
||||
const largeOutput = 'x'.repeat(2 * 1024 * 1024); // 2MB
|
||||
const mockProcess = createMockProcess(0, '', largeOutput);
|
||||
mockSpawn.mockImplementation(() => mockProcess);
|
||||
|
||||
const hookConfig: HookConfig = {
|
||||
type: HookType.Command,
|
||||
command: 'echo large',
|
||||
source: HooksConfigSource.Project,
|
||||
};
|
||||
const input = createMockInput();
|
||||
|
||||
const result = await hookRunner.executeHook(
|
||||
hookConfig,
|
||||
HookEventName.PreToolUse,
|
||||
input,
|
||||
);
|
||||
|
||||
// stderr should be truncated to MAX_OUTPUT_LENGTH (1MB)
|
||||
expect(result.stderr?.length).toBeLessThanOrEqual(1024 * 1024);
|
||||
});
|
||||
|
||||
it('should handle partial truncation gracefully', async () => {
|
||||
// Output exactly at the limit
|
||||
const exactOutput = 'x'.repeat(1024 * 1024); // 1MB exactly
|
||||
const mockProcess = createMockProcess(0, exactOutput);
|
||||
mockSpawn.mockImplementation(() => mockProcess);
|
||||
|
||||
const hookConfig: HookConfig = {
|
||||
type: HookType.Command,
|
||||
command: 'echo exact',
|
||||
source: HooksConfigSource.Project,
|
||||
};
|
||||
const input = createMockInput();
|
||||
|
||||
const result = await hookRunner.executeHook(
|
||||
hookConfig,
|
||||
HookEventName.PreToolUse,
|
||||
input,
|
||||
);
|
||||
|
||||
expect(result.stdout?.length).toBe(1024 * 1024);
|
||||
});
|
||||
});
|
||||
|
||||
describe('expandCommand', () => {
|
||||
it('should expand GEMINI_PROJECT_DIR placeholder', async () => {
|
||||
const mockProcess = createMockProcess(0, 'result');
|
||||
mockSpawn.mockImplementation(() => mockProcess);
|
||||
|
||||
const hookConfig: HookConfig = {
|
||||
type: HookType.Command,
|
||||
command: 'echo $GEMINI_PROJECT_DIR',
|
||||
source: HooksConfigSource.Project,
|
||||
};
|
||||
const input = createMockInput({ cwd: '/test/project' });
|
||||
|
||||
await hookRunner.executeHook(hookConfig, HookEventName.PreToolUse, input);
|
||||
|
||||
// Verify spawn was called with expanded command
|
||||
const spawnCall = mockSpawn.mock.calls[0];
|
||||
const command = spawnCall[1][1]; // Second arg after shell args
|
||||
expect(command).toContain('/test/project');
|
||||
});
|
||||
|
||||
it('should expand CLAUDE_PROJECT_DIR placeholder for compatibility', async () => {
|
||||
const mockProcess = createMockProcess(0, 'result');
|
||||
mockSpawn.mockImplementation(() => mockProcess);
|
||||
|
||||
const hookConfig: HookConfig = {
|
||||
type: HookType.Command,
|
||||
command: 'echo $CLAUDE_PROJECT_DIR',
|
||||
source: HooksConfigSource.Project,
|
||||
};
|
||||
const input = createMockInput({ cwd: '/test/project' });
|
||||
|
||||
await hookRunner.executeHook(hookConfig, HookEventName.PreToolUse, input);
|
||||
|
||||
const spawnCall = mockSpawn.mock.calls[0];
|
||||
const command = spawnCall[1][1];
|
||||
expect(command).toContain('/test/project');
|
||||
});
|
||||
|
||||
it('should not modify command without placeholders', async () => {
|
||||
const mockProcess = createMockProcess(0, 'result');
|
||||
mockSpawn.mockImplementation(() => mockProcess);
|
||||
|
||||
const hookConfig: HookConfig = {
|
||||
type: HookType.Command,
|
||||
command: 'echo hello',
|
||||
source: HooksConfigSource.Project,
|
||||
};
|
||||
const input = createMockInput({ cwd: '/test/project' });
|
||||
|
||||
await hookRunner.executeHook(hookConfig, HookEventName.PreToolUse, input);
|
||||
|
||||
const spawnCall = mockSpawn.mock.calls[0];
|
||||
const command = spawnCall[1][1];
|
||||
expect(command).toBe('echo hello');
|
||||
});
|
||||
});
|
||||
|
||||
describe('convertPlainTextToHookOutput', () => {
|
||||
it('should convert plain text to allow output on success', async () => {
|
||||
const mockProcess = createMockProcess(0, 'plain text response');
|
||||
mockSpawn.mockImplementation(() => mockProcess);
|
||||
|
||||
const hookConfig: HookConfig = {
|
||||
type: HookType.Command,
|
||||
command: 'echo text',
|
||||
source: HooksConfigSource.Project,
|
||||
};
|
||||
const input = createMockInput();
|
||||
|
||||
const result = await hookRunner.executeHook(
|
||||
hookConfig,
|
||||
HookEventName.PreToolUse,
|
||||
input,
|
||||
);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.output?.decision).toBe('allow');
|
||||
expect(result.output?.systemMessage).toBe('plain text response');
|
||||
});
|
||||
|
||||
it('should convert non-zero exit code to deny output', async () => {
|
||||
const mockProcess = createMockProcess(3, '', 'error message');
|
||||
mockSpawn.mockImplementation(() => mockProcess);
|
||||
|
||||
const hookConfig: HookConfig = {
|
||||
type: HookType.Command,
|
||||
command: 'exit 3',
|
||||
source: HooksConfigSource.Project,
|
||||
};
|
||||
const input = createMockInput();
|
||||
|
||||
const result = await hookRunner.executeHook(
|
||||
hookConfig,
|
||||
HookEventName.PreToolUse,
|
||||
input,
|
||||
);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.output?.decision).toBe('deny');
|
||||
expect(result.output?.reason).toBe('error message');
|
||||
});
|
||||
|
||||
it('should use stderr when stdout is empty on success', async () => {
|
||||
const mockProcess = createMockProcess(0, '', 'stderr output');
|
||||
mockSpawn.mockImplementation(() => mockProcess);
|
||||
|
||||
const hookConfig: HookConfig = {
|
||||
type: HookType.Command,
|
||||
command: 'echo test',
|
||||
source: HooksConfigSource.Project,
|
||||
};
|
||||
const input = createMockInput();
|
||||
|
||||
const result = await hookRunner.executeHook(
|
||||
hookConfig,
|
||||
HookEventName.PreToolUse,
|
||||
input,
|
||||
);
|
||||
|
||||
expect(result.output?.systemMessage).toBe('stderr output');
|
||||
});
|
||||
|
||||
it('should handle empty output gracefully', async () => {
|
||||
const mockProcess = createMockProcess(0, '', '');
|
||||
mockSpawn.mockImplementation(() => mockProcess);
|
||||
|
||||
const hookConfig: HookConfig = {
|
||||
type: HookType.Command,
|
||||
command: 'echo test',
|
||||
source: HooksConfigSource.Project,
|
||||
};
|
||||
const input = createMockInput();
|
||||
|
||||
const result = await hookRunner.executeHook(
|
||||
hookConfig,
|
||||
HookEventName.PreToolUse,
|
||||
input,
|
||||
);
|
||||
|
||||
expect(result.output).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should parse nested JSON strings', async () => {
|
||||
const nestedJson = JSON.stringify(JSON.stringify({ decision: 'allow' }));
|
||||
const mockProcess = createMockProcess(0, nestedJson);
|
||||
mockSpawn.mockImplementation(() => mockProcess);
|
||||
|
||||
const hookConfig: HookConfig = {
|
||||
type: HookType.Command,
|
||||
command: 'echo json',
|
||||
source: HooksConfigSource.Project,
|
||||
};
|
||||
const input = createMockInput();
|
||||
|
||||
const result = await hookRunner.executeHook(
|
||||
hookConfig,
|
||||
HookEventName.PreToolUse,
|
||||
input,
|
||||
);
|
||||
|
||||
expect(result.output?.decision).toBe('allow');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@ -28,6 +28,12 @@ const debugLogger = createDebugLogger('TRUSTED_HOOKS');
|
||||
*/
|
||||
const DEFAULT_HOOK_TIMEOUT = 60000;
|
||||
|
||||
/**
|
||||
* Maximum length for stdout/stderr output (1MB)
|
||||
* Prevents memory issues from unbounded output
|
||||
*/
|
||||
const MAX_OUTPUT_LENGTH = 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Exit code constants for hook execution
|
||||
*/
|
||||
@ -270,12 +276,28 @@ export class HookRunner {
|
||||
|
||||
// Collect stdout
|
||||
child.stdout?.on('data', (data: Buffer) => {
|
||||
stdout += data.toString();
|
||||
if (stdout.length < MAX_OUTPUT_LENGTH) {
|
||||
const remaining = MAX_OUTPUT_LENGTH - stdout.length;
|
||||
stdout += data.slice(0, remaining).toString();
|
||||
if (data.length > remaining) {
|
||||
debugLogger.warn(
|
||||
`Hook stdout exceeded max length (${MAX_OUTPUT_LENGTH} bytes), truncating`,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Collect stderr
|
||||
child.stderr?.on('data', (data: Buffer) => {
|
||||
stderr += data.toString();
|
||||
if (stderr.length < MAX_OUTPUT_LENGTH) {
|
||||
const remaining = MAX_OUTPUT_LENGTH - stderr.length;
|
||||
stderr += data.slice(0, remaining).toString();
|
||||
if (data.length > remaining) {
|
||||
debugLogger.warn(
|
||||
`Hook stderr exceeded max length (${MAX_OUTPUT_LENGTH} bytes), truncating`,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Handle process exit
|
||||
|
||||
@ -11,7 +11,12 @@ import { HookRunner } from './hookRunner.js';
|
||||
import { HookAggregator } from './hookAggregator.js';
|
||||
import { HookPlanner } from './hookPlanner.js';
|
||||
import { HookEventHandler } from './hookEventHandler.js';
|
||||
import { HookType, HooksConfigSource, HookEventName } from './types.js';
|
||||
import {
|
||||
HookType,
|
||||
HooksConfigSource,
|
||||
HookEventName,
|
||||
type HookDecision,
|
||||
} from './types.js';
|
||||
import type { Config } from '../config/config.js';
|
||||
|
||||
vi.mock('./hookRegistry.js');
|
||||
@ -213,4 +218,111 @@ describe('HookSystem', () => {
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('fireUserPromptSubmitEvent', () => {
|
||||
it('should fire UserPromptSubmit event and return output', async () => {
|
||||
const mockResult = {
|
||||
success: true,
|
||||
allOutputs: [],
|
||||
errors: [],
|
||||
totalDuration: 50,
|
||||
finalOutput: {
|
||||
continue: true,
|
||||
decision: 'allow' as HookDecision,
|
||||
},
|
||||
};
|
||||
vi.mocked(
|
||||
mockHookEventHandler.fireUserPromptSubmitEvent,
|
||||
).mockResolvedValue(mockResult);
|
||||
|
||||
const result = await hookSystem.fireUserPromptSubmitEvent('test prompt');
|
||||
|
||||
expect(
|
||||
mockHookEventHandler.fireUserPromptSubmitEvent,
|
||||
).toHaveBeenCalledWith('test prompt');
|
||||
expect(result).toBeDefined();
|
||||
});
|
||||
|
||||
it('should pass prompt to event handler', async () => {
|
||||
const mockResult = {
|
||||
success: true,
|
||||
allOutputs: [],
|
||||
errors: [],
|
||||
totalDuration: 0,
|
||||
finalOutput: {
|
||||
decision: 'allow' as HookDecision,
|
||||
},
|
||||
};
|
||||
vi.mocked(
|
||||
mockHookEventHandler.fireUserPromptSubmitEvent,
|
||||
).mockResolvedValue(mockResult);
|
||||
|
||||
await hookSystem.fireUserPromptSubmitEvent('my custom prompt');
|
||||
|
||||
expect(
|
||||
mockHookEventHandler.fireUserPromptSubmitEvent,
|
||||
).toHaveBeenCalledWith('my custom prompt');
|
||||
});
|
||||
|
||||
it('should return undefined when no final output', async () => {
|
||||
const mockResult = {
|
||||
success: true,
|
||||
allOutputs: [],
|
||||
errors: [],
|
||||
totalDuration: 0,
|
||||
finalOutput: undefined,
|
||||
};
|
||||
vi.mocked(
|
||||
mockHookEventHandler.fireUserPromptSubmitEvent,
|
||||
).mockResolvedValue(mockResult);
|
||||
|
||||
const result = await hookSystem.fireUserPromptSubmitEvent('test');
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should return DefaultHookOutput with blocking decision', async () => {
|
||||
const mockResult = {
|
||||
success: true,
|
||||
allOutputs: [],
|
||||
errors: [],
|
||||
totalDuration: 50,
|
||||
finalOutput: {
|
||||
decision: 'block' as HookDecision,
|
||||
reason: 'Blocked by policy',
|
||||
},
|
||||
};
|
||||
vi.mocked(
|
||||
mockHookEventHandler.fireUserPromptSubmitEvent,
|
||||
).mockResolvedValue(mockResult);
|
||||
|
||||
const result = await hookSystem.fireUserPromptSubmitEvent('test');
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.isBlockingDecision()).toBe(true);
|
||||
});
|
||||
|
||||
it('should return DefaultHookOutput with additional context', async () => {
|
||||
const mockResult = {
|
||||
success: true,
|
||||
allOutputs: [],
|
||||
errors: [],
|
||||
totalDuration: 50,
|
||||
finalOutput: {
|
||||
decision: 'allow' as HookDecision,
|
||||
hookSpecificOutput: {
|
||||
additionalContext: 'Some additional context',
|
||||
},
|
||||
},
|
||||
};
|
||||
vi.mocked(
|
||||
mockHookEventHandler.fireUserPromptSubmitEvent,
|
||||
).mockResolvedValue(mockResult);
|
||||
|
||||
const result = await hookSystem.fireUserPromptSubmitEvent('test');
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.getAdditionalContext()).toBe('Some additional context');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user