mirror of
https://github.com/QwenLM/qwen-code.git
synced 2025-12-21 01:07:46 +00:00
# 🚀 Sync Gemini CLI v0.2.1 - Major Feature Update (#483)
This commit is contained in:
@@ -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() {
|
||||
|
||||
Reference in New Issue
Block a user