Merge tag 'v0.3.0' into chore/sync-gemini-cli-v0.3.0

This commit is contained in:
mingholy.lmh
2025-09-10 21:01:40 +08:00
583 changed files with 30160 additions and 10770 deletions

View File

@@ -4,89 +4,141 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, afterEach, vi } from 'vitest';
import { detectIde, DetectedIde } from './detect-ide.js';
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
import { detectIde, DetectedIde, getIdeInfo } from './detect-ide.js';
describe('detectIde', () => {
const ideProcessInfo = { pid: 123, command: 'some/path/to/code' };
const ideProcessInfoNoCode = { pid: 123, command: 'some/path/to/fork' };
// Clear all IDE-related environment variables before each test
beforeEach(() => {
vi.stubEnv('__COG_BASHRC_SOURCED', '');
vi.stubEnv('REPLIT_USER', '');
vi.stubEnv('CURSOR_TRACE_ID', '');
vi.stubEnv('CODESPACES', '');
vi.stubEnv('EDITOR_IN_CLOUD_SHELL', '');
vi.stubEnv('CLOUD_SHELL', '');
vi.stubEnv('TERM_PRODUCT', '');
vi.stubEnv('MONOSPACE_ENV', '');
});
afterEach(() => {
vi.unstubAllEnvs();
});
it.each([
{
env: {},
expected: DetectedIde.VSCode,
},
{
env: { __COG_BASHRC_SOURCED: '1' },
expected: DetectedIde.Devin,
},
{
env: { REPLIT_USER: 'test' },
expected: DetectedIde.Replit,
},
{
env: { CURSOR_TRACE_ID: 'test' },
expected: DetectedIde.Cursor,
},
{
env: { CODESPACES: 'true' },
expected: DetectedIde.Codespaces,
},
{
env: { EDITOR_IN_CLOUD_SHELL: 'true' },
expected: DetectedIde.CloudShell,
},
{
env: { CLOUD_SHELL: 'true' },
expected: DetectedIde.CloudShell,
},
{
env: { TERM_PRODUCT: 'Trae' },
expected: DetectedIde.Trae,
},
{
env: { FIREBASE_DEPLOY_AGENT: 'true' },
expected: DetectedIde.FirebaseStudio,
},
{
env: { MONOSPACE_ENV: 'true' },
expected: DetectedIde.FirebaseStudio,
},
])('detects the IDE for $expected', ({ env, expected }) => {
// Clear all environment variables first
vi.unstubAllEnvs();
// Set TERM_PROGRAM to vscode (required for all IDE detection)
vi.stubEnv('TERM_PROGRAM', 'vscode');
// Explicitly stub all environment variables that detectIde() checks to undefined
// This ensures no real environment variables interfere with the tests
vi.stubEnv('__COG_BASHRC_SOURCED', undefined);
vi.stubEnv('REPLIT_USER', undefined);
vi.stubEnv('CURSOR_TRACE_ID', undefined);
vi.stubEnv('CODESPACES', undefined);
vi.stubEnv('EDITOR_IN_CLOUD_SHELL', undefined);
vi.stubEnv('CLOUD_SHELL', undefined);
vi.stubEnv('TERM_PRODUCT', undefined);
vi.stubEnv('FIREBASE_DEPLOY_AGENT', undefined);
vi.stubEnv('MONOSPACE_ENV', undefined);
// Set only the specific environment variables for this test case
for (const [key, value] of Object.entries(env)) {
vi.stubEnv(key, value);
}
expect(detectIde()).toBe(expected);
it('should return undefined if TERM_PROGRAM is not vscode', () => {
vi.stubEnv('TERM_PROGRAM', '');
expect(detectIde(ideProcessInfo)).toBeUndefined();
});
it('returns undefined for non-vscode', () => {
// Clear all environment variables first
vi.unstubAllEnvs();
it('should detect Devin', () => {
vi.stubEnv('TERM_PROGRAM', 'vscode');
vi.stubEnv('__COG_BASHRC_SOURCED', '1');
expect(detectIde(ideProcessInfo)).toBe(DetectedIde.Devin);
});
// Set TERM_PROGRAM to something other than vscode
vi.stubEnv('TERM_PROGRAM', 'definitely-not-vscode');
it('should detect Replit', () => {
vi.stubEnv('TERM_PROGRAM', 'vscode');
vi.stubEnv('REPLIT_USER', 'testuser');
expect(detectIde(ideProcessInfo)).toBe(DetectedIde.Replit);
});
expect(detectIde()).toBeUndefined();
it('should detect Cursor', () => {
vi.stubEnv('TERM_PROGRAM', 'vscode');
vi.stubEnv('CURSOR_TRACE_ID', 'some-id');
expect(detectIde(ideProcessInfo)).toBe(DetectedIde.Cursor);
});
it('should detect Codespaces', () => {
vi.stubEnv('TERM_PROGRAM', 'vscode');
vi.stubEnv('CODESPACES', 'true');
expect(detectIde(ideProcessInfo)).toBe(DetectedIde.Codespaces);
});
it('should detect Cloud Shell via EDITOR_IN_CLOUD_SHELL', () => {
vi.stubEnv('TERM_PROGRAM', 'vscode');
vi.stubEnv('EDITOR_IN_CLOUD_SHELL', 'true');
expect(detectIde(ideProcessInfo)).toBe(DetectedIde.CloudShell);
});
it('should detect Cloud Shell via CLOUD_SHELL', () => {
vi.stubEnv('TERM_PROGRAM', 'vscode');
vi.stubEnv('CLOUD_SHELL', 'true');
expect(detectIde(ideProcessInfo)).toBe(DetectedIde.CloudShell);
});
it('should detect Trae', () => {
vi.stubEnv('TERM_PROGRAM', 'vscode');
vi.stubEnv('TERM_PRODUCT', 'Trae');
expect(detectIde(ideProcessInfo)).toBe(DetectedIde.Trae);
});
it('should detect Firebase Studio via MONOSPACE_ENV', () => {
vi.stubEnv('TERM_PROGRAM', 'vscode');
vi.stubEnv('MONOSPACE_ENV', 'true');
expect(detectIde(ideProcessInfo)).toBe(DetectedIde.FirebaseStudio);
});
it('should detect VSCode when no other IDE is detected and command includes "code"', () => {
vi.stubEnv('TERM_PROGRAM', 'vscode');
vi.stubEnv('MONOSPACE_ENV', '');
expect(detectIde(ideProcessInfo)).toBe(DetectedIde.VSCode);
});
it('should detect VSCodeFork when no other IDE is detected and command does not include "code"', () => {
vi.stubEnv('TERM_PROGRAM', 'vscode');
vi.stubEnv('MONOSPACE_ENV', '');
expect(detectIde(ideProcessInfoNoCode)).toBe(DetectedIde.VSCodeFork);
});
it('should prioritize other IDEs over VSCode detection', () => {
vi.stubEnv('TERM_PROGRAM', 'vscode');
vi.stubEnv('REPLIT_USER', 'testuser');
expect(detectIde(ideProcessInfo)).toBe(DetectedIde.Replit);
});
});
describe('getIdeInfo', () => {
it('should return correct info for Devin', () => {
expect(getIdeInfo(DetectedIde.Devin)).toEqual({ displayName: 'Devin' });
});
it('should return correct info for Replit', () => {
expect(getIdeInfo(DetectedIde.Replit)).toEqual({ displayName: 'Replit' });
});
it('should return correct info for Cursor', () => {
expect(getIdeInfo(DetectedIde.Cursor)).toEqual({ displayName: 'Cursor' });
});
it('should return correct info for CloudShell', () => {
expect(getIdeInfo(DetectedIde.CloudShell)).toEqual({
displayName: 'Cloud Shell',
});
});
it('should return correct info for Codespaces', () => {
expect(getIdeInfo(DetectedIde.Codespaces)).toEqual({
displayName: 'GitHub Codespaces',
});
});
it('should return correct info for FirebaseStudio', () => {
expect(getIdeInfo(DetectedIde.FirebaseStudio)).toEqual({
displayName: 'Firebase Studio',
});
});
it('should return correct info for Trae', () => {
expect(getIdeInfo(DetectedIde.Trae)).toEqual({ displayName: 'Trae' });
});
it('should return correct info for VSCode', () => {
expect(getIdeInfo(DetectedIde.VSCode)).toEqual({ displayName: 'VS Code' });
});
it('should return correct info for VSCodeFork', () => {
expect(getIdeInfo(DetectedIde.VSCodeFork)).toEqual({ displayName: 'IDE' });
});
});

View File

@@ -7,12 +7,13 @@
export enum DetectedIde {
Devin = 'devin',
Replit = 'replit',
VSCode = 'vscode',
Cursor = 'cursor',
CloudShell = 'cloudshell',
Codespaces = 'codespaces',
FirebaseStudio = 'firebasestudio',
Trae = 'trae',
VSCode = 'vscode',
VSCodeFork = 'vscodefork',
}
export interface IdeInfo {
@@ -29,10 +30,6 @@ export function getIdeInfo(ide: DetectedIde): IdeInfo {
return {
displayName: 'Replit',
};
case DetectedIde.VSCode:
return {
displayName: 'VS Code',
};
case DetectedIde.Cursor:
return {
displayName: 'Cursor',
@@ -53,6 +50,14 @@ export function getIdeInfo(ide: DetectedIde): IdeInfo {
return {
displayName: 'Trae',
};
case DetectedIde.VSCode:
return {
displayName: 'VS Code',
};
case DetectedIde.VSCodeFork:
return {
displayName: 'IDE',
};
default: {
// This ensures that if a new IDE is added to the enum, we get a compile-time error.
const exhaustiveCheck: never = ide;
@@ -61,11 +66,7 @@ export function getIdeInfo(ide: DetectedIde): IdeInfo {
}
}
export function detectIde(): DetectedIde | undefined {
// Only VSCode-based integrations are currently supported.
if (process.env['TERM_PROGRAM'] !== 'vscode') {
return undefined;
}
export function detectIdeFromEnv(): DetectedIde {
if (process.env['__COG_BASHRC_SOURCED']) {
return DetectedIde.Devin;
}
@@ -84,8 +85,37 @@ export function detectIde(): DetectedIde | undefined {
if (process.env['TERM_PRODUCT'] === 'Trae') {
return DetectedIde.Trae;
}
if (process.env['FIREBASE_DEPLOY_AGENT'] || process.env['MONOSPACE_ENV']) {
if (process.env['MONOSPACE_ENV']) {
return DetectedIde.FirebaseStudio;
}
return DetectedIde.VSCode;
}
function verifyVSCode(
ide: DetectedIde,
ideProcessInfo: {
pid: number;
command: string;
},
): DetectedIde {
if (ide !== DetectedIde.VSCode) {
return ide;
}
if (ideProcessInfo.command.toLowerCase().includes('code')) {
return DetectedIde.VSCode;
}
return DetectedIde.VSCodeFork;
}
export function detectIde(ideProcessInfo: {
pid: number;
command: string;
}): DetectedIde | undefined {
// Only VSCode-based integrations are currently supported.
if (process.env['TERM_PROGRAM'] !== 'vscode') {
return undefined;
}
const ide = detectIdeFromEnv();
return verifyVSCode(ide, ideProcessInfo);
}

View File

@@ -4,75 +4,229 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect } from 'vitest';
import * as path from 'path';
import { IdeClient } from './ide-client.js';
import {
describe,
it,
expect,
vi,
beforeEach,
afterEach,
type Mocked,
} from 'vitest';
import { IdeClient, IDEConnectionStatus } from './ide-client.js';
import * as fs from 'node:fs';
import { getIdeProcessInfo } from './process-utils.js';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import {
detectIde,
DetectedIde,
getIdeInfo,
type IdeInfo,
} from './detect-ide.js';
import * as os from 'node:os';
import * as path from 'node:path';
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);
vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal();
return {
...(actual as object),
promises: {
readFile: vi.fn(),
},
realpathSync: (p: string) => p,
existsSync: () => false,
};
});
vi.mock('./process-utils.js');
vi.mock('@modelcontextprotocol/sdk/client/index.js');
vi.mock('@modelcontextprotocol/sdk/client/streamableHttp.js');
vi.mock('@modelcontextprotocol/sdk/client/stdio.js');
vi.mock('./detect-ide.js');
vi.mock('node:os');
describe('IdeClient', () => {
let mockClient: Mocked<Client>;
let mockHttpTransport: Mocked<StreamableHTTPClientTransport>;
let mockStdioTransport: Mocked<StdioClientTransport>;
beforeEach(async () => {
// Reset singleton instance for test isolation
(IdeClient as unknown as { instance: IdeClient | undefined }).instance =
undefined;
// Mock environment variables
process.env['QWEN_CODE_IDE_WORKSPACE_PATH'] = '/test/workspace';
delete process.env['QWEN_CODE_IDE_SERVER_PORT'];
delete process.env['QWEN_CODE_IDE_SERVER_STDIO_COMMAND'];
delete process.env['QWEN_CODE_IDE_SERVER_STDIO_ARGS'];
// Mock dependencies
vi.spyOn(process, 'cwd').mockReturnValue('/test/workspace/sub-dir');
vi.mocked(detectIde).mockReturnValue(DetectedIde.VSCode);
vi.mocked(getIdeInfo).mockReturnValue({
displayName: 'VS Code',
} as IdeInfo);
vi.mocked(getIdeProcessInfo).mockResolvedValue({
pid: 12345,
command: 'test-ide',
});
vi.mocked(os.tmpdir).mockReturnValue('/tmp');
// Mock MCP client and transports
mockClient = {
connect: vi.fn().mockResolvedValue(undefined),
close: vi.fn(),
setNotificationHandler: vi.fn(),
callTool: vi.fn(),
} as unknown as Mocked<Client>;
mockHttpTransport = {
close: vi.fn(),
} as unknown as Mocked<StreamableHTTPClientTransport>;
mockStdioTransport = {
close: vi.fn(),
} as unknown as Mocked<StdioClientTransport>;
vi.mocked(Client).mockReturnValue(mockClient);
vi.mocked(StreamableHTTPClientTransport).mockReturnValue(mockHttpTransport);
vi.mocked(StdioClientTransport).mockReturnValue(mockStdioTransport);
await IdeClient.getInstance();
});
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');
afterEach(() => {
vi.restoreAllMocks();
});
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');
});
describe('connect', () => {
it('should connect using HTTP when port is provided in config file', async () => {
const config = { port: '8080' };
vi.mocked(fs.promises.readFile).mockResolvedValue(JSON.stringify(config));
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');
});
const ideClient = await IdeClient.getInstance();
await ideClient.connect();
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);
});
expect(fs.promises.readFile).toHaveBeenCalledWith(
path.join('/tmp', 'qwen-code-ide-server-12345.json'),
'utf8',
);
expect(StreamableHTTPClientTransport).toHaveBeenCalledWith(
new URL('http://localhost:8080/mcp'),
expect.any(Object),
);
expect(mockClient.connect).toHaveBeenCalledWith(mockHttpTransport);
expect(ideClient.getConnectionStatus().status).toBe(
IDEConnectionStatus.Connected,
);
});
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('should connect using stdio when stdio config is provided in file', async () => {
const config = { stdio: { command: 'test-cmd', args: ['--foo'] } };
vi.mocked(fs.promises.readFile).mockResolvedValue(JSON.stringify(config));
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);
const ideClient = await IdeClient.getInstance();
await ideClient.connect();
expect(StdioClientTransport).toHaveBeenCalledWith({
command: 'test-cmd',
args: ['--foo'],
});
expect(mockClient.connect).toHaveBeenCalledWith(mockStdioTransport);
expect(ideClient.getConnectionStatus().status).toBe(
IDEConnectionStatus.Connected,
);
});
it('should prioritize port over stdio when both are in config file', async () => {
const config = {
port: '8080',
stdio: { command: 'test-cmd', args: ['--foo'] },
};
vi.mocked(fs.promises.readFile).mockResolvedValue(JSON.stringify(config));
const ideClient = await IdeClient.getInstance();
await ideClient.connect();
expect(StreamableHTTPClientTransport).toHaveBeenCalled();
expect(StdioClientTransport).not.toHaveBeenCalled();
expect(ideClient.getConnectionStatus().status).toBe(
IDEConnectionStatus.Connected,
);
});
it('should connect using HTTP when port is provided in environment variables', async () => {
vi.mocked(fs.promises.readFile).mockRejectedValue(
new Error('File not found'),
);
process.env['QWEN_CODE_IDE_SERVER_PORT'] = '9090';
const ideClient = await IdeClient.getInstance();
await ideClient.connect();
expect(StreamableHTTPClientTransport).toHaveBeenCalledWith(
new URL('http://localhost:9090/mcp'),
expect.any(Object),
);
expect(mockClient.connect).toHaveBeenCalledWith(mockHttpTransport);
expect(ideClient.getConnectionStatus().status).toBe(
IDEConnectionStatus.Connected,
);
});
it('should connect using stdio when stdio config is in environment variables', async () => {
vi.mocked(fs.promises.readFile).mockRejectedValue(
new Error('File not found'),
);
process.env['QWEN_CODE_IDE_SERVER_STDIO_COMMAND'] = 'env-cmd';
process.env['QWEN_CODE_IDE_SERVER_STDIO_ARGS'] = '["--bar"]';
const ideClient = await IdeClient.getInstance();
await ideClient.connect();
expect(StdioClientTransport).toHaveBeenCalledWith({
command: 'env-cmd',
args: ['--bar'],
});
expect(mockClient.connect).toHaveBeenCalledWith(mockStdioTransport);
expect(ideClient.getConnectionStatus().status).toBe(
IDEConnectionStatus.Connected,
);
});
it('should prioritize file config over environment variables', async () => {
const config = { port: '8080' };
vi.mocked(fs.promises.readFile).mockResolvedValue(JSON.stringify(config));
process.env['QWEN_CODE_IDE_SERVER_PORT'] = '9090';
const ideClient = await IdeClient.getInstance();
await ideClient.connect();
expect(StreamableHTTPClientTransport).toHaveBeenCalledWith(
new URL('http://localhost:8080/mcp'),
expect.any(Object),
);
expect(ideClient.getConnectionStatus().status).toBe(
IDEConnectionStatus.Connected,
);
});
it('should be disconnected if no config is found', async () => {
vi.mocked(fs.promises.readFile).mockRejectedValue(
new Error('File not found'),
);
const ideClient = await IdeClient.getInstance();
await ideClient.connect();
expect(StreamableHTTPClientTransport).not.toHaveBeenCalled();
expect(StdioClientTransport).not.toHaveBeenCalled();
expect(ideClient.getConnectionStatus().status).toBe(
IDEConnectionStatus.Disconnected,
);
expect(ideClient.getConnectionStatus().details).toContain(
'Failed to connect',
);
});
});
});

