# 🚀 Sync Gemini CLI v0.2.1 - Major Feature Update (#483)

This commit is contained in:
tanzhenxin
2025-09-01 14:48:55 +08:00
committed by GitHub
parent 1610c1586e
commit 2572faf726
292 changed files with 19401 additions and 5941 deletions

View File

@@ -86,7 +86,7 @@ describe('file-system', () => {
).toBeTruthy();
// Log success info if verbose
if (process.env.VERBOSE === 'true') {
if (process.env['VERBOSE'] === 'true') {
console.log('File written successfully with hello message.');
}
});

View File

@@ -4,6 +4,11 @@
* SPDX-License-Identifier: Apache-2.0
*/
// Unset NO_COLOR environment variable to ensure consistent theme behavior between local and CI test runs
if (process.env['NO_COLOR'] !== undefined) {
delete process.env['NO_COLOR'];
}
import { mkdir, readdir, rm } from 'fs/promises';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
@@ -35,21 +40,21 @@ export async function setup() {
console.error('Error cleaning up old test runs:', e);
}
process.env.INTEGRATION_TEST_FILE_DIR = runDir;
process.env.GEMINI_CLI_INTEGRATION_TEST = 'true';
process.env.TELEMETRY_LOG_FILE = join(runDir, 'telemetry.log');
process.env['INTEGRATION_TEST_FILE_DIR'] = runDir;
process.env['GEMINI_CLI_INTEGRATION_TEST'] = 'true';
process.env['TELEMETRY_LOG_FILE'] = join(runDir, 'telemetry.log');
if (process.env.KEEP_OUTPUT) {
if (process.env['KEEP_OUTPUT']) {
console.log(`Keeping output for test run in: ${runDir}`);
}
process.env.VERBOSE = process.env.VERBOSE ?? 'false';
process.env['VERBOSE'] = process.env['VERBOSE'] ?? 'false';
console.log(`\nIntegration test output directory: ${runDir}`);
}
export async function teardown() {
// Cleanup the test run directory unless KEEP_OUTPUT is set
if (process.env.KEEP_OUTPUT !== 'true' && runDir) {
if (process.env['KEEP_OUTPUT'] !== 'true' && runDir) {
await rm(runDir, { recursive: true, force: true });
}
}

View File

@@ -0,0 +1,206 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import * as net from 'node:net';
import * as child_process from 'node:child_process';
import type { ChildProcess } from 'node:child_process';
import { IdeClient } from '../packages/core/src/ide/ide-client.js';
import { TestMcpServer } from './test-mcp-server.js';
// Helper function to reset the IdeClient singleton instance for testing
const resetIdeClientInstance = () => {
// Access the private instance property using type assertion
(IdeClient as unknown as { instance?: IdeClient }).instance = undefined;
};
describe.skip('IdeClient', () => {
it('reads port from file and connects', async () => {
const server = new TestMcpServer();
const port = await server.start();
const pid = process.pid;
const portFile = path.join(os.tmpdir(), `qwen-code-ide-server-${pid}.json`);
fs.writeFileSync(portFile, JSON.stringify({ port }));
process.env['QWEN_CODE_IDE_WORKSPACE_PATH'] = process.cwd();
process.env['TERM_PROGRAM'] = 'vscode';
const ideClient = IdeClient.getInstance();
await ideClient.connect();
expect(ideClient.getConnectionStatus()).toEqual({
status: 'connected',
details: undefined,
});
fs.unlinkSync(portFile);
await server.stop();
delete process.env['QWEN_CODE_IDE_WORKSPACE_PATH'];
});
});
const getFreePort = (): Promise<number> => {
return new Promise((resolve, reject) => {
const server = net.createServer();
server.unref();
server.on('error', reject);
server.listen(0, () => {
const port = (server.address() as net.AddressInfo).port;
server.close(() => {
resolve(port);
});
});
});
};
describe('IdeClient fallback connection logic', () => {
let server: TestMcpServer;
let envPort: number;
let pid: number;
let portFile: string;
beforeEach(async () => {
pid = process.pid;
portFile = path.join(os.tmpdir(), `qwen-code-ide-server-${pid}.json`);
server = new TestMcpServer();
envPort = await server.start();
process.env['QWEN_CODE_IDE_SERVER_PORT'] = String(envPort);
process.env['TERM_PROGRAM'] = 'vscode';
process.env['QWEN_CODE_IDE_WORKSPACE_PATH'] = process.cwd();
// Reset instance
resetIdeClientInstance();
});
afterEach(async () => {
await server.stop();
delete process.env['QWEN_CODE_IDE_SERVER_PORT'];
delete process.env['QWEN_CODE_IDE_WORKSPACE_PATH'];
if (fs.existsSync(portFile)) {
fs.unlinkSync(portFile);
}
});
it('connects using env var when port file does not exist', async () => {
// Ensure port file doesn't exist
if (fs.existsSync(portFile)) {
fs.unlinkSync(portFile);
}
const ideClient = IdeClient.getInstance();
await ideClient.connect();
expect(ideClient.getConnectionStatus()).toEqual({
status: 'connected',
details: undefined,
});
});
it('falls back to env var when connection with port from file fails', async () => {
const filePort = await getFreePort();
// Write port file with a port that is not listening
fs.writeFileSync(portFile, JSON.stringify({ port: filePort }));
const ideClient = IdeClient.getInstance();
await ideClient.connect();
expect(ideClient.getConnectionStatus()).toEqual({
status: 'connected',
details: undefined,
});
});
});
describe.skip('getIdeProcessId', () => {
let child: ChildProcess;
afterEach(() => {
if (child) {
child.kill();
}
});
it('should return the pid of the parent process', async () => {
// We need to spawn a child process that will run the test
// so that we can check that getIdeProcessId returns the pid of the parent
const parentPid = process.pid;
const output = await new Promise<string>((resolve, reject) => {
child = child_process.spawn(
'node',
[
'-e',
`
const { getIdeProcessId } = require('../packages/core/src/ide/process-utils.js');
getIdeProcessId().then(pid => console.log(pid));
`,
],
{
stdio: ['pipe', 'pipe', 'pipe'],
},
);
let out = '';
child.stdout?.on('data', (data: Buffer) => {
out += data.toString();
});
child.on('close', (code: number | null) => {
if (code === 0) {
resolve(out.trim());
} else {
reject(new Error(`Child process exited with code ${code}`));
}
});
});
expect(parseInt(output, 10)).toBe(parentPid);
}, 10000);
});
describe('IdeClient with proxy', () => {
let mcpServer: TestMcpServer;
let proxyServer: net.Server;
let mcpServerPort: number;
let proxyServerPort: number;
beforeEach(async () => {
mcpServer = new TestMcpServer();
mcpServerPort = await mcpServer.start();
proxyServer = net.createServer().listen();
proxyServerPort = (proxyServer.address() as net.AddressInfo).port;
vi.stubEnv('QWEN_CODE_IDE_SERVER_PORT', String(mcpServerPort));
vi.stubEnv('TERM_PROGRAM', 'vscode');
vi.stubEnv('QWEN_CODE_IDE_WORKSPACE_PATH', process.cwd());
// Reset instance
resetIdeClientInstance();
});
afterEach(async () => {
IdeClient.getInstance().disconnect();
await mcpServer.stop();
proxyServer.close();
vi.unstubAllEnvs();
});
it('should connect to IDE server when HTTP_PROXY, HTTPS_PROXY and NO_PROXY are set', async () => {
vi.stubEnv('HTTP_PROXY', `http://localhost:${proxyServerPort}`);
vi.stubEnv('HTTPS_PROXY', `http://localhost:${proxyServerPort}`);
vi.stubEnv('NO_PROXY', 'example.com,127.0.0.1,::1');
const ideClient = IdeClient.getInstance();
await ideClient.connect();
expect(ideClient.getConnectionStatus()).toEqual({
status: 'connected',
details: undefined,
});
});
});

View File

@@ -27,7 +27,7 @@ const readline = require('readline');
const fs = require('fs');
// Debug logging to stderr (only when MCP_DEBUG or VERBOSE is set)
const debugEnabled = process.env.MCP_DEBUG === 'true' || process.env.VERBOSE === 'true';
const debugEnabled = process.env['MCP_DEBUG'] === 'true' || process.env['VERBOSE'] === 'true';
function debug(msg) {
if (debugEnabled) {
fs.writeSync(2, \`[MCP-DEBUG] \${msg}\\n\`);

View File

@@ -4,7 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect } from 'vitest';
import { describe, it, expect, vi } from 'vitest';
import { TestRig, printDebugInfo, validateModelOutput } from './test-helper.js';
describe('replace', () => {
@@ -56,7 +56,8 @@ describe('replace', () => {
expect(newFileContent).toBe(expectedContent);
// Log success info if verbose
if (process.env.VERBOSE === 'true') {
vi.stubEnv('VERBOSE', 'true');
if (process.env['VERBOSE'] === 'true') {
console.log('File replaced successfully. New content:', newFileContent);
}
});

View File

@@ -0,0 +1,126 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, beforeAll } from 'vitest';
import { ShellExecutionService } from '../packages/core/src/services/shellExecutionService.js';
import * as fs from 'fs/promises';
import * as path from 'path';
import { vi } from 'vitest';
describe('ShellExecutionService programmatic integration tests', () => {
let testDir: string;
beforeAll(async () => {
// Create a dedicated directory for this test suite to avoid conflicts.
testDir = path.join(
process.env['INTEGRATION_TEST_FILE_DIR']!,
'shell-service-tests',
);
await fs.mkdir(testDir, { recursive: true });
});
it('should execute a simple cross-platform command (echo)', async () => {
const command = 'echo "hello from the service"';
const onOutputEvent = vi.fn();
const abortController = new AbortController();
const handle = await ShellExecutionService.execute(
command,
testDir,
onOutputEvent,
abortController.signal,
false,
);
const result = await handle.result;
expect(result.error).toBeNull();
expect(result.exitCode).toBe(0);
// Output can vary slightly between shells (e.g., quotes), so check for inclusion.
expect(result.output).toContain('hello from the service');
});
it.runIf(process.platform === 'win32')(
'should execute "dir" on Windows',
async () => {
const testFile = 'test-file-windows.txt';
await fs.writeFile(path.join(testDir, testFile), 'windows test');
const command = 'dir';
const onOutputEvent = vi.fn();
const abortController = new AbortController();
const handle = await ShellExecutionService.execute(
command,
testDir,
onOutputEvent,
abortController.signal,
false,
);
const result = await handle.result;
expect(result.error).toBeNull();
expect(result.exitCode).toBe(0);
expect(result.output).toContain(testFile);
},
);
it.skipIf(process.platform === 'win32')(
'should execute "ls -l" on Unix',
async () => {
const testFile = 'test-file-unix.txt';
await fs.writeFile(path.join(testDir, testFile), 'unix test');
const command = 'ls -l';
const onOutputEvent = vi.fn();
const abortController = new AbortController();
const handle = await ShellExecutionService.execute(
command,
testDir,
onOutputEvent,
abortController.signal,
false,
);
const result = await handle.result;
expect(result.error).toBeNull();
expect(result.exitCode).toBe(0);
expect(result.output).toContain(testFile);
},
);
it('should abort a running process', async () => {
// A command that runs for a bit. 'sleep' on unix, 'timeout' on windows.
const command = process.platform === 'win32' ? 'timeout /t 20' : 'sleep 20';
const onOutputEvent = vi.fn();
const abortController = new AbortController();
const handle = await ShellExecutionService.execute(
command,
testDir,
onOutputEvent,
abortController.signal,
false,
);
// Abort shortly after starting
setTimeout(() => abortController.abort(), 50);
const result = await handle.result;
// For debugging the flaky test.
console.log('Abort test result:', result);
expect(result.aborted).toBe(true);
// A clean exit is exitCode 0 and no signal. If the process was truly
// aborted, it should not have exited cleanly.
const exitedCleanly = result.exitCode === 0 && result.signal === null;
expect(exitedCleanly, 'Process should not have exited cleanly').toBe(false);
});
});

View File

@@ -28,7 +28,7 @@ const readline = require('readline');
const fs = require('fs');
// Debug logging to stderr (only when MCP_DEBUG or VERBOSE is set)
const debugEnabled = process.env.MCP_DEBUG === 'true' || process.env.VERBOSE === 'true';
const debugEnabled = process.env['MCP_DEBUG'] === 'true' || process.env['VERBOSE'] === 'true';
function debug(msg) {
if (debugEnabled) {
fs.writeSync(2, \`[MCP-DEBUG] \${msg}\\n\`);

View File

@@ -100,7 +100,7 @@ export function validateModelOutput(
'The tool was called successfully, which is the main requirement.',
);
return false;
} else if (process.env.VERBOSE === 'true') {
} else if (process.env['VERBOSE'] === 'true') {
console.log(`${testName}: Model output validated successfully.`);
}
return true;
@@ -221,8 +221,8 @@ export class TestRig {
// Handle stdin if provided
if (execOptions.input) {
child.stdin!.write(execOptions.input);
child.stdin!.end();
}
child.stdin!.end();
child.stdout!.on('data', (data: Buffer) => {
stdout += data;

View File

@@ -0,0 +1,64 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import express from 'express';
import { type Server as HTTPServer } from 'node:http';
import { randomUUID } from 'node:crypto';
export class TestMcpServer {
private server: HTTPServer | undefined;
async start(): Promise<number> {
const app = express();
app.use(express.json());
const mcpServer = new McpServer(
{
name: 'test-mcp-server',
version: '1.0.0',
},
{ capabilities: {} },
);
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: () => randomUUID(),
});
mcpServer.connect(transport);
app.post('/mcp', async (req, res) => {
await transport.handleRequest(req, res, req.body);
});
return new Promise((resolve, reject) => {
this.server = app.listen(0, () => {
const address = this.server!.address();
if (address && typeof address !== 'string') {
resolve(address.port);
} else {
reject(new Error('Could not determine server port.'));
}
});
this.server.on('error', reject);
});
}
async stop(): Promise<void> {
if (this.server) {
await new Promise<void>((resolve, reject) => {
this.server!.close((err?: Error) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
this.server = undefined;
}
}
}

View File

@@ -60,7 +60,7 @@ Please create a todo list for these tasks.`;
}
// Log success info if verbose
if (process.env.VERBOSE === 'true') {
if (process.env['VERBOSE'] === 'true') {
console.log('Todo list created successfully');
}
});
@@ -125,7 +125,7 @@ Please create a todo list for these tasks.`;
}
// Log success info if verbose
if (process.env.VERBOSE === 'true') {
if (process.env['VERBOSE'] === 'true') {
console.log('Todo list updated successfully');
}
});

View File

@@ -10,7 +10,7 @@ import { TestRig, printDebugInfo, validateModelOutput } from './test-helper.js';
describe('web_search', () => {
it('should be able to search the web', async () => {
// Skip if Tavily key is not configured
if (!process.env.TAVILY_API_KEY) {
if (!process.env['TAVILY_API_KEY']) {
console.warn('Skipping web search test: TAVILY_API_KEY not set');
return;
}

View File

@@ -4,7 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect } from 'vitest';
import { describe, it, expect, vi } from 'vitest';
import {
TestRig,
createToolCallErrorMessage,
@@ -58,7 +58,8 @@ describe('write_file', () => {
expect(newFileContent).not.toBe('');
// Log success info if verbose
if (process.env.VERBOSE === 'true') {
vi.stubEnv('VERBOSE', 'true');
if (process.env['VERBOSE'] === 'true') {
console.log(
'File created successfully with content:',
newFileContent.substring(0, 100) + '...',