# 🚀 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

@@ -63,28 +63,28 @@ export function getIdeInfo(ide: DetectedIde): IdeInfo {
export function detectIde(): DetectedIde | undefined {
// Only VSCode-based integrations are currently supported.
if (process.env.TERM_PROGRAM !== 'vscode') {
if (process.env['TERM_PROGRAM'] !== 'vscode') {
return undefined;
}
if (process.env.__COG_BASHRC_SOURCED) {
if (process.env['__COG_BASHRC_SOURCED']) {
return DetectedIde.Devin;
}
if (process.env.REPLIT_USER) {
if (process.env['REPLIT_USER']) {
return DetectedIde.Replit;
}
if (process.env.CURSOR_TRACE_ID) {
if (process.env['CURSOR_TRACE_ID']) {
return DetectedIde.Cursor;
}
if (process.env.CODESPACES) {
if (process.env['CODESPACES']) {
return DetectedIde.Codespaces;
}
if (process.env.EDITOR_IN_CLOUD_SHELL || process.env.CLOUD_SHELL) {
if (process.env['EDITOR_IN_CLOUD_SHELL'] || process.env['CLOUD_SHELL']) {
return DetectedIde.CloudShell;
}
if (process.env.TERM_PRODUCT === 'Trae') {
if (process.env['TERM_PRODUCT'] === 'Trae') {
return DetectedIde.Trae;
}
if (process.env.FIREBASE_DEPLOY_AGENT || process.env.MONOSPACE_ENV) {
if (process.env['FIREBASE_DEPLOY_AGENT'] || process.env['MONOSPACE_ENV']) {
return DetectedIde.FirebaseStudio;
}
return DetectedIde.VSCode;

View File

@@ -0,0 +1,78 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect } from 'vitest';
import * as path from 'path';
import { IdeClient } from './ide-client.js';
describe('IdeClient.validateWorkspacePath', () => {
it('should return valid if cwd is a subpath of the IDE workspace path', () => {
const result = IdeClient.validateWorkspacePath(
'/Users/person/gemini-cli',
'VS Code',
'/Users/person/gemini-cli/sub-dir',
);
expect(result.isValid).toBe(true);
});
it('should return invalid if GEMINI_CLI_IDE_WORKSPACE_PATH is undefined', () => {
const result = IdeClient.validateWorkspacePath(
undefined,
'VS Code',
'/Users/person/gemini-cli/sub-dir',
);
expect(result.isValid).toBe(false);
expect(result.error).toContain('Failed to connect');
});
it('should return invalid if GEMINI_CLI_IDE_WORKSPACE_PATH is empty', () => {
const result = IdeClient.validateWorkspacePath(
'',
'VS Code',
'/Users/person/gemini-cli/sub-dir',
);
expect(result.isValid).toBe(false);
expect(result.error).toContain('please open a workspace folder');
});
it('should return invalid if cwd is not within the IDE workspace path', () => {
const result = IdeClient.validateWorkspacePath(
'/some/other/path',
'VS Code',
'/Users/person/gemini-cli/sub-dir',
);
expect(result.isValid).toBe(false);
expect(result.error).toContain('Directory mismatch');
});
it('should handle multiple workspace paths and return valid', () => {
const result = IdeClient.validateWorkspacePath(
['/some/other/path', '/Users/person/gemini-cli'].join(path.delimiter),
'VS Code',
'/Users/person/gemini-cli/sub-dir',
);
expect(result.isValid).toBe(true);
});
it('should return invalid if cwd is not in any of the multiple workspace paths', () => {
const result = IdeClient.validateWorkspacePath(
['/some/other/path', '/another/path'].join(path.delimiter),
'VS Code',
'/Users/person/gemini-cli/sub-dir',
);
expect(result.isValid).toBe(false);
expect(result.error).toContain('Directory mismatch');
});
it.skipIf(process.platform !== 'win32')('should handle windows paths', () => {
const result = IdeClient.validateWorkspacePath(
'c:/some/other/path;d:/Users/person/gemini-cli',
'VS Code',
'd:/Users/person/gemini-cli/sub-dir',
);
expect(result.isValid).toBe(true);
});
});

View File

@@ -5,7 +5,7 @@
*/
import * as fs from 'node:fs';
import * as path from 'node:path';
import { isSubpath } from '../utils/paths.js';
import { detectIde, DetectedIde, getIdeInfo } from '../ide/detect-ide.js';
import {
ideContext,
@@ -15,8 +15,12 @@ import {
CloseDiffResponseSchema,
DiffUpdateResult,
} from '../ide/ideContext.js';
import { getIdeProcessId } from './process-utils.js';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import * as os from 'node:os';
import * as path from 'node:path';
import { EnvHttpProxyAgent } from 'undici';
const logger = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -60,6 +64,7 @@ export class IdeClient {
private readonly currentIde: DetectedIde | undefined;
private readonly currentIdeDisplayName: string | undefined;
private diffResponses = new Map<string, (result: DiffUpdateResult) => void>();
private statusListeners = new Set<(state: IDEConnectionState) => void>();
private constructor() {
this.currentIde = detectIde();
@@ -75,6 +80,14 @@ export class IdeClient {
return IdeClient.instance;
}
addStatusChangeListener(listener: (state: IDEConnectionState) => void) {
this.statusListeners.add(listener);
}
removeStatusChangeListener(listener: (state: IDEConnectionState) => void) {
this.statusListeners.delete(listener);
}
async connect(): Promise<void> {
if (!this.currentIde || !this.currentIdeDisplayName) {
this.setState(
@@ -91,16 +104,43 @@ export class IdeClient {
this.setState(IDEConnectionStatus.Connecting);
if (!this.validateWorkspacePath()) {
const ideInfoFromFile = await this.getIdeInfoFromFile();
const workspacePath =
ideInfoFromFile.workspacePath ??
process.env['QWEN_CODE_IDE_WORKSPACE_PATH'];
const { isValid, error } = IdeClient.validateWorkspacePath(
workspacePath,
this.currentIdeDisplayName,
process.cwd(),
);
if (!isValid) {
this.setState(IDEConnectionStatus.Disconnected, error, true);
return;
}
const port = this.getPortFromEnv();
if (!port) {
return;
const portFromFile = ideInfoFromFile.port;
if (portFromFile) {
const connected = await this.establishConnection(portFromFile);
if (connected) {
return;
}
}
await this.establishConnection(port);
const portFromEnv = this.getPortFromEnv();
if (portFromEnv) {
const connected = await this.establishConnection(portFromEnv);
if (connected) {
return;
}
}
this.setState(
IDEConnectionStatus.Disconnected,
`Failed to connect to IDE companion extension for ${this.currentIdeDisplayName}. Please ensure the extension is running. To install the extension, run /ide install.`,
true,
);
}
/**
@@ -212,6 +252,9 @@ export class IdeClient {
// disconnected, so that the first detail message is preserved.
if (!isAlreadyDisconnected) {
this.state = { status, details };
for (const listener of this.statusListeners) {
listener(this.state);
}
if (details) {
if (logToConsole) {
logger.error(details);
@@ -228,52 +271,95 @@ export class IdeClient {
}
}
private validateWorkspacePath(): boolean {
const ideWorkspacePath = process.env['QWEN_CODE_IDE_WORKSPACE_PATH'];
static validateWorkspacePath(
ideWorkspacePath: string | undefined,
currentIdeDisplayName: string | undefined,
cwd: string,
): { isValid: boolean; error?: string } {
if (ideWorkspacePath === undefined) {
this.setState(
IDEConnectionStatus.Disconnected,
`Failed to connect to IDE companion extension for ${this.currentIdeDisplayName}. Please ensure the extension is running and try refreshing your terminal. To install the extension, run /ide install.`,
true,
);
return false;
}
if (ideWorkspacePath === '') {
this.setState(
IDEConnectionStatus.Disconnected,
`To use this feature, please open a single workspace folder in ${this.currentIdeDisplayName} and try again.`,
true,
);
return false;
return {
isValid: false,
error: `Failed to connect to IDE companion extension for ${currentIdeDisplayName}. Please ensure the extension is running. To install the extension, run /ide install.`,
};
}
const idePath = getRealPath(ideWorkspacePath).toLocaleLowerCase();
const cwd = getRealPath(process.cwd()).toLocaleLowerCase();
const rel = path.relative(idePath, cwd);
if (rel.startsWith('..') || path.isAbsolute(rel)) {
this.setState(
IDEConnectionStatus.Disconnected,
`Directory mismatch. Qwen Code is running in a different location than the open workspace in ${this.currentIdeDisplayName}. Please run the CLI from the same directory as your project's root folder.`,
true,
);
return false;
if (ideWorkspacePath === '') {
return {
isValid: false,
error: `To use this feature, please open a workspace folder in ${currentIdeDisplayName} and try again.`,
};
}
return true;
const ideWorkspacePaths = ideWorkspacePath.split(path.delimiter);
const realCwd = getRealPath(cwd);
const isWithinWorkspace = ideWorkspacePaths.some((workspacePath) => {
const idePath = getRealPath(workspacePath);
return isSubpath(idePath, realCwd);
});
if (!isWithinWorkspace) {
return {
isValid: false,
error: `Directory mismatch. Qwen Code is running in a different location than the open workspace in ${currentIdeDisplayName}. Please run the CLI from one of the following directories: ${ideWorkspacePaths.join(
', ',
)}`,
};
}
return { isValid: true };
}
private getPortFromEnv(): string | undefined {
const port = process.env['QWEN_CODE_IDE_SERVER_PORT'];
if (!port) {
this.setState(
IDEConnectionStatus.Disconnected,
`Failed to connect to IDE companion extension for ${this.currentIdeDisplayName}. Please ensure the extension is running and try restarting your terminal. To install the extension, run /ide install.`,
true,
);
return undefined;
}
return port;
}
private async getIdeInfoFromFile(): Promise<{
port?: string;
workspacePath?: string;
}> {
try {
const ideProcessId = await getIdeProcessId();
const portFile = path.join(
os.tmpdir(),
`qwen-code-ide-server-${ideProcessId}.json`,
);
const portFileContents = await fs.promises.readFile(portFile, 'utf8');
const ideInfo = JSON.parse(portFileContents);
return {
port: ideInfo?.port?.toString(),
workspacePath: ideInfo?.workspacePath,
};
} catch (_) {
return {};
}
}
private createProxyAwareFetch() {
// ignore proxy for 'localhost' by deafult to allow connecting to the ide mcp server
const existingNoProxy = process.env['NO_PROXY'] || '';
const agent = new EnvHttpProxyAgent({
noProxy: [existingNoProxy, 'localhost'].filter(Boolean).join(','),
});
const undiciPromise = import('undici');
return async (url: string | URL, init?: RequestInit): Promise<Response> => {
const { fetch: fetchFn } = await undiciPromise;
const fetchOptions: RequestInit & { dispatcher?: unknown } = {
...init,
dispatcher: agent,
};
const options = fetchOptions as unknown as import('undici').RequestInit;
const response = await fetchFn(url, options);
return new Response(response.body as ReadableStream<unknown> | null, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
};
}
private registerClientHandlers() {
if (!this.client) {
return;
@@ -328,7 +414,7 @@ export class IdeClient {
);
}
private async establishConnection(port: string) {
private async establishConnection(port: string): Promise<boolean> {
let transport: StreamableHTTPClientTransport | undefined;
try {
this.client = new Client({
@@ -339,6 +425,9 @@ export class IdeClient {
transport = new StreamableHTTPClientTransport(
new URL(`http://${getIdeServerHost()}:${port}/mcp`),
{
fetch: this.createProxyAwareFetch(),
},
);
this.registerClientHandlers();
@@ -346,12 +435,8 @@ export class IdeClient {
await this.client.connect(transport);
this.registerClientHandlers();
this.setState(IDEConnectionStatus.Connected);
return true;
} catch (_error) {
this.setState(
IDEConnectionStatus.Disconnected,
`Failed to connect to IDE companion extension for ${this.currentIdeDisplayName}. Please ensure the extension is running and try restarting your terminal. To install the extension, run /ide install.`,
true,
);
if (transport) {
try {
await transport.close();
@@ -359,42 +444,9 @@ export class IdeClient {
logger.debug('Failed to close transport:', closeError);
}
}
return false;
}
}
async init(): Promise<void> {
if (this.state.status === IDEConnectionStatus.Connected) {
return;
}
if (!this.currentIde) {
this.setState(
IDEConnectionStatus.Disconnected,
'Not running in a supported IDE, skipping connection.',
);
return;
}
this.setState(IDEConnectionStatus.Connecting);
if (!this.validateWorkspacePath()) {
return;
}
const port = this.getPortFromEnv();
if (!port) {
return;
}
await this.establishConnection(port);
}
dispose() {
this.client?.close();
}
setDisconnected() {
this.setState(IDEConnectionStatus.Disconnected);
}
}
function getIdeServerHost() {

View File

@@ -16,6 +16,14 @@ vi.mock('fs');
vi.mock('os');
describe('ide-installer', () => {
beforeEach(() => {
vi.spyOn(os, 'homedir').mockReturnValue('/home/user');
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('getIdeInstaller', () => {
it('should return a VsCodeInstaller for "vscode"', () => {
const installer = getIdeInstaller(DetectedIde.VSCode);
@@ -38,11 +46,6 @@ describe('ide-installer', () => {
installer = getIdeInstaller(DetectedIde.VSCode)!;
vi.spyOn(child_process, 'execSync').mockImplementation(() => '');
vi.spyOn(fs, 'existsSync').mockReturnValue(false);
vi.spyOn(os, 'homedir').mockReturnValue('/home/user');
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('install', () => {

View File

@@ -26,13 +26,22 @@ export interface InstallResult {
async function findVsCodeCommand(): Promise<string | null> {
// 1. Check PATH first.
try {
child_process.execSync(
process.platform === 'win32'
? `where.exe ${VSCODE_COMMAND}`
: `command -v ${VSCODE_COMMAND}`,
{ stdio: 'ignore' },
);
return VSCODE_COMMAND;
if (process.platform === 'win32') {
const result = child_process
.execSync(`where.exe ${VSCODE_COMMAND}`)
.toString()
.trim();
// `where.exe` can return multiple paths. Return the first one.
const firstPath = result.split(/\r?\n/)[0];
if (firstPath) {
return firstPath;
}
} else {
child_process.execSync(`command -v ${VSCODE_COMMAND}`, {
stdio: 'ignore',
});
return VSCODE_COMMAND;
}
} catch {
// Not in PATH, continue to check common locations.
}
@@ -59,7 +68,7 @@ async function findVsCodeCommand(): Promise<string | null> {
// Windows
locations.push(
path.join(
process.env.ProgramFiles || 'C:\\Program Files',
process.env['ProgramFiles'] || 'C:\\Program Files',
'Microsoft VS Code',
'bin',
'code.cmd',
@@ -97,7 +106,7 @@ class VsCodeInstaller implements IdeInstaller {
if (!commandPath) {
return {
success: false,
message: `VS Code CLI not found. Please ensure 'code' is in your system's PATH. For help, see https://code.visualstudio.com/docs/configure/command-line#_code-is-not-recognized-as-an-internal-or-external-command. You can also install the companion extension manually from the VS Code marketplace.`,
message: `VS Code CLI not found. Please ensure 'code' is in your system's PATH. For help, see https://code.visualstudio.com/docs/configure/command-line#_code-is-not-recognized-as-an-internal-or-external-command. You can also install the '${QWEN_CODE_COMPANION_EXTENSION_NAME}' extension manually from the VS Code marketplace.`,
};
}
@@ -106,8 +115,7 @@ class VsCodeInstaller implements IdeInstaller {
child_process.execSync(command, { stdio: 'pipe' });
return {
success: true,
message:
'VS Code companion extension was installed successfully. Please restart your terminal to complete the setup.',
message: 'VS Code companion extension was installed successfully.',
};
} catch (_error) {
return {

View File

@@ -0,0 +1,157 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { exec } from 'child_process';
import { promisify } from 'util';
import os from 'os';
import path from 'path';
const execAsync = promisify(exec);
const MAX_TRAVERSAL_DEPTH = 32;
/**
* Fetches the parent process ID and name for a given process ID.
*
* @param pid The process ID to inspect.
* @returns A promise that resolves to the parent's PID and name.
*/
async function getParentProcessInfo(pid: number): Promise<{
parentPid: number;
name: string;
}> {
const platform = os.platform();
if (platform === 'win32') {
const command = `wmic process where "ProcessId=${pid}" get Name,ParentProcessId /value`;
const { stdout } = await execAsync(command);
const nameMatch = stdout.match(/Name=([^\n]*)/);
const processName = nameMatch ? nameMatch[1].trim() : '';
const ppidMatch = stdout.match(/ParentProcessId=(\d+)/);
const parentPid = ppidMatch ? parseInt(ppidMatch[1], 10) : 0;
return { parentPid, name: processName };
} else {
const command = `ps -o ppid=,command= -p ${pid}`;
const { stdout } = await execAsync(command);
const trimmedStdout = stdout.trim();
const ppidString = trimmedStdout.split(/\s+/)[0];
const parentPid = parseInt(ppidString, 10);
const fullCommand = trimmedStdout.substring(ppidString.length).trim();
const processName = path.basename(fullCommand.split(' ')[0]);
return { parentPid: isNaN(parentPid) ? 1 : parentPid, name: processName };
}
}
/**
* Traverses the process tree on Unix-like systems to find the IDE process ID.
*
* The strategy is to find the shell process that spawned the CLI, and then
* find that shell's parent process (the IDE). To get the true IDE process,
* we traverse one level higher to get the grandparent.
*
* @returns A promise that resolves to the numeric PID.
*/
async function getIdeProcessIdForUnix(): Promise<number> {
const shells = ['zsh', 'bash', 'sh', 'tcsh', 'csh', 'ksh', 'fish', 'dash'];
let currentPid = process.pid;
for (let i = 0; i < MAX_TRAVERSAL_DEPTH; i++) {
try {
const { parentPid, name } = await getParentProcessInfo(currentPid);
const isShell = shells.some((shell) => name === shell);
if (isShell) {
// The direct parent of the shell is often a utility process (e.g. VS
// Code's `ptyhost` process). To get the true IDE process, we need to
// traverse one level higher to get the grandparent.
try {
const { parentPid: grandParentPid } =
await getParentProcessInfo(parentPid);
if (grandParentPid > 1) {
return grandParentPid;
}
} catch {
// Ignore if getting grandparent fails, we'll just use the parent pid.
}
return parentPid;
}
if (parentPid <= 1) {
break; // Reached the root
}
currentPid = parentPid;
} catch {
// Process in chain died
break;
}
}
console.error(
'Failed to find shell process in the process tree. Falling back to top-level process, which may be inaccurate. If you see this, please file a bug via /bug.',
);
return currentPid;
}
/**
* Traverses the process tree on Windows to find the IDE process ID.
*
* The strategy is to find the grandchild of the root process.
*
* @returns A promise that resolves to the numeric PID.
*/
async function getIdeProcessIdForWindows(): Promise<number> {
let currentPid = process.pid;
for (let i = 0; i < MAX_TRAVERSAL_DEPTH; i++) {
try {
const { parentPid } = await getParentProcessInfo(currentPid);
if (parentPid > 0) {
try {
const { parentPid: grandParentPid } =
await getParentProcessInfo(parentPid);
if (grandParentPid === 0) {
// Found grandchild of root
return currentPid;
}
} catch {
// getting grandparent failed, proceed
}
}
if (parentPid <= 0) {
break; // Reached the root
}
currentPid = parentPid;
} catch {
// Process in chain died
break;
}
}
return currentPid;
}
/**
* Traverses up the process tree to find the process ID of the IDE.
*
* This function uses different strategies depending on the operating system
* to identify the main application process (e.g., the main VS Code window
* process).
*
* If the IDE process cannot be reliably identified, it will return the
* top-level ancestor process ID as a fallback.
*
* @returns A promise that resolves to the numeric PID of the IDE process.
* @throws Will throw an error if the underlying shell commands fail.
*/
export async function getIdeProcessId(): Promise<number> {
const platform = os.platform();
if (platform === 'win32') {
return getIdeProcessIdForWindows();
}
return getIdeProcessIdForUnix();
}