View File

@@ -6,18 +6,19 @@
import * as fs from 'node:fs';
import { isSubpath } from '../utils/paths.js';
import { detectIde, DetectedIde, getIdeInfo } from '../ide/detect-ide.js';
import { detectIde, type DetectedIde, getIdeInfo } from '../ide/detect-ide.js';
import type { DiffUpdateResult } from '../ide/ideContext.js';
import {
ideContext,
IdeContextNotificationSchema,
IdeDiffAcceptedNotificationSchema,
IdeDiffClosedNotificationSchema,
CloseDiffResponseSchema,
DiffUpdateResult,
} from '../ide/ideContext.js';
import { getIdeProcessId } from './process-utils.js';
import { getIdeProcessInfo } from './process-utils.js';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import * as os from 'node:os';
import * as path from 'node:path';
import { EnvHttpProxyAgent } from 'undici';
@@ -40,6 +41,16 @@ export enum IDEConnectionStatus {
Connecting = 'connecting',
}
type StdioConfig = {
command: string;
args: string[];
};
type ConnectionConfig = {
port?: string;
stdio?: StdioConfig;
};
function getRealPath(path: string): string {
try {
return fs.realpathSync(path);
@@ -61,21 +72,25 @@ export class IdeClient {
details:
'IDE integration is currently disabled. To enable it, run /ide enable.',
};
private readonly currentIde: DetectedIde | undefined;
private readonly currentIdeDisplayName: string | undefined;
private currentIde: DetectedIde | undefined;
private currentIdeDisplayName: string | undefined;
private ideProcessInfo: { pid: number; command: string } | undefined;
private diffResponses = new Map<string, (result: DiffUpdateResult) => void>();
private statusListeners = new Set<(state: IDEConnectionState) => void>();
private constructor() {
this.currentIde = detectIde();
if (this.currentIde) {
this.currentIdeDisplayName = getIdeInfo(this.currentIde).displayName;
}
}
private constructor() {}
static getInstance(): IdeClient {
static async getInstance(): Promise<IdeClient> {
if (!IdeClient.instance) {
IdeClient.instance = new IdeClient();
const client = new IdeClient();
client.ideProcessInfo = await getIdeProcessInfo();
client.currentIde = detectIde(client.ideProcessInfo);
if (client.currentIde) {
client.currentIdeDisplayName = getIdeInfo(
client.currentIde,
).displayName;
}
IdeClient.instance = client;
}
return IdeClient.instance;
}
@@ -92,11 +107,7 @@ export class IdeClient {
if (!this.currentIde || !this.currentIdeDisplayName) {
this.setState(
IDEConnectionStatus.Disconnected,
`IDE integration is not supported in your current environment. To use this feature, run Qwen Code in one of these supported IDEs: ${Object.values(
DetectedIde,
)
.map((ide) => getIdeInfo(ide).displayName)
.join(', ')}`,
`IDE integration is not supported in your current environment. To use this feature, run Qwen Code in one of these supported IDEs: VS Code or VS Code forks`,
false,
);
return;
@@ -104,9 +115,9 @@ export class IdeClient {
this.setState(IDEConnectionStatus.Connecting);
const ideInfoFromFile = await this.getIdeInfoFromFile();
const configFromFile = await this.getConnectionConfigFromFile();
const workspacePath =
ideInfoFromFile.workspacePath ??
configFromFile?.workspacePath ??
process.env['QWEN_CODE_IDE_WORKSPACE_PATH'];
const { isValid, error } = IdeClient.validateWorkspacePath(
@@ -120,17 +131,36 @@ export class IdeClient {
return;
}
const portFromFile = ideInfoFromFile.port;
if (portFromFile) {
const connected = await this.establishConnection(portFromFile);
if (connected) {
return;
if (configFromFile) {
if (configFromFile.port) {
const connected = await this.establishHttpConnection(
configFromFile.port,
);
if (connected) {
return;
}
}
if (configFromFile.stdio) {
const connected = await this.establishStdioConnection(
configFromFile.stdio,
);
if (connected) {
return;
}
}
}
const portFromEnv = this.getPortFromEnv();
if (portFromEnv) {
const connected = await this.establishConnection(portFromEnv);
const connected = await this.establishHttpConnection(portFromEnv);
if (connected) {
return;
}
}
const stdioConfigFromEnv = this.getStdioConfigFromEnv();
if (stdioConfigFromEnv) {
const connected = await this.establishStdioConnection(stdioConfigFromEnv);
if (connected) {
return;
}
@@ -138,7 +168,7 @@ export class IdeClient {
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.`,
`Failed to connect to IDE companion extension in ${this.currentIdeDisplayName}. Please ensure the extension is running. To install the extension, run /ide install.`,
true,
);
}
@@ -279,7 +309,7 @@ export class IdeClient {
if (ideWorkspacePath === undefined) {
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.`,
error: `Failed to connect to IDE companion extension in ${currentIdeDisplayName}. Please ensure the extension is running. To install the extension, run /ide install.`,
};
}
@@ -316,24 +346,47 @@ export class IdeClient {
return port;
}
private async getIdeInfoFromFile(): Promise<{
port?: string;
workspacePath?: string;
}> {
private getStdioConfigFromEnv(): StdioConfig | undefined {
const command = process.env['QWEN_CODE_IDE_SERVER_STDIO_COMMAND'];
if (!command) {
return undefined;
}
const argsStr = process.env['QWEN_CODE_IDE_SERVER_STDIO_ARGS'];
let args: string[] = [];
if (argsStr) {
try {
const parsedArgs = JSON.parse(argsStr);
if (Array.isArray(parsedArgs)) {
args = parsedArgs;
} else {
logger.error(
'QWEN_CODE_IDE_SERVER_STDIO_ARGS must be a JSON array string.',
);
}
} catch (e) {
logger.error('Failed to parse QWEN_CODE_IDE_SERVER_STDIO_ARGS:', e);
}
}
return { command, args };
}
private async getConnectionConfigFromFile(): Promise<
(ConnectionConfig & { workspacePath?: string }) | undefined
> {
if (!this.ideProcessInfo) {
return {};
}
try {
const ideProcessId = await getIdeProcessId();
const portFile = path.join(
os.tmpdir(),
`qwen-code-ide-server-${ideProcessId}.json`,
`qwen-code-ide-server-${this.ideProcessInfo.pid}.json`,
);
const portFileContents = await fs.promises.readFile(portFile, 'utf8');
const ideInfo = JSON.parse(portFileContents);
return {
port: ideInfo?.port?.toString(),
workspacePath: ideInfo?.workspacePath,
};
return JSON.parse(portFileContents);
} catch (_) {
return {};
return undefined;
}
}
@@ -414,9 +467,10 @@ export class IdeClient {
);
}
private async establishConnection(port: string): Promise<boolean> {
private async establishHttpConnection(port: string): Promise<boolean> {
let transport: StreamableHTTPClientTransport | undefined;
try {
logger.debug('Attempting to connect to IDE via HTTP SSE');
this.client = new Client({
name: 'streamable-http-client',
// TODO(#3487): use the CLI version here.
@@ -447,6 +501,39 @@ export class IdeClient {
return false;
}
}
private async establishStdioConnection({
command,
args,
}: StdioConfig): Promise<boolean> {
let transport: StdioClientTransport | undefined;
try {
logger.debug('Attempting to connect to IDE via stdio');
this.client = new Client({
name: 'stdio-client',
// TODO(#3487): use the CLI version here.
version: '1.0.0',
});
transport = new StdioClientTransport({
command,
args,
});
await this.client.connect(transport);
this.registerClientHandlers();
this.setState(IDEConnectionStatus.Connected);
return true;
} catch (_error) {
if (transport) {
try {
await transport.close();
} catch (closeError) {
logger.debug('Failed to close transport:', closeError);
}
}
return false;
}
}
}
function getIdeServerHost() {

View File

@@ -5,10 +5,11 @@
*/
import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
import { getIdeInstaller, IdeInstaller } from './ide-installer.js';
import * as child_process from 'child_process';
import * as fs from 'fs';
import * as os from 'os';
import { getIdeInstaller } from './ide-installer.js';
import * as child_process from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { DetectedIde } from './detect-ide.js';
vi.mock('child_process');
@@ -16,8 +17,10 @@ vi.mock('fs');
vi.mock('os');
describe('ide-installer', () => {
const HOME_DIR = '/home/user';
beforeEach(() => {
vi.spyOn(os, 'homedir').mockReturnValue('/home/user');
vi.spyOn(os, 'homedir').mockReturnValue(HOME_DIR);
});
afterEach(() => {
@@ -25,41 +28,123 @@ describe('ide-installer', () => {
});
describe('getIdeInstaller', () => {
it('should return a VsCodeInstaller for "vscode"', () => {
const installer = getIdeInstaller(DetectedIde.VSCode);
expect(installer).not.toBeNull();
// A more specific check might be needed if we export the class
expect(installer).toBeInstanceOf(Object);
});
it.each([{ ide: DetectedIde.VSCode }, { ide: DetectedIde.FirebaseStudio }])(
'returns a VsCodeInstaller for "$ide"',
({ ide }) => {
const installer = getIdeInstaller(ide);
it('should return null for an unknown IDE', () => {
const installer = getIdeInstaller('unknown' as DetectedIde);
expect(installer).toBeNull();
});
expect(installer).not.toBeNull();
expect(installer?.install).toEqual(expect.any(Function));
},
);
});
describe('VsCodeInstaller', () => {
let installer: IdeInstaller;
function setup({
ide = DetectedIde.VSCode,
existsResult = false,
execSync = () => '',
platform = 'linux' as NodeJS.Platform,
} = {}) {
vi.spyOn(child_process, 'execSync').mockImplementation(execSync);
vi.spyOn(fs, 'existsSync').mockReturnValue(existsResult);
const installer = getIdeInstaller(ide, platform)!;
beforeEach(() => {
// We get a new installer for each test to reset the find command logic
installer = getIdeInstaller(DetectedIde.VSCode)!;
vi.spyOn(child_process, 'execSync').mockImplementation(() => '');
vi.spyOn(fs, 'existsSync').mockReturnValue(false);
});
return { installer };
}
describe('install', () => {
it('should return a failure message if VS Code is not installed', async () => {
vi.spyOn(child_process, 'execSync').mockImplementation(() => {
throw new Error('Command not found');
it.each([
{
platform: 'win32' as NodeJS.Platform,
expectedLookupPaths: [
path.join('C:\\Program Files', 'Microsoft VS Code/bin/code.cmd'),
path.join(
HOME_DIR,
'/AppData/Local/Programs/Microsoft VS Code/bin/code.cmd',
),
],
},
{
platform: 'darwin' as NodeJS.Platform,
expectedLookupPaths: [
'/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code',
path.join(HOME_DIR, 'Library/Application Support/Code/bin/code'),
],
},
{
platform: 'linux' as NodeJS.Platform,
expectedLookupPaths: ['/usr/share/code/bin/code'],
},
])(
'identifies the path to code cli on platform: $platform',
async ({ platform, expectedLookupPaths }) => {
const { installer } = setup({
platform,
execSync: () => {
throw new Error('Command not found'); // `code` is not in PATH
},
});
await installer.install();
for (const [idx, path] of expectedLookupPaths.entries()) {
expect(fs.existsSync).toHaveBeenNthCalledWith(idx + 1, path);
}
},
);
it('installs the extension using code cli', async () => {
const { installer } = setup({
platform: 'linux',
});
vi.spyOn(fs, 'existsSync').mockReturnValue(false);
// Re-create the installer so it re-runs findVsCodeCommand
installer = getIdeInstaller(DetectedIde.VSCode)!;
const result = await installer.install();
expect(result.success).toBe(false);
expect(result.message).toContain('VS Code CLI not found');
await installer.install();
expect(child_process.execSync).toHaveBeenCalledWith(
'"code" --install-extension qwenlm.qwen-code-vscode-ide-companion --force',
{ stdio: 'pipe' },
);
});
it.each([
{
ide: DetectedIde.VSCode,
expectedMessage:
'VS Code companion extension was installed successfully',
},
{
ide: DetectedIde.FirebaseStudio,
expectedMessage:
'Firebase Studio companion extension was installed successfully',
},
])(
'returns that the cli was installed successfully',
async ({ ide, expectedMessage }) => {
const { installer } = setup({ ide });
const result = await installer.install();
expect(result.success).toBe(true);
expect(result.message).toContain(expectedMessage);
},
);
it.each([
{ ide: DetectedIde.VSCode, expectedErr: 'VS Code CLI not found' },
{
ide: DetectedIde.FirebaseStudio,
expectedErr: 'Firebase Studio CLI not found',
},
])(
'should return a failure message if $ide is not installed',
async ({ ide, expectedErr }) => {
const { installer } = setup({
ide,
execSync: () => {
throw new Error('Command not found');
},
existsResult: false,
});
const result = await installer.install();
expect(result.success).toBe(false);
expect(result.message).toContain(expectedErr);
},
);
});
});
});

View File

@@ -4,15 +4,17 @@
* SPDX-License-Identifier: Apache-2.0
*/
import * as child_process from 'child_process';
import * as process from 'process';
import * as path from 'path';
import * as fs from 'fs';
import * as os from 'os';
import { DetectedIde } from './detect-ide.js';
import * as child_process from 'node:child_process';
import * as process from 'node:process';
import * as path from 'node:path';
import * as fs from 'node:fs';
import * as os from 'node:os';
import { DetectedIde, getIdeInfo, type IdeInfo } from './detect-ide.js';
import { QWEN_CODE_COMPANION_EXTENSION_NAME } from './constants.js';
const VSCODE_COMMAND = process.platform === 'win32' ? 'code.cmd' : 'code';
function getVsCodeCommand(platform: NodeJS.Platform = process.platform) {
return platform === 'win32' ? 'code.cmd' : 'code';
}
export interface IdeInstaller {
install(): Promise<InstallResult>;
@@ -23,12 +25,15 @@ export interface InstallResult {
message: string;
}
async function findVsCodeCommand(): Promise<string | null> {
async function findVsCodeCommand(
platform: NodeJS.Platform = process.platform,
): Promise<string | null> {
// 1. Check PATH first.
const vscodeCommand = getVsCodeCommand(platform);
try {
if (process.platform === 'win32') {
if (platform === 'win32') {
const result = child_process
.execSync(`where.exe ${VSCODE_COMMAND}`)
.execSync(`where.exe ${vscodeCommand}`)
.toString()
.trim();
// `where.exe` can return multiple paths. Return the first one.
@@ -37,10 +42,10 @@ async function findVsCodeCommand(): Promise<string | null> {
return firstPath;
}
} else {
child_process.execSync(`command -v ${VSCODE_COMMAND}`, {
child_process.execSync(`command -v ${vscodeCommand}`, {
stdio: 'ignore',
});
return VSCODE_COMMAND;
return vscodeCommand;
}
} catch {
// Not in PATH, continue to check common locations.
@@ -48,7 +53,6 @@ async function findVsCodeCommand(): Promise<string | null> {
// 2. Check common installation locations.
const locations: string[] = [];
const platform = process.platform;
const homeDir = os.homedir();
if (platform === 'darwin') {
@@ -96,9 +100,14 @@ async function findVsCodeCommand(): Promise<string | null> {
class VsCodeInstaller implements IdeInstaller {
private vsCodeCommand: Promise<string | null>;
private readonly ideInfo: IdeInfo;
constructor() {
this.vsCodeCommand = findVsCodeCommand();
constructor(
readonly ide: DetectedIde,
readonly platform = process.platform,
) {
this.vsCodeCommand = findVsCodeCommand(platform);
this.ideInfo = getIdeInfo(ide);
}
async install(): Promise<InstallResult> {
@@ -106,7 +115,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 '${QWEN_CODE_COMPANION_EXTENSION_NAME}' extension manually from the VS Code marketplace.`,
message: `${this.ideInfo.displayName} 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.`,
};
}
@@ -115,21 +124,25 @@ class VsCodeInstaller implements IdeInstaller {
child_process.execSync(command, { stdio: 'pipe' });
return {
success: true,
message: 'VS Code companion extension was installed successfully.',
message: `${this.ideInfo.displayName} companion extension was installed successfully.`,
};
} catch (_error) {
return {
success: false,
message: `Failed to install VS Code companion extension. Please try installing '${QWEN_CODE_COMPANION_EXTENSION_NAME}' manually from the VS Code extension marketplace.`,
message: `Failed to install ${this.ideInfo.displayName} companion extension. Please try installing '${QWEN_CODE_COMPANION_EXTENSION_NAME}' manually from the ${this.ideInfo.displayName} extension marketplace.`,
};
}
}
}
export function getIdeInstaller(ide: DetectedIde): IdeInstaller | null {
export function getIdeInstaller(
ide: DetectedIde,
platform = process.platform,
): IdeInstaller | null {
switch (ide) {
case DetectedIde.VSCode:
return new VsCodeInstaller();
case DetectedIde.FirebaseStudio:
return new VsCodeInstaller(ide, platform);
default:
return null;
}

View File

@@ -0,0 +1,90 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {
describe,
it,
expect,
vi,
afterEach,
beforeEach,
type Mock,
} from 'vitest';
import { getIdeProcessInfo } from './process-utils.js';
import os from 'node:os';
const mockedExec = vi.hoisted(() => vi.fn());
vi.mock('node:util', () => ({
promisify: vi.fn().mockReturnValue(mockedExec),
}));
vi.mock('node:os', () => ({
default: {
platform: vi.fn(),
},
}));
describe('getIdeProcessInfo', () => {
beforeEach(() => {
Object.defineProperty(process, 'pid', { value: 1000, configurable: true });
mockedExec.mockReset();
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('on Unix', () => {
it('should traverse up to find the shell and return grandparent process info', async () => {
(os.platform as Mock).mockReturnValue('linux');
// process (1000) -> shell (800) -> IDE (700)
mockedExec
.mockResolvedValueOnce({ stdout: '800 /bin/bash' }) // pid 1000 -> ppid 800 (shell)
.mockResolvedValueOnce({ stdout: '700 /usr/lib/vscode/code' }) // pid 800 -> ppid 700 (IDE)
.mockResolvedValueOnce({ stdout: '700 /usr/lib/vscode/code' }); // get command for pid 700
const result = await getIdeProcessInfo();
expect(result).toEqual({ pid: 700, command: '/usr/lib/vscode/code' });
});
it('should return parent process info if grandparent lookup fails', async () => {
(os.platform as Mock).mockReturnValue('linux');
mockedExec
.mockResolvedValueOnce({ stdout: '800 /bin/bash' }) // pid 1000 -> ppid 800 (shell)
.mockRejectedValueOnce(new Error('ps failed')) // lookup for ppid of 800 fails
.mockResolvedValueOnce({ stdout: '800 /bin/bash' }); // get command for pid 800
const result = await getIdeProcessInfo();
expect(result).toEqual({ pid: 800, command: '/bin/bash' });
});
});
describe('on Windows', () => {
it('should traverse up and find the great-grandchild of the root process', async () => {
(os.platform as Mock).mockReturnValue('win32');
const processInfoMap = new Map([
[1000, { stdout: 'ParentProcessId=900\r\nCommandLine=node.exe\r\n' }],
[
900,
{ stdout: 'ParentProcessId=800\r\nCommandLine=powershell.exe\r\n' },
],
[800, { stdout: 'ParentProcessId=700\r\nCommandLine=code.exe\r\n' }],
[700, { stdout: 'ParentProcessId=0\r\nCommandLine=wininit.exe\r\n' }],
]);
mockedExec.mockImplementation((command: string) => {
const pidMatch = command.match(/ProcessId=(\d+)/);
if (pidMatch) {
const pid = parseInt(pidMatch[1], 10);
return Promise.resolve(processInfoMap.get(pid));
}
return Promise.reject(new Error('Invalid command for mock'));
});
const result = await getIdeProcessInfo();
expect(result).toEqual({ pid: 900, command: 'powershell.exe' });
});
});
});

View File

@@ -4,34 +4,37 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { exec } from 'child_process';
import { promisify } from 'util';
import os from 'os';
import path from 'path';
import { exec } from 'node:child_process';
import { promisify } from 'node:util';
import os from 'node:os';
import path from 'node:path';
const execAsync = promisify(exec);
const MAX_TRAVERSAL_DEPTH = 32;
/**
* Fetches the parent process ID and name for a given process ID.
* Fetches the parent process ID, name, and command for a given process ID.
*
* @param pid The process ID to inspect.
* @returns A promise that resolves to the parent's PID and name.
* @returns A promise that resolves to the parent's PID, name, and command.
*/
async function getParentProcessInfo(pid: number): Promise<{
async function getProcessInfo(pid: number): Promise<{
parentPid: number;
name: string;
command: string;
}> {
const platform = os.platform();
if (platform === 'win32') {
const command = `wmic process where "ProcessId=${pid}" get Name,ParentProcessId /value`;
const command = `wmic process where "ProcessId=${pid}" get Name,ParentProcessId,CommandLine /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 };
const commandLineMatch = stdout.match(/CommandLine=([^\n]*)/);
const commandLine = commandLineMatch ? commandLineMatch[1].trim() : '';
return { parentPid, name: processName, command: commandLine };
} else {
const command = `ps -o ppid=,command= -p ${pid}`;
const { stdout } = await execAsync(command);
@@ -40,42 +43,50 @@ async function getParentProcessInfo(pid: number): Promise<{
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 };
return {
parentPid: isNaN(parentPid) ? 1 : parentPid,
name: processName,
command: fullCommand,
};
}
}
/**
* Traverses the process tree on Unix-like systems to find the IDE process ID.
* Finds the IDE process info on Unix-like systems.
*
* 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.
* @returns A promise that resolves to the PID and command of the IDE process.
*/
async function getIdeProcessIdForUnix(): Promise<number> {
async function getIdeProcessInfoForUnix(): Promise<{
pid: number;
command: string;
}> {
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 { parentPid, name } = await getProcessInfo(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.
let idePid = parentPid;
try {
const { parentPid: grandParentPid } =
await getParentProcessInfo(parentPid);
const { parentPid: grandParentPid } = await getProcessInfo(parentPid);
if (grandParentPid > 1) {
return grandParentPid;
idePid = grandParentPid;
}
} catch {
// Ignore if getting grandparent fails, we'll just use the parent pid.
}
return parentPid;
const { command } = await getProcessInfo(idePid);
return { pid: idePid, command };
}
if (parentPid <= 1) {
@@ -88,33 +99,36 @@ async function getIdeProcessIdForUnix(): Promise<number> {
}
}
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;
const { command } = await getProcessInfo(currentPid);
return { pid: currentPid, command };
}
/**
* Traverses the process tree on Windows to find the IDE process ID.
* Finds the IDE process info on Windows.
*
* The strategy is to find the grandchild of the root process.
* The strategy is to find the great-grandchild of the root process.
*
* @returns A promise that resolves to the numeric PID.
* @returns A promise that resolves to the PID and command of the IDE process.
*/
async function getIdeProcessIdForWindows(): Promise<number> {
async function getIdeProcessInfoForWindows(): Promise<{
pid: number;
command: string;
}> {
let currentPid = process.pid;
let previousPid = process.pid;
for (let i = 0; i < MAX_TRAVERSAL_DEPTH; i++) {
try {
const { parentPid } = await getParentProcessInfo(currentPid);
const { parentPid } = await getProcessInfo(currentPid);
if (parentPid > 0) {
try {
const { parentPid: grandParentPid } =
await getParentProcessInfo(parentPid);
const { parentPid: grandParentPid } = await getProcessInfo(parentPid);
if (grandParentPid === 0) {
// Found grandchild of root
return currentPid;
// We've found the grandchild of the root (`currentPid`). The IDE
// process is its child, which we've stored in `previousPid`.
const { command } = await getProcessInfo(previousPid);
return { pid: previousPid, command };
}
} catch {
// getting grandparent failed, proceed
@@ -124,34 +138,39 @@ async function getIdeProcessIdForWindows(): Promise<number> {
if (parentPid <= 0) {
break; // Reached the root
}
previousPid = currentPid;
currentPid = parentPid;
} catch {
// Process in chain died
break;
}
}
return currentPid;
const { command } = await getProcessInfo(currentPid);
return { pid: currentPid, command };
}
/**
* Traverses up the process tree to find the process ID of the IDE.
* Traverses up the process tree to find the process ID and command 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.
* top-level ancestor process ID and command as a fallback.
*
* @returns A promise that resolves to the numeric PID of the IDE process.
* @returns A promise that resolves to the PID and command of the IDE process.
* @throws Will throw an error if the underlying shell commands fail.
*/
export async function getIdeProcessId(): Promise<number> {
export async function getIdeProcessInfo(): Promise<{
pid: number;
command: string;
}> {
const platform = os.platform();
if (platform === 'win32') {
return getIdeProcessIdForWindows();
return getIdeProcessInfoForWindows();
}
return getIdeProcessIdForUnix();
return getIdeProcessInfoForUnix();
}