Migrate console to coreEvents.emitFeedback or debugLogger (#15219)

This commit is contained in:
Adib234
2025-12-29 15:46:10 -05:00
committed by GitHub
parent dcd2449b1a
commit 10ae84869a
66 changed files with 564 additions and 425 deletions
+1 -9
View File
@@ -842,16 +842,8 @@ Logging in with Google... Restarting Gemini CLI to continue.
const handleClearScreen = useCallback(() => {
historyManager.clearItems();
clearConsoleMessagesState();
if (!isAlternateBuffer) {
console.clear();
}
refreshStatic();
}, [
historyManager,
clearConsoleMessagesState,
refreshStatic,
isAlternateBuffer,
]);
}, [historyManager, clearConsoleMessagesState, refreshStatic]);
const { handleInput: vimHandleInput } = useVim(buffer, handleFinalSubmit);
@@ -4,14 +4,30 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render } from 'ink-testing-library';
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
import { render } from '../test-utils/render.js';
import { act } from 'react';
import { IdeIntegrationNudge } from './IdeIntegrationNudge.js';
import { KeypressProvider } from './contexts/KeypressContext.js';
import { debugLogger } from '@google/gemini-cli-core';
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
// Mock debugLogger
vi.mock('@google/gemini-cli-core', async (importOriginal) => {
const actual =
await importOriginal<typeof import('@google/gemini-cli-core')>();
return {
...actual,
debugLogger: {
log: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn(),
},
};
});
describe('IdeIntegrationNudge', () => {
const defaultProps = {
ide: {
@@ -21,24 +37,20 @@ describe('IdeIntegrationNudge', () => {
onComplete: vi.fn(),
};
const originalError = console.error;
afterEach(() => {
console.error = originalError;
vi.restoreAllMocks();
vi.unstubAllEnvs();
});
beforeEach(() => {
console.error = (...args) => {
vi.mocked(debugLogger.warn).mockImplementation((...args) => {
if (
typeof args[0] === 'string' &&
/was not wrapped in act/.test(args[0])
) {
return;
}
originalError.call(console, ...args);
};
});
vi.stubEnv('GEMINI_CLI_IDE_SERVER_PORT', '');
vi.stubEnv('GEMINI_CLI_IDE_WORKSPACE_PATH', '');
});
@@ -5,12 +5,27 @@
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render } from 'ink-testing-library';
import { render } from '../../test-utils/render.js';
import { act } from 'react';
import { AuthInProgress } from './AuthInProgress.js';
import { useKeypress, type Key } from '../hooks/useKeypress.js';
import { debugLogger } from '@google/gemini-cli-core';
// Mock dependencies
vi.mock('@google/gemini-cli-core', async (importOriginal) => {
const actual =
await importOriginal<typeof import('@google/gemini-cli-core')>();
return {
...actual,
debugLogger: {
log: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn(),
},
};
});
vi.mock('../hooks/useKeypress.js', () => ({
useKeypress: vi.fn(),
}));
@@ -22,24 +37,20 @@ vi.mock('../components/CliSpinner.js', () => ({
describe('AuthInProgress', () => {
const onTimeout = vi.fn();
const originalError = console.error;
beforeEach(() => {
vi.clearAllMocks();
vi.useFakeTimers();
console.error = (...args) => {
vi.mocked(debugLogger.error).mockImplementation((...args) => {
if (
typeof args[0] === 'string' &&
args[0].includes('was not wrapped in act')
) {
return;
}
originalError.call(console, ...args);
};
});
});
afterEach(() => {
console.error = originalError;
vi.useRealTimers();
});
@@ -12,6 +12,7 @@ import type { LoadedSettings } from '../../config/settings.js';
import { KeypressProvider } from '../contexts/KeypressContext.js';
import { act } from 'react';
import { waitFor } from '../../test-utils/async.js';
import { debugLogger } from '@google/gemini-cli-core';
vi.mock('@google/gemini-cli-core', async (importOriginal) => {
const actual =
@@ -101,7 +102,7 @@ describe('EditorSettingsDialog', () => {
await waitFor(() => {
const frame = lastFrame() || '';
if (!frame.includes('> Apply To')) {
console.log(
debugLogger.debug(
'Waiting for scope focus. Current frame:',
JSON.stringify(frame),
);
@@ -166,7 +167,7 @@ describe('EditorSettingsDialog', () => {
const frame = lastFrame() || '';
if (!frame.includes('(Also modified')) {
console.log(
debugLogger.debug(
'Modified message test failure. Frame:',
JSON.stringify(frame),
);
@@ -24,6 +24,7 @@ import {
EDITOR_DISPLAY_NAMES,
} from '@google/gemini-cli-core';
import { useKeypress } from '../hooks/useKeypress.js';
import { coreEvents } from '@google/gemini-cli-core';
interface EditorDialogProps {
onSelect: (
@@ -68,7 +69,10 @@ export function EditorSettingsDialog({
)
: 0;
if (editorIndex === -1) {
console.error(`Editor is not supported: ${currentPreference}`);
coreEvents.emitFeedback(
'error',
`Editor is not supported: ${currentPreference}`,
);
editorIndex = 0;
}
@@ -8,6 +8,7 @@ import { vi, describe, it, expect, beforeEach } from 'vitest';
import * as processUtils from '../../utils/processUtils.js';
import { renderWithProviders } from '../../test-utils/render.js';
import { IdeTrustChangeDialog } from './IdeTrustChangeDialog.js';
import { debugLogger } from '@google/gemini-cli-core';
describe('IdeTrustChangeDialog', () => {
beforeEach(() => {
@@ -39,8 +40,8 @@ describe('IdeTrustChangeDialog', () => {
});
it('renders a generic message and logs an error for NONE reason', () => {
const consoleErrorSpy = vi
.spyOn(console, 'error')
const debugLoggerWarnSpy = vi
.spyOn(debugLogger, 'warn')
.mockImplementation(() => {});
const { lastFrame } = renderWithProviders(
<IdeTrustChangeDialog reason="NONE" />,
@@ -48,7 +49,7 @@ describe('IdeTrustChangeDialog', () => {
const frameText = lastFrame();
expect(frameText).toContain('Workspace trust has changed.');
expect(consoleErrorSpy).toHaveBeenCalledWith(
expect(debugLoggerWarnSpy).toHaveBeenCalledWith(
'IdeTrustChangeDialog rendered with unexpected reason "NONE"',
);
});
@@ -9,6 +9,7 @@ import { theme } from '../semantic-colors.js';
import { useKeypress } from '../hooks/useKeypress.js';
import { relaunchApp } from '../../utils/processUtils.js';
import { type RestartReason } from '../hooks/useIdeTrustListener.js';
import { debugLogger } from '@google/gemini-cli-core';
interface IdeTrustChangeDialogProps {
reason: RestartReason;
@@ -28,7 +29,7 @@ export const IdeTrustChangeDialog = ({ reason }: IdeTrustChangeDialogProps) => {
let message = 'Workspace trust has changed.';
if (reason === 'NONE') {
// This should not happen, but provides a fallback and a debug log.
console.error(
debugLogger.warn(
'IdeTrustChangeDialog rendered with unexpected reason "NONE"',
);
} else if (reason === 'CONNECTION_CHANGE') {
@@ -15,7 +15,7 @@ import {
calculateTransformedLine,
} from './shared/text-buffer.js';
import type { Config } from '@google/gemini-cli-core';
import { ApprovalMode } from '@google/gemini-cli-core';
import { ApprovalMode, debugLogger } from '@google/gemini-cli-core';
import * as path from 'node:path';
import type { CommandContext, SlashCommand } from '../commands/types.js';
import { CommandKind } from '../commands/types.js';
@@ -577,8 +577,8 @@ describe('InputPrompt', () => {
});
it('should handle errors during clipboard operations', async () => {
const consoleErrorSpy = vi
.spyOn(console, 'error')
const debugLoggerErrorSpy = vi
.spyOn(debugLogger, 'error')
.mockImplementation(() => {});
vi.mocked(clipboardUtils.clipboardHasImage).mockRejectedValue(
new Error('Clipboard error'),
@@ -592,14 +592,14 @@ describe('InputPrompt', () => {
stdin.write('\x16'); // Ctrl+V
});
await waitFor(() => {
expect(consoleErrorSpy).toHaveBeenCalledWith(
expect(debugLoggerErrorSpy).toHaveBeenCalledWith(
'Error handling clipboard image:',
expect.any(Error),
);
});
expect(mockBuffer.setText).not.toHaveBeenCalled();
consoleErrorSpy.mockRestore();
debugLoggerErrorSpy.mockRestore();
unmount();
});
});
@@ -24,7 +24,7 @@ import { useKeypress } from '../hooks/useKeypress.js';
import { keyMatchers, Command } from '../keyMatchers.js';
import type { CommandContext, SlashCommand } from '../commands/types.js';
import type { Config } from '@google/gemini-cli-core';
import { ApprovalMode } from '@google/gemini-cli-core';
import { ApprovalMode, debugLogger } from '@google/gemini-cli-core';
import {
parseInputForHighlighting,
parseSegmentsFromTokens,
@@ -354,7 +354,7 @@ export const InputPrompt: React.FC<InputPromptProps> = ({
const offset = buffer.getOffset();
buffer.replaceRangeByOffset(offset, offset, textToInsert);
} catch (error) {
console.error('Error handling clipboard image:', error);
debugLogger.error('Error handling clipboard image:', error);
}
}, [buffer, config]);
@@ -12,7 +12,7 @@ import { theme } from '../semantic-colors.js';
import { StreamingState } from '../types.js';
import { UpdateNotification } from './UpdateNotification.js';
import { GEMINI_DIR, Storage } from '@google/gemini-cli-core';
import { GEMINI_DIR, Storage, debugLogger } from '@google/gemini-cli-core';
import * as fs from 'node:fs/promises';
import os from 'node:os';
@@ -66,7 +66,7 @@ export const Notifications = () => {
});
await fs.writeFile(screenReaderNudgeFilePath, 'true');
} catch (error) {
console.error('Error storing screen reader nudge', error);
debugLogger.error('Error storing screen reader nudge', error);
}
}
};
@@ -42,7 +42,7 @@ import {
type SettingsValue,
TOGGLE_TYPES,
} from '../../config/settingsSchema.js';
import { debugLogger } from '@google/gemini-cli-core';
import { coreEvents, debugLogger } from '@google/gemini-cli-core';
import { keyMatchers, Command } from '../keyMatchers.js';
import type { Config } from '@google/gemini-cli-core';
import { useUIState } from '../contexts/UIStateContext.js';
@@ -254,7 +254,11 @@ export function SettingsDialog({
if (key === 'general.vimMode' && newValue !== vimEnabled) {
// Call toggleVimEnabled to sync the VimModeContext local state
toggleVimEnabled().catch((error) => {
console.error('Failed to toggle vim mode:', error);
coreEvents.emitFeedback(
'error',
'Failed to toggle vim mode:',
error,
);
});
}
@@ -10,6 +10,7 @@ import stringWidth from 'string-width';
import { theme } from '../../semantic-colors.js';
import { toCodePoints } from '../../utils/textUtils.js';
import { useOverflowActions } from '../../contexts/OverflowContext.js';
import { debugLogger } from '@google/gemini-cli-core';
let enableDebugLog = false;
@@ -28,7 +29,7 @@ function debugReportError(message: string, element: React.ReactNode) {
if (!enableDebugLog) return;
if (!React.isValidElement(element)) {
console.error(
debugLogger.warn(
message,
`Invalid element: '${String(element)}' typeof=${typeof element}`,
);
@@ -44,10 +45,13 @@ function debugReportError(message: string, element: React.ReactNode) {
const lineNumber = elementWithSource._source?.lineNumber;
sourceMessage = fileName ? `${fileName}:${lineNumber}` : '<Unknown file>';
} catch (error) {
console.error('Error while trying to get file name:', error);
debugLogger.warn('Error while trying to get file name:', error);
}
console.error(message, `${String(element.type)}. Source: ${sourceMessage}`);
debugLogger.warn(
message,
`${String(element.type)}. Source: ${sourceMessage}`,
);
}
interface MaxSizedBoxProps {
children?: React.ReactNode;
@@ -10,7 +10,12 @@ import os from 'node:os';
import pathMod from 'node:path';
import * as path from 'node:path';
import { useState, useCallback, useEffect, useMemo, useReducer } from 'react';
import { coreEvents, CoreEvent, unescapePath } from '@google/gemini-cli-core';
import {
coreEvents,
CoreEvent,
debugLogger,
unescapePath,
} from '@google/gemini-cli-core';
import {
toCodePoints,
cpLen,
@@ -1411,7 +1416,7 @@ function textBufferReducerLogic(
break;
default: {
const exhaustiveCheck: never = dir;
console.error(
debugLogger.error(
`Unknown visual movement direction: ${exhaustiveCheck}`,
);
return state;
@@ -1751,7 +1756,7 @@ function textBufferReducerLogic(
default: {
const exhaustiveCheck: never = action;
console.error(`Unknown action encountered: ${exhaustiveCheck}`);
debugLogger.error(`Unknown action encountered: ${exhaustiveCheck}`);
return state;
}
}
@@ -2173,7 +2178,11 @@ export function useTextBuffer({
newText = newText.replace(/\r\n?/g, '\n');
dispatch({ type: 'set_text', payload: newText, pushToUndo: false });
} catch (err) {
console.error('[useTextBuffer] external editor error', err);
coreEvents.emitFeedback(
'error',
'[useTextBuffer] external editor error',
err,
);
} finally {
coreEvents.emit(CoreEvent.ExternalEditorClosed);
if (wasRaw) setRawMode?.(true);
@@ -502,7 +502,7 @@ export async function handleAtCommand({
const errorMessages = resourceReadDisplays
.filter((d) => d.status === ToolCallStatus.Error)
.map((d) => d.resultDisplay);
console.error(errorMessages);
debugLogger.error(errorMessages);
const errorMsg = `Exiting due to an error processing the @ command: ${firstError.resultDisplay}`;
return { processedQuery: null, error: errorMsg };
}
@@ -244,7 +244,6 @@ describe('useSlashCommandProcessor', () => {
});
expect(mockClearItems).toHaveBeenCalled();
expect(console.clear).not.toHaveBeenCalled();
});
it('should call console.clear if alternate buffer is not active', async () => {
@@ -262,7 +261,6 @@ describe('useSlashCommandProcessor', () => {
});
expect(mockClearItems).toHaveBeenCalled();
expect(console.clear).toHaveBeenCalled();
});
});
@@ -50,7 +50,6 @@ import {
type ExtensionUpdateStatus,
} from '../state/extensions.js';
import { appEvents } from '../../utils/events.js';
import { useAlternateBuffer } from './useAlternateBuffer.js';
import {
LogoutConfirmationDialog,
LogoutChoice,
@@ -96,7 +95,6 @@ export const useSlashCommandProcessor = (
const [commands, setCommands] = useState<readonly SlashCommand[] | undefined>(
undefined,
);
const alternateBuffer = useAlternateBuffer();
const [reloadTrigger, setReloadTrigger] = useState(0);
const reloadCommands = useCallback(() => {
@@ -212,9 +210,6 @@ export const useSlashCommandProcessor = (
addItem,
clear: () => {
clearItems();
if (!alternateBuffer) {
console.clear();
}
refreshStatic();
setBannerVisible(false);
},
@@ -238,7 +233,6 @@ export const useSlashCommandProcessor = (
},
}),
[
alternateBuffer,
config,
settings,
gitService,
@@ -8,7 +8,10 @@ import { useEffect } from 'react';
import type { Config } from '@google/gemini-cli-core';
import { loadTrustedFolders } from '../../config/trustedFolders.js';
import { expandHomeDir } from '../utils/directoryUtils.js';
import { refreshServerHierarchicalMemory } from '@google/gemini-cli-core';
import {
debugLogger,
refreshServerHierarchicalMemory,
} from '@google/gemini-cli-core';
import { MultiFolderTrustDialog } from '../components/MultiFolderTrustDialog.js';
import type { UseHistoryManagerReturn } from './useHistoryManager.js';
import { MessageType, type HistoryItem } from '../types.js';
@@ -133,7 +136,7 @@ export function useIncludeDirsTrust(
}
if (undefinedTrustDirs.length > 0) {
console.log(
debugLogger.log(
'Creating custom dialog with undecidedDirs:',
undefinedTrustDirs,
);
@@ -7,6 +7,7 @@
import { useReducer, useRef, useEffect, useCallback } from 'react';
import { useKeypress, type Key } from './useKeypress.js';
import { keyMatchers, Command } from '../keyMatchers.js';
import { debugLogger } from '@google/gemini-cli-core';
export interface SelectionListItem<T> {
key: string;
@@ -198,7 +199,7 @@ function selectionListReducer(
default: {
const exhaustiveCheck: never = action;
console.error(`Unknown selection list action: ${exhaustiveCheck}`);
debugLogger.warn(`Unknown selection list action: ${exhaustiveCheck}`);
return state;
}
}
@@ -19,6 +19,7 @@ import type {
ConversationRecord,
MessageRecord,
} from '@google/gemini-cli-core';
import { coreEvents } from '@google/gemini-cli-core';
// Mock modules
vi.mock('fs/promises');
@@ -52,6 +53,7 @@ describe('useSessionBrowser', () => {
beforeEach(() => {
vi.resetAllMocks();
vi.spyOn(coreEvents, 'emitFeedback').mockImplementation(() => {});
mockedPath.join.mockImplementation((...args) => args.join('/'));
vi.mocked(mockConfig.storage.getProjectTempDir).mockReturnValue(
MOCKED_PROJECT_TEMP_DIR,
@@ -100,9 +102,6 @@ describe('useSessionBrowser', () => {
fileName: MOCKED_FILENAME,
} as SessionInfo;
mockedFs.readFile.mockRejectedValue(new Error('File not found'));
const consoleErrorSpy = vi
.spyOn(console, 'error')
.mockImplementation(() => {});
const { result } = renderHook(() =>
useSessionBrowser(mockConfig, mockOnLoadHistory),
@@ -112,9 +111,12 @@ describe('useSessionBrowser', () => {
await result.current.handleResumeSession(mockSession);
});
expect(consoleErrorSpy).toHaveBeenCalled();
expect(coreEvents.emitFeedback).toHaveBeenCalledWith(
'error',
'Error resuming session:',
expect.any(Error),
);
expect(result.current.isSessionBrowserOpen).toBe(false);
consoleErrorSpy.mockRestore();
});
it('should handle JSON parse error', async () => {
@@ -124,9 +126,6 @@ describe('useSessionBrowser', () => {
fileName: MOCKED_FILENAME,
} as SessionInfo;
mockedFs.readFile.mockResolvedValue('invalid json');
const consoleErrorSpy = vi
.spyOn(console, 'error')
.mockImplementation(() => {});
const { result } = renderHook(() =>
useSessionBrowser(mockConfig, mockOnLoadHistory),
@@ -136,9 +135,12 @@ describe('useSessionBrowser', () => {
await result.current.handleResumeSession(mockSession);
});
expect(consoleErrorSpy).toHaveBeenCalled();
expect(coreEvents.emitFeedback).toHaveBeenCalledWith(
'error',
'Error resuming session:',
expect.any(Error),
);
expect(result.current.isSessionBrowserOpen).toBe(false);
consoleErrorSpy.mockRestore();
});
});
@@ -14,7 +14,7 @@ import type {
ResumedSessionData,
} from '@google/gemini-cli-core';
import type { Part } from '@google/genai';
import { partListUnionToString } from '@google/gemini-cli-core';
import { partListUnionToString, coreEvents } from '@google/gemini-cli-core';
import type { SessionInfo } from '../../utils/sessionUtils.js';
import { MessageType, ToolCallStatus } from '../types.js';
@@ -79,7 +79,7 @@ export const useSessionBrowser = (
resumedSessionData,
);
} catch (error) {
console.error('Error resuming session:', error);
coreEvents.emitFeedback('error', 'Error resuming session:', error);
setIsSessionBrowserOpen(false);
}
},
@@ -103,7 +103,7 @@ export const useSessionBrowser = (
chatRecordingService.deleteSession(session.file);
}
} catch (error) {
console.error('Error deleting session:', error);
coreEvents.emitFeedback('error', 'Error deleting session:', error);
throw error;
}
},
+3 -3
View File
@@ -7,7 +7,7 @@
import { useState, useEffect, useCallback } from 'react';
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import { isNodeError, Storage } from '@google/gemini-cli-core';
import { debugLogger, isNodeError, Storage } from '@google/gemini-cli-core';
const MAX_HISTORY_LENGTH = 100;
@@ -52,7 +52,7 @@ async function readHistoryFile(filePath: string): Promise<string[]> {
return result;
} catch (err) {
if (isNodeError(err) && err.code === 'ENOENT') return [];
console.error('Error reading history:', err);
debugLogger.error('Error reading history:', err);
return [];
}
}
@@ -65,7 +65,7 @@ async function writeHistoryFile(
await fs.mkdir(path.dirname(filePath), { recursive: true });
await fs.writeFile(filePath, history.join('\n'));
} catch (error) {
console.error('Error writing shell history:', error);
debugLogger.error('Error writing shell history:', error);
}
}
@@ -4,6 +4,8 @@
* SPDX-License-Identifier: Apache-2.0
*/
/* eslint-disable no-console */
import util from 'node:util';
import type { ConsoleMessageItem } from '../types.js';
@@ -8,6 +8,7 @@ import React from 'react';
import { Text } from 'ink';
import { theme } from '../semantic-colors.js';
import stringWidth from 'string-width';
import { debugLogger } from '@google/gemini-cli-core';
// Constants for Markdown parsing
const BOLD_MARKER_LENGTH = 2; // For "**"
@@ -144,7 +145,7 @@ const RenderInlineInternal: React.FC<RenderInlineProps> = ({
);
}
} catch (e) {
console.error('Error parsing inline markdown part:', fullMatch, e);
debugLogger.warn('Error parsing inline markdown part:', fullMatch, e);
renderedNode = null;
}