Merge branch 'main' into feature/differentiated-user-agent

This commit is contained in:
Bryan Morgan
2026-03-11 12:34:37 -04:00
committed by GitHub
26 changed files with 673 additions and 254 deletions
+2 -1
View File
@@ -204,7 +204,8 @@ const SETTINGS_SCHEMA = {
description: oneLine`
The default approval mode for tool execution.
'default' prompts for approval, 'auto_edit' auto-approves edit tools,
and 'plan' is read-only mode. 'yolo' is not supported yet.
and 'plan' is read-only mode. YOLO mode (auto-approve all actions) can
only be enabled via command line (--yolo or --approval-mode=yolo).
`,
showInDialog: true,
options: [
@@ -17,6 +17,7 @@ vi.mock('@google/gemini-cli-core', async () => {
...actual,
uiTelemetryService: {
setLastPromptTokenCount: vi.fn(),
clear: vi.fn(),
},
};
});
@@ -74,17 +75,16 @@ describe('clearCommand', () => {
expect(mockResetChat).toHaveBeenCalledTimes(1);
expect(mockHintClear).toHaveBeenCalledTimes(1);
expect(uiTelemetryService.setLastPromptTokenCount).toHaveBeenCalledWith(0);
expect(uiTelemetryService.setLastPromptTokenCount).toHaveBeenCalledTimes(1);
expect(uiTelemetryService.clear).toHaveBeenCalled();
expect(uiTelemetryService.clear).toHaveBeenCalledTimes(1);
expect(mockContext.ui.clear).toHaveBeenCalledTimes(1);
// Check the order of operations.
const setDebugMessageOrder = (mockContext.ui.setDebugMessage as Mock).mock
.invocationCallOrder[0];
const resetChatOrder = mockResetChat.mock.invocationCallOrder[0];
const resetTelemetryOrder = (
uiTelemetryService.setLastPromptTokenCount as Mock
).mock.invocationCallOrder[0];
const resetTelemetryOrder = (uiTelemetryService.clear as Mock).mock
.invocationCallOrder[0];
const clearOrder = (mockContext.ui.clear as Mock).mock
.invocationCallOrder[0];
@@ -110,8 +110,8 @@ describe('clearCommand', () => {
'Clearing terminal.',
);
expect(mockResetChat).not.toHaveBeenCalled();
expect(uiTelemetryService.setLastPromptTokenCount).toHaveBeenCalledWith(0);
expect(uiTelemetryService.setLastPromptTokenCount).toHaveBeenCalledTimes(1);
expect(uiTelemetryService.clear).toHaveBeenCalled();
expect(uiTelemetryService.clear).toHaveBeenCalledTimes(1);
expect(nullConfigContext.ui.clear).toHaveBeenCalledTimes(1);
});
});
+13 -15
View File
@@ -23,10 +23,6 @@ export const clearCommand: SlashCommand = {
action: async (context, _args) => {
const geminiClient = context.services.config?.getGeminiClient();
const config = context.services.config;
const chatRecordingService = context.services.config
?.getGeminiClient()
?.getChat()
.getChatRecordingService();
// Fire SessionEnd hook before clearing
const hookSystem = config?.getHookSystem();
@@ -34,6 +30,18 @@ export const clearCommand: SlashCommand = {
await hookSystem.fireSessionEndEvent(SessionEndReason.Clear);
}
// Reset user steering hints
config?.userHintService.clear();
// Start a new conversation recording with a new session ID
// We MUST do this before calling resetChat() so the new ChatRecordingService
// initialized by GeminiChat picks up the new session ID.
let newSessionId: string | undefined;
if (config) {
newSessionId = randomUUID();
config.setSessionId(newSessionId);
}
if (geminiClient) {
context.ui.setDebugMessage('Clearing terminal and resetting chat.');
// If resetChat fails, the exception will propagate and halt the command,
@@ -43,16 +51,6 @@ export const clearCommand: SlashCommand = {
context.ui.setDebugMessage('Clearing terminal.');
}
// Reset user steering hints
config?.userHintService.clear();
// Start a new conversation recording with a new session ID
if (config && chatRecordingService) {
const newSessionId = randomUUID();
config.setSessionId(newSessionId);
chatRecordingService.initialize();
}
// Fire SessionStart hook after clearing
let result;
if (hookSystem) {
@@ -69,7 +67,7 @@ export const clearCommand: SlashCommand = {
await flushTelemetry(config);
}
uiTelemetryService.setLastPromptTokenCount(0);
uiTelemetryService.clear(newSessionId);
context.ui.clear();
if (result?.systemMessage) {
@@ -238,6 +238,34 @@ describe('SessionStatsContext', () => {
unmount();
});
it('should update session ID and reset stats when the uiTelemetryService emits a clear event', () => {
const contextRef: MutableRefObject<
ReturnType<typeof useSessionStats> | undefined
> = { current: undefined };
const { unmount } = render(
<SessionStatsProvider>
<TestHarness contextRef={contextRef} />
</SessionStatsProvider>,
);
const initialStartTime = contextRef.current?.stats.sessionStartTime;
const newSessionId = 'new-session-id';
act(() => {
uiTelemetryService.emit('clear', newSessionId);
});
const stats = contextRef.current?.stats;
expect(stats?.sessionId).toBe(newSessionId);
expect(stats?.promptCount).toBe(0);
expect(stats?.sessionStartTime.getTime()).toBeGreaterThanOrEqual(
initialStartTime!.getTime(),
);
unmount();
});
it('should throw an error when useSessionStats is used outside of a provider', () => {
const onError = vi.fn();
// Suppress console.error from React for this test
@@ -216,7 +216,17 @@ export const SessionStatsProvider: React.FC<{ children: React.ReactNode }> = ({
});
};
const handleClear = (newSessionId?: string) => {
setStats((prevState) => ({
...prevState,
sessionId: newSessionId || prevState.sessionId,
sessionStartTime: new Date(),
promptCount: 0,
}));
};
uiTelemetryService.on('update', handleUpdate);
uiTelemetryService.on('clear', handleClear);
// Set initial state
handleUpdate({
metrics: uiTelemetryService.getMetrics(),
@@ -225,6 +235,7 @@ export const SessionStatsProvider: React.FC<{ children: React.ReactNode }> = ({
return () => {
uiTelemetryService.off('update', handleUpdate);
uiTelemetryService.off('clear', handleClear);
};
}, []);
@@ -23,6 +23,7 @@ import {
import {
coreEvents,
convertSessionToClientHistory,
uiTelemetryService,
} from '@google/gemini-cli-core';
// Mock modules
@@ -36,6 +37,17 @@ vi.mock('../../utils/sessionUtils.js', async (importOriginal) => {
getSessionFiles: vi.fn(),
};
});
vi.mock('@google/gemini-cli-core', async (importOriginal) => {
const actual =
await importOriginal<typeof import('@google/gemini-cli-core')>();
return {
...actual,
uiTelemetryService: {
clear: vi.fn(),
hydrate: vi.fn(),
},
};
});
const MOCKED_PROJECT_TEMP_DIR = '/test/project/temp';
const MOCKED_CHATS_DIR = '/test/project/temp/chats';
@@ -102,6 +114,7 @@ describe('useSessionBrowser', () => {
expect(mockConfig.setSessionId).toHaveBeenCalledWith(
'existing-session-456',
);
expect(uiTelemetryService.hydrate).toHaveBeenCalledWith(mockConversation);
expect(result.current.isSessionBrowserOpen).toBe(false);
expect(mockOnLoadHistory).toHaveBeenCalled();
});
@@ -16,6 +16,7 @@ import type {
import {
coreEvents,
convertSessionToClientHistory,
uiTelemetryService,
} from '@google/gemini-cli-core';
import type { SessionInfo } from '../../utils/sessionUtils.js';
import { convertSessionToHistoryFormats } from '../../utils/sessionUtils.js';
@@ -68,6 +69,7 @@ export const useSessionBrowser = (
// Use the old session's ID to continue it.
const existingSessionId = conversation.sessionId;
config.setSessionId(existingSessionId);
uiTelemetryService.hydrate(conversation);
const resumedSessionData = {
conversation,
+1
View File
@@ -134,6 +134,7 @@ export class KeyBinding {
'insert',
'numlock',
'scrolllock',
'printscreen',
'numpad_multiply',
'numpad_add',
'numpad_separator',
@@ -375,7 +375,7 @@ describe('telemetry', () => {
expect(mockServer.recordConversationInteraction).toHaveBeenCalledWith(
expect.objectContaining({
language: 'TypeScript',
language: 'typescript',
}),
);
});
@@ -408,7 +408,7 @@ describe('telemetry', () => {
expect(mockServer.recordConversationInteraction).toHaveBeenCalledWith(
expect.objectContaining({
language: 'Python',
language: 'python',
}),
);
});
@@ -171,6 +171,7 @@ export class ChatRecordingService {
this.cachedConversation = null;
} else {
// Create new session
this.sessionId = this.config.getSessionId();
const chatsDir = path.join(
this.config.storage.getProjectTempDir(),
'chats',
@@ -1398,12 +1398,11 @@ describe('ShellExecutionService child_process fallback', () => {
expectedSignal,
);
} else {
expect(mockCpSpawn).toHaveBeenCalledWith(expectedCommand, [
'/pid',
String(mockChildProcess.pid),
'/f',
'/t',
]);
expect(mockCpSpawn).toHaveBeenCalledWith(
expectedCommand,
['/pid', String(mockChildProcess.pid), '/f', '/t'],
undefined,
);
}
});
},
@@ -1181,10 +1181,12 @@ export class ShellExecutionService {
await this.cleanupLogStream(pid);
if (activeChild) {
killProcessGroup({ pid }).catch(() => {});
await killProcessGroup({ pid }).catch(() => {});
this.activeChildProcesses.delete(pid);
} else if (activePty) {
killProcessGroup({ pid, pty: activePty.ptyProcess }).catch(() => {});
await killProcessGroup({ pid, pty: activePty.ptyProcess }).catch(
() => {},
);
try {
(activePty.ptyProcess as IPty & { destroy?: () => void }).destroy?.();
} catch {
@@ -18,14 +18,14 @@ describe('getProgrammingLanguage', () => {
{
name: 'file_path is present',
args: { file_path: 'src/test.ts' },
expected: 'TypeScript',
expected: 'typescript',
},
{
name: 'absolute_path is present',
args: { absolute_path: 'src/test.py' },
expected: 'Python',
expected: 'python',
},
{ name: 'path is present', args: { path: 'src/test.go' }, expected: 'Go' },
{ name: 'path is present', args: { path: 'src/test.go' }, expected: 'go' },
{
name: 'no file path is present',
args: {},
@@ -15,6 +15,7 @@ import {
type ApiErrorEvent,
type ApiResponseEvent,
} from './types.js';
import { type ConversationRecord } from '../services/chatRecordingService.js';
import type {
CompletedToolCall,
ErroredToolCall,
@@ -698,6 +699,121 @@ describe('UiTelemetryService', () => {
});
});
describe('clear', () => {
it('should reset metrics and last prompt token count', () => {
// Set up initial state with some metrics
const event = {
'event.name': EVENT_API_RESPONSE,
model: 'gemini-2.5-pro',
duration_ms: 500,
usage: {
input_token_count: 100,
output_token_count: 200,
total_token_count: 300,
cached_content_token_count: 50,
thoughts_token_count: 20,
tool_token_count: 30,
},
} as ApiResponseEvent & { 'event.name': typeof EVENT_API_RESPONSE };
service.addEvent(event);
service.setLastPromptTokenCount(123);
expect(service.getMetrics().models['gemini-2.5-pro']).toBeDefined();
expect(service.getLastPromptTokenCount()).toBe(123);
service.clear();
expect(service.getMetrics().models).toEqual({});
expect(service.getLastPromptTokenCount()).toBe(0);
});
it('should emit clear and update events', () => {
const clearSpy = vi.fn();
const updateSpy = vi.fn();
service.on('clear', clearSpy);
service.on('update', updateSpy);
const newSessionId = 'new-session-id';
service.clear(newSessionId);
expect(clearSpy).toHaveBeenCalledWith(newSessionId);
expect(updateSpy).toHaveBeenCalledOnce();
const { metrics, lastPromptTokenCount } = updateSpy.mock.calls[0][0];
expect(metrics.models).toEqual({});
expect(lastPromptTokenCount).toBe(0);
});
});
describe('hydrate', () => {
it('should aggregate metrics from a ConversationRecord', () => {
const conversation = {
sessionId: 'resumed-session',
messages: [
{
type: 'user',
content: 'Hello',
},
{
type: 'gemini',
model: 'gemini-1.5-pro',
tokens: {
input: 10,
output: 20,
total: 30,
cached: 5,
thoughts: 2,
tool: 3,
},
toolCalls: [
{ name: 'test_tool', status: 'success' },
{ name: 'test_tool', status: 'error' },
],
},
{
type: 'gemini',
model: 'gemini-1.5-pro',
tokens: {
input: 100,
output: 200,
total: 300,
cached: 50,
thoughts: 20,
tool: 30,
},
},
],
} as unknown as ConversationRecord;
const clearSpy = vi.fn();
const updateSpy = vi.fn();
service.on('clear', clearSpy);
service.on('update', updateSpy);
service.hydrate(conversation);
expect(clearSpy).toHaveBeenCalledWith('resumed-session');
const metrics = service.getMetrics();
const modelMetrics = metrics.models['gemini-1.5-pro'];
expect(modelMetrics).toBeDefined();
expect(modelMetrics.tokens.prompt).toBe(110); // 10 + 100
expect(modelMetrics.tokens.candidates).toBe(220); // 20 + 200
expect(modelMetrics.tokens.cached).toBe(55); // 5 + 50
expect(modelMetrics.tokens.thoughts).toBe(22); // 2 + 20
expect(modelMetrics.tokens.tool).toBe(33); // 3 + 30
expect(modelMetrics.tokens.input).toBe(55); // 110 - 55
expect(metrics.tools.totalCalls).toBe(2);
expect(metrics.tools.totalSuccess).toBe(1);
expect(metrics.tools.totalFail).toBe(1);
expect(metrics.tools.byName['test_tool'].count).toBe(2);
expect(service.getLastPromptTokenCount()).toBe(300); // 100 (input) + 200 (output)
expect(updateSpy).toHaveBeenCalled();
});
});
describe('Tool Call Event with Line Count Metadata', () => {
it('should aggregate valid line count metadata', () => {
const toolCall = createFakeCompletedToolCall('test_tool', true, 100);
@@ -16,6 +16,7 @@ import {
} from './types.js';
import { ToolCallDecision } from './tool-call-decision.js';
import { type ConversationRecord } from '../services/chatRecordingService.js';
export type UiEvent =
| (ApiResponseEvent & { 'event.name': typeof EVENT_API_RESPONSE })
@@ -185,6 +186,96 @@ export class UiTelemetryService extends EventEmitter {
});
}
clear(newSessionId?: string): void {
this.#metrics = createInitialMetrics();
this.#lastPromptTokenCount = 0;
this.emit('clear', newSessionId);
this.emit('update', {
metrics: this.#metrics,
lastPromptTokenCount: this.#lastPromptTokenCount,
});
}
/**
* Hydrates the telemetry metrics from a historical conversation record.
* This is used when resuming a session to restore token counts and tool stats.
*/
hydrate(conversation: ConversationRecord): void {
this.clear(conversation.sessionId);
let totalTokensInContext = 0;
for (const message of conversation.messages) {
if (message.type === 'gemini') {
const model = message.model || 'unknown';
const modelMetrics = this.getOrCreateModelMetrics(model);
// Restore API request stats
modelMetrics.api.totalRequests++;
// Restore token metrics
if (message.tokens) {
modelMetrics.tokens.prompt += message.tokens.input;
modelMetrics.tokens.candidates += message.tokens.output;
modelMetrics.tokens.total += message.tokens.total;
modelMetrics.tokens.cached += message.tokens.cached;
modelMetrics.tokens.thoughts += message.tokens.thoughts || 0;
modelMetrics.tokens.tool += message.tokens.tool || 0;
modelMetrics.tokens.input = Math.max(
0,
modelMetrics.tokens.prompt - modelMetrics.tokens.cached,
);
// The total tokens of the last Gemini message represents the context
// size at that point in time.
totalTokensInContext = message.tokens.total;
}
// Restore tool metrics
if (message.toolCalls) {
for (const toolCall of message.toolCalls) {
this.#metrics.tools.totalCalls++;
if (toolCall.status === 'success') {
this.#metrics.tools.totalSuccess++;
} else if (toolCall.status === 'error') {
this.#metrics.tools.totalFail++;
}
if (!this.#metrics.tools.byName[toolCall.name]) {
this.#metrics.tools.byName[toolCall.name] = {
count: 0,
success: 0,
fail: 0,
durationMs: 0,
decisions: {
[ToolCallDecision.ACCEPT]: 0,
[ToolCallDecision.REJECT]: 0,
[ToolCallDecision.MODIFY]: 0,
[ToolCallDecision.AUTO_ACCEPT]: 0,
},
};
}
const toolStats = this.#metrics.tools.byName[toolCall.name];
toolStats.count++;
if (toolCall.status === 'success') {
toolStats.success++;
} else if (toolCall.status === 'error') {
toolStats.fail++;
}
}
}
}
}
this.#lastPromptTokenCount = totalTokensInContext;
this.emit('update', {
metrics: this.#metrics,
lastPromptTokenCount: this.#lastPromptTokenCount,
});
}
private getOrCreateModelMetrics(modelName: string): ModelMetrics {
if (!this.#metrics.models[modelName]) {
this.#metrics.models[modelName] = createInitialModelMetrics();
@@ -0,0 +1,44 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect } from 'vitest';
import { getLanguageFromFilePath } from './language-detection.js';
describe('language-detection', () => {
it('should return correct LSP identifiers for various extensions', () => {
expect(getLanguageFromFilePath('test.ts')).toBe('typescript');
expect(getLanguageFromFilePath('test.js')).toBe('javascript');
expect(getLanguageFromFilePath('test.py')).toBe('python');
expect(getLanguageFromFilePath('test.java')).toBe('java');
expect(getLanguageFromFilePath('test.go')).toBe('go');
expect(getLanguageFromFilePath('test.cs')).toBe('csharp');
expect(getLanguageFromFilePath('test.cpp')).toBe('cpp');
expect(getLanguageFromFilePath('test.sh')).toBe('shellscript');
expect(getLanguageFromFilePath('test.bat')).toBe('bat');
expect(getLanguageFromFilePath('test.json')).toBe('json');
expect(getLanguageFromFilePath('test.md')).toBe('markdown');
expect(getLanguageFromFilePath('test.tsx')).toBe('typescriptreact');
expect(getLanguageFromFilePath('test.jsx')).toBe('javascriptreact');
});
it('should handle uppercase extensions', () => {
expect(getLanguageFromFilePath('TEST.TS')).toBe('typescript');
});
it('should handle filenames without extensions but in map', () => {
expect(getLanguageFromFilePath('.gitignore')).toBe('ignore');
expect(getLanguageFromFilePath('.dockerfile')).toBe('dockerfile');
expect(getLanguageFromFilePath('Dockerfile')).toBe('dockerfile');
});
it('should return undefined for unknown extensions', () => {
expect(getLanguageFromFilePath('test.unknown')).toBeUndefined();
});
it('should return undefined for files without extension or known filename', () => {
expect(getLanguageFromFilePath('just_a_file')).toBeUndefined();
});
});
+98 -89
View File
@@ -6,98 +6,107 @@
import * as path from 'node:path';
/**
* Maps file extensions or filenames to LSP 3.18 language identifiers.
* See: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.18/specification/#textDocumentItem
*/
const extensionToLanguageMap: { [key: string]: string } = {
'.ts': 'TypeScript',
'.js': 'JavaScript',
'.mjs': 'JavaScript',
'.cjs': 'JavaScript',
'.jsx': 'JavaScript',
'.tsx': 'TypeScript',
'.py': 'Python',
'.java': 'Java',
'.go': 'Go',
'.rb': 'Ruby',
'.php': 'PHP',
'.phtml': 'PHP',
'.cs': 'C#',
'.cpp': 'C++',
'.cxx': 'C++',
'.cc': 'C++',
'.c': 'C',
'.h': 'C/C++',
'.hpp': 'C++',
'.swift': 'Swift',
'.kt': 'Kotlin',
'.rs': 'Rust',
'.m': 'Objective-C',
'.mm': 'Objective-C',
'.pl': 'Perl',
'.pm': 'Perl',
'.lua': 'Lua',
'.r': 'R',
'.scala': 'Scala',
'.sc': 'Scala',
'.sh': 'Shell',
'.ps1': 'PowerShell',
'.bat': 'Batch',
'.cmd': 'Batch',
'.sql': 'SQL',
'.html': 'HTML',
'.htm': 'HTML',
'.css': 'CSS',
'.less': 'Less',
'.sass': 'Sass',
'.scss': 'Sass',
'.json': 'JSON',
'.xml': 'XML',
'.yaml': 'YAML',
'.yml': 'YAML',
'.md': 'Markdown',
'.markdown': 'Markdown',
'.dockerfile': 'Dockerfile',
'.vim': 'Vim script',
'.vb': 'Visual Basic',
'.fs': 'F#',
'.clj': 'Clojure',
'.cljs': 'Clojure',
'.dart': 'Dart',
'.ex': 'Elixir',
'.erl': 'Erlang',
'.hs': 'Haskell',
'.lisp': 'Lisp',
'.rkt': 'Racket',
'.groovy': 'Groovy',
'.jl': 'Julia',
'.tex': 'LaTeX',
'.ino': 'Arduino',
'.asm': 'Assembly',
'.s': 'Assembly',
'.toml': 'TOML',
'.vue': 'Vue',
'.svelte': 'Svelte',
'.gohtml': 'Go Template',
'.hbs': 'Handlebars',
'.ejs': 'EJS',
'.erb': 'ERB',
'.jsp': 'JSP',
'.dockerignore': 'Docker',
'.gitignore': 'Git',
'.npmignore': 'npm',
'.editorconfig': 'EditorConfig',
'.prettierrc': 'Prettier',
'.eslintrc': 'ESLint',
'.babelrc': 'Babel',
'.tsconfig': 'TypeScript',
'.flow': 'Flow',
'.graphql': 'GraphQL',
'.proto': 'Protocol Buffers',
'.ts': 'typescript',
'.js': 'javascript',
'.mjs': 'javascript',
'.cjs': 'javascript',
'.jsx': 'javascriptreact',
'.tsx': 'typescriptreact',
'.py': 'python',
'.java': 'java',
'.go': 'go',
'.rb': 'ruby',
'.php': 'php',
'.phtml': 'php',
'.cs': 'csharp',
'.cpp': 'cpp',
'.cxx': 'cpp',
'.cc': 'cpp',
'.c': 'c',
'.h': 'c',
'.hpp': 'cpp',
'.swift': 'swift',
'.kt': 'kotlin',
'.rs': 'rust',
'.m': 'objective-c',
'.mm': 'objective-cpp',
'.pl': 'perl',
'.pm': 'perl',
'.lua': 'lua',
'.r': 'r',
'.scala': 'scala',
'.sc': 'scala',
'.sh': 'shellscript',
'.ps1': 'powershell',
'.bat': 'bat',
'.cmd': 'bat',
'.sql': 'sql',
'.html': 'html',
'.htm': 'html',
'.css': 'css',
'.less': 'less',
'.sass': 'sass',
'.scss': 'scss',
'.json': 'json',
'.xml': 'xml',
'.yaml': 'yaml',
'.yml': 'yaml',
'.md': 'markdown',
'.markdown': 'markdown',
'.dockerfile': 'dockerfile',
'.vim': 'vim',
'.vb': 'vb',
'.fs': 'fsharp',
'.clj': 'clojure',
'.cljs': 'clojure',
'.dart': 'dart',
'.ex': 'elixir',
'.erl': 'erlang',
'.hs': 'haskell',
'.lisp': 'lisp',
'.rkt': 'racket',
'.groovy': 'groovy',
'.jl': 'julia',
'.tex': 'latex',
'.ino': 'arduino',
'.asm': 'assembly',
'.s': 'assembly',
'.toml': 'toml',
'.vue': 'vue',
'.svelte': 'svelte',
'.gohtml': 'gohtml', // Not in standard LSP well-known list but kept for compatibility
'.hbs': 'handlebars',
'.ejs': 'ejs',
'.erb': 'erb',
'.jsp': 'jsp',
'.dockerignore': 'ignore',
'.gitignore': 'ignore',
'.npmignore': 'ignore',
'.editorconfig': 'properties',
'.prettierrc': 'json',
'.eslintrc': 'json',
'.babelrc': 'json',
'.tsconfig': 'json',
'.flow': 'javascript',
'.graphql': 'graphql',
'.proto': 'proto',
};
export function getLanguageFromFilePath(filePath: string): string | undefined {
const extension = path.extname(filePath).toLowerCase();
if (extension) {
return extensionToLanguageMap[extension];
}
const filename = path.basename(filePath).toLowerCase();
return extensionToLanguageMap[`.${filename}`];
const extension = path.extname(filePath).toLowerCase();
const candidates = [
extension, // 1. Standard extension (e.g., '.js')
filename, // 2. Exact filename (e.g., 'dockerfile')
`.${filename}`, // 3. Dot-prefixed filename (e.g., '.gitignore')
];
const match = candidates.find((key) => key in extensionToLanguageMap);
return match ? extensionToLanguageMap[match] : undefined;
}
+44 -10
View File
@@ -4,27 +4,37 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import {
describe,
it,
expect,
vi,
beforeEach,
afterEach,
type Mock,
type MockInstance,
} from 'vitest';
import os from 'node:os';
import { spawn as cpSpawn } from 'node:child_process';
import { killProcessGroup, SIGKILL_TIMEOUT_MS } from './process-utils.js';
import { spawnAsync } from './shell-utils.js';
vi.mock('node:os');
vi.mock('node:child_process');
vi.mock('./shell-utils.js');
describe('process-utils', () => {
const mockProcessKill = vi
.spyOn(process, 'kill')
.mockImplementation(() => true);
const mockSpawn = vi.mocked(cpSpawn);
let mockProcessKill: MockInstance;
let mockSpawnAsync: Mock;
beforeEach(() => {
vi.clearAllMocks();
vi.useFakeTimers();
mockProcessKill = vi.spyOn(process, 'kill').mockImplementation(() => true);
mockSpawnAsync = vi.mocked(spawnAsync);
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});
describe('killProcessGroup', () => {
@@ -33,7 +43,7 @@ describe('process-utils', () => {
await killProcessGroup({ pid: 1234 });
expect(mockSpawn).toHaveBeenCalledWith('taskkill', [
expect(mockSpawnAsync).toHaveBeenCalledWith('taskkill', [
'/pid',
'1234',
'/f',
@@ -42,14 +52,20 @@ describe('process-utils', () => {
expect(mockProcessKill).not.toHaveBeenCalled();
});
it('should use pty.kill() on Windows if pty is provided', async () => {
it('should use pty.kill() on Windows if pty is provided and also taskkill for descendants', async () => {
vi.mocked(os.platform).mockReturnValue('win32');
const mockPty = { kill: vi.fn() };
await killProcessGroup({ pid: 1234, pty: mockPty });
expect(mockPty.kill).toHaveBeenCalled();
expect(mockSpawn).not.toHaveBeenCalled();
// taskkill is also called to reap orphaned descendant processes
expect(mockSpawnAsync).toHaveBeenCalledWith('taskkill', [
'/pid',
'1234',
'/f',
'/t',
]);
});
it('should kill the process group on Unix with SIGKILL by default', async () => {
@@ -130,5 +146,23 @@ describe('process-utils', () => {
expect(mockPty.kill).toHaveBeenCalledWith('SIGKILL');
});
it('should attempt process group kill on Unix after pty fallback to reap orphaned descendants', async () => {
vi.mocked(os.platform).mockReturnValue('linux');
// First call (group kill) throws to trigger PTY fallback
mockProcessKill.mockImplementationOnce(() => {
throw new Error('ESRCH');
});
// Second call (group kill retry after pty.kill) should succeed
mockProcessKill.mockImplementationOnce(() => true);
const mockPty = { kill: vi.fn() };
await killProcessGroup({ pid: 1234, pty: mockPty });
// Group kill should be called first to ensure it's hit before PTY leader dies
expect(mockProcessKill).toHaveBeenCalledWith(-1234, 'SIGKILL');
// Then PTY kill should be called
expect(mockPty.kill).toHaveBeenCalledWith('SIGKILL');
});
});
});
+19 -4
View File
@@ -5,7 +5,8 @@
*/
import os from 'node:os';
import { spawn as cpSpawn } from 'node:child_process';
import { spawnAsync } from './shell-utils.js';
/** Default timeout for SIGKILL escalation on Unix systems. */
export const SIGKILL_TIMEOUT_MS = 200;
@@ -44,8 +45,12 @@ export async function killProcessGroup(options: KillOptions): Promise<void> {
} catch {
// Ignore errors for dead processes
}
} else {
cpSpawn('taskkill', ['/pid', pid.toString(), '/f', '/t']);
}
// Invoke taskkill to ensure the entire tree is terminated and any orphaned descendant processes are reaped.
try {
await spawnAsync('taskkill', ['/pid', pid.toString(), '/f', '/t']);
} catch (_e) {
// Ignore errors if the process tree is already dead
}
return;
}
@@ -73,14 +78,24 @@ export async function killProcessGroup(options: KillOptions): Promise<void> {
if (pty) {
if (escalate) {
try {
// Attempt the group kill BEFORE the pty session leader dies
process.kill(-pid, 'SIGTERM');
pty.kill('SIGTERM');
await new Promise((res) => setTimeout(res, SIGKILL_TIMEOUT_MS));
if (!isExited()) pty.kill('SIGKILL');
if (!isExited()) {
try {
process.kill(-pid, 'SIGKILL');
} catch {
// Ignore
}
pty.kill('SIGKILL');
}
} catch {
// Ignore
}
} else {
try {
process.kill(-pid, 'SIGKILL'); // Group kill first
pty.kill('SIGKILL');
} catch {
// Ignore