Skip to content

Commit fbf71f8

Browse files
authored
Merge branch 'google-gemini:main' into main
2 parents 4e430ff + 4442e89 commit fbf71f8

File tree

9 files changed

+151
-112
lines changed

9 files changed

+151
-112
lines changed

packages/cli/src/gemini.tsx

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import { getStartupWarnings } from './utils/startupWarnings.js';
2525
import { getUserStartupWarnings } from './utils/userStartupWarnings.js';
2626
import { runNonInteractive } from './nonInteractiveCli.js';
2727
import { loadExtensions, Extension } from './config/extension.js';
28-
import { cleanupCheckpoints } from './utils/cleanup.js';
28+
import { cleanupCheckpoints, registerCleanup } from './utils/cleanup.js';
2929
import { getCliVersion } from './utils/version.js';
3030
import {
3131
ApprovalMode,
@@ -202,7 +202,7 @@ export async function main() {
202202
if (shouldBeInteractive) {
203203
const version = await getCliVersion();
204204
setWindowTitle(basename(workspaceRoot), settings);
205-
render(
205+
const instance = render(
206206
<React.StrictMode>
207207
<AppWrapper
208208
config={config}
@@ -213,6 +213,8 @@ export async function main() {
213213
</React.StrictMode>,
214214
{ exitOnCtrlC: false },
215215
);
216+
217+
registerCleanup(() => instance.unmount());
216218
return;
217219
}
218220
// If not a TTY, read from stdin

packages/cli/src/ui/App.tsx

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,8 @@ import { Help } from './components/Help.js';
4141
import { loadHierarchicalGeminiMemory } from '../config/config.js';
4242
import { LoadedSettings } from '../config/settings.js';
4343
import { Tips } from './components/Tips.js';
44-
import { useConsolePatcher } from './components/ConsolePatcher.js';
44+
import { ConsolePatcher } from './utils/ConsolePatcher.js';
45+
import { registerCleanup } from '../utils/cleanup.js';
4546
import { DetailedMessagesDisplay } from './components/DetailedMessagesDisplay.js';
4647
import { HistoryItemDisplay } from './components/HistoryItemDisplay.js';
4748
import { ContextSummaryDisplay } from './components/ContextSummaryDisplay.js';
@@ -111,6 +112,16 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
111112
handleNewMessage,
112113
clearConsoleMessages: clearConsoleMessagesState,
113114
} = useConsoleMessages();
115+
116+
useEffect(() => {
117+
const consolePatcher = new ConsolePatcher({
118+
onNewMessage: handleNewMessage,
119+
debugMode: config.getDebugMode(),
120+
});
121+
consolePatcher.patch();
122+
registerCleanup(consolePatcher.cleanup);
123+
}, [handleNewMessage, config]);
124+
114125
const { stats: sessionStats } = useSessionStats();
115126
const [staticNeedsRefresh, setStaticNeedsRefresh] = useState(false);
116127
const [staticKey, setStaticKey] = useState(0);
@@ -470,11 +481,6 @@ const App = ({ config, settings, startupWarnings = [], version }: AppProps) => {
470481
}
471482
});
472483

473-
useConsolePatcher({
474-
onNewMessage: handleNewMessage,
475-
debugMode: config.getDebugMode(),
476-
});
477-
478484
useEffect(() => {
479485
if (config) {
480486
setGeminiMdFileCount(config.getGeminiMdFileCount());

packages/cli/src/ui/components/ConsolePatcher.tsx

Lines changed: 0 additions & 60 deletions
This file was deleted.

packages/cli/src/ui/hooks/useAuthCommand.ts

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
clearCachedCredentialFile,
1313
getErrorMessage,
1414
} from '@google/gemini-cli-core';
15+
import { runExitCleanup } from '../../utils/cleanup.js';
1516

1617
export const useAuthCommand = (
1718
settings: LoadedSettings,
@@ -55,11 +56,22 @@ export const useAuthCommand = (
5556
if (authType) {
5657
await clearCachedCredentialFile();
5758
settings.setValue(scope, 'selectedAuthType', authType);
59+
if (authType === AuthType.LOGIN_WITH_GOOGLE && config.getNoBrowser()) {
60+
runExitCleanup();
61+
console.log(
62+
`
63+
----------------------------------------------------------------
64+
Logging in with Google... Please restart Gemini CLI to continue.
65+
----------------------------------------------------------------
66+
`,
67+
);
68+
process.exit(0);
69+
}
5870
}
5971
setIsAuthDialogOpen(false);
6072
setAuthError(null);
6173
},
62-
[settings, setAuthError],
74+
[settings, setAuthError, config],
6375
);
6476

6577
const cancelAuthentication = useCallback(() => {
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* @license
3+
* Copyright 2025 Google LLC
4+
* SPDX-License-Identifier: Apache-2.0
5+
*/
6+
7+
import util from 'util';
8+
import { ConsoleMessageItem } from '../types.js';
9+
10+
interface ConsolePatcherParams {
11+
onNewMessage: (message: Omit<ConsoleMessageItem, 'id'>) => void;
12+
debugMode: boolean;
13+
}
14+
15+
export class ConsolePatcher {
16+
private originalConsoleLog = console.log;
17+
private originalConsoleWarn = console.warn;
18+
private originalConsoleError = console.error;
19+
private originalConsoleDebug = console.debug;
20+
21+
private params: ConsolePatcherParams;
22+
23+
constructor(params: ConsolePatcherParams) {
24+
this.params = params;
25+
}
26+
27+
patch() {
28+
console.log = this.patchConsoleMethod('log', this.originalConsoleLog);
29+
console.warn = this.patchConsoleMethod('warn', this.originalConsoleWarn);
30+
console.error = this.patchConsoleMethod('error', this.originalConsoleError);
31+
console.debug = this.patchConsoleMethod('debug', this.originalConsoleDebug);
32+
}
33+
34+
cleanup = () => {
35+
console.log = this.originalConsoleLog;
36+
console.warn = this.originalConsoleWarn;
37+
console.error = this.originalConsoleError;
38+
console.debug = this.originalConsoleDebug;
39+
};
40+
41+
private formatArgs = (args: unknown[]): string => util.format(...args);
42+
43+
private patchConsoleMethod =
44+
(
45+
type: 'log' | 'warn' | 'error' | 'debug',
46+
originalMethod: (...args: unknown[]) => void,
47+
) =>
48+
(...args: unknown[]) => {
49+
if (this.params.debugMode) {
50+
originalMethod.apply(console, args);
51+
}
52+
53+
if (type !== 'debug' || this.params.debugMode) {
54+
this.params.onNewMessage({
55+
type,
56+
content: this.formatArgs(args),
57+
count: 1,
58+
});
59+
}
60+
};
61+
}

packages/cli/src/utils/cleanup.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,23 @@ import { promises as fs } from 'fs';
88
import { join } from 'path';
99
import { getProjectTempDir } from '@google/gemini-cli-core';
1010

11+
const cleanupFunctions: Array<() => void> = [];
12+
13+
export function registerCleanup(fn: () => void) {
14+
cleanupFunctions.push(fn);
15+
}
16+
17+
export function runExitCleanup() {
18+
for (const fn of cleanupFunctions) {
19+
try {
20+
fn();
21+
} catch (_) {
22+
// Ignore errors during cleanup.
23+
}
24+
}
25+
cleanupFunctions.length = 0; // Clear the array
26+
}
27+
1128
export async function cleanupCheckpoints() {
1229
const tempDir = getProjectTempDir(process.cwd());
1330
const checkpointsDir = join(tempDir, 'checkpoints');

packages/core/src/code_assist/oauth2.test.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -212,9 +212,7 @@ describe('oauth2', () => {
212212
};
213213
(readline.createInterface as Mock).mockReturnValue(mockReadline);
214214

215-
const consoleErrorSpy = vi
216-
.spyOn(console, 'error')
217-
.mockImplementation(() => {});
215+
const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
218216

219217
const client = await getOauthClient(
220218
AuthType.LOGIN_WITH_GOOGLE,
@@ -226,7 +224,7 @@ describe('oauth2', () => {
226224
// Verify the auth flow
227225
expect(mockGenerateCodeVerifierAsync).toHaveBeenCalled();
228226
expect(mockGenerateAuthUrl).toHaveBeenCalled();
229-
expect(consoleErrorSpy).toHaveBeenCalledWith(
227+
expect(consoleLogSpy).toHaveBeenCalledWith(
230228
expect.stringContaining(mockAuthUrl),
231229
);
232230
expect(mockReadline.question).toHaveBeenCalledWith(
@@ -240,7 +238,7 @@ describe('oauth2', () => {
240238
});
241239
expect(mockSetCredentials).toHaveBeenCalledWith(mockTokens);
242240

243-
consoleErrorSpy.mockRestore();
241+
consoleLogSpy.mockRestore();
244242
});
245243

246244
describe('in Cloud Shell', () => {

packages/core/src/code_assist/oauth2.ts

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -163,38 +163,35 @@ async function authWithUserCode(client: OAuth2Client): Promise<boolean> {
163163
code_challenge: codeVerifier.codeChallenge,
164164
state,
165165
});
166-
console.error('Please visit the following URL to authorize the application:');
167-
console.error('');
168-
console.error(authUrl);
169-
console.error('');
166+
console.log('Please visit the following URL to authorize the application:');
167+
console.log('');
168+
console.log(authUrl);
169+
console.log('');
170170

171171
const code = await new Promise<string>((resolve) => {
172172
const rl = readline.createInterface({
173173
input: process.stdin,
174174
output: process.stdout,
175175
});
176-
rl.question('Enter the authorization code: ', (answer) => {
176+
rl.question('Enter the authorization code: ', (code) => {
177177
rl.close();
178-
resolve(answer.trim());
178+
resolve(code.trim());
179179
});
180180
});
181181

182182
if (!code) {
183183
console.error('Authorization code is required.');
184184
return false;
185-
} else {
186-
console.error(`Received authorization code: "${code}"`);
187185
}
188186

189187
try {
190-
const response = await client.getToken({
188+
const { tokens } = await client.getToken({
191189
code,
192190
codeVerifier: codeVerifier.codeVerifier,
193191
redirect_uri: redirectUri,
194192
});
195-
client.setCredentials(response.tokens);
193+
client.setCredentials(tokens);
196194
} catch (_error) {
197-
// Consider logging the error.
198195
return false;
199196
}
200197
return true;

0 commit comments

Comments
 (0)