summaryrefslogtreecommitdiff
path: root/packages/core/src
diff options
context:
space:
mode:
Diffstat (limited to 'packages/core/src')
-rw-r--r--packages/core/src/ide/ide-client.ts56
-rw-r--r--packages/core/src/ide/process-utils.ts62
2 files changed, 102 insertions, 16 deletions
diff --git a/packages/core/src/ide/ide-client.ts b/packages/core/src/ide/ide-client.ts
index fe605eb2..94107f21 100644
--- a/packages/core/src/ide/ide-client.ts
+++ b/packages/core/src/ide/ide-client.ts
@@ -5,7 +5,6 @@
*/
import * as fs from 'node:fs';
-import * as path from 'node:path';
import { detectIde, DetectedIde, getIdeInfo } from '../ide/detect-ide.js';
import {
ideContext,
@@ -15,8 +14,11 @@ 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';
const logger = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -95,12 +97,27 @@ export class IdeClient {
return;
}
- const port = this.getPortFromEnv();
- if (!port) {
- return;
+ const portFromFile = await this.getPortFromFile();
+ 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 and try restarting your terminal. To install the extension, run /ide install.`,
+ true,
+ );
}
/**
@@ -264,16 +281,26 @@ export class IdeClient {
private getPortFromEnv(): string | undefined {
const port = process.env['GEMINI_CLI_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 getPortFromFile(): Promise<string | undefined> {
+ try {
+ const ideProcessId = await getIdeProcessId();
+ const portFile = path.join(
+ os.tmpdir(),
+ `gemini-ide-server-${ideProcessId}.json`,
+ );
+ const portFileContents = await fs.promises.readFile(portFile, 'utf8');
+ const port = JSON.parse(portFileContents).port;
+ return port.toString();
+ } catch (_) {
+ return undefined;
+ }
+ }
+
private registerClientHandlers() {
if (!this.client) {
return;
@@ -328,7 +355,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({
@@ -342,12 +369,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();
@@ -355,6 +378,7 @@ export class IdeClient {
logger.debug('Failed to close transport:', closeError);
}
}
+ return false;
}
}
}
diff --git a/packages/core/src/ide/process-utils.ts b/packages/core/src/ide/process-utils.ts
new file mode 100644
index 00000000..40e16a73
--- /dev/null
+++ b/packages/core/src/ide/process-utils.ts
@@ -0,0 +1,62 @@
+/**
+ * @license
+ * Copyright 2025 Google LLC
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+import { exec } from 'child_process';
+import { promisify } from 'util';
+import os from 'os';
+
+const execAsync = promisify(exec);
+
+/**
+ * Traverses up the process tree from the current process to find the top-level ancestor process ID.
+ * This is useful for identifying the main application process that spawned the current script,
+ * such as the main VS Code window process.
+ *
+ * @returns A promise that resolves to the numeric PID of the top-level process.
+ * @throws Will throw an error if the underlying shell commands fail unexpectedly.
+ */
+export async function getIdeProcessId(): Promise<number> {
+ const platform = os.platform();
+ let currentPid = process.pid;
+
+ // Loop upwards through the process tree, with a depth limit to prevent infinite loops.
+ const MAX_TRAVERSAL_DEPTH = 32;
+ for (let i = 0; i < MAX_TRAVERSAL_DEPTH; i++) {
+ let parentPid: number;
+
+ try {
+ // Use wmic for Windows
+ if (platform === 'win32') {
+ const command = `wmic process where "ProcessId=${currentPid}" get ParentProcessId /value`;
+ const { stdout } = await execAsync(command);
+ const match = stdout.match(/ParentProcessId=(\d+)/);
+ parentPid = match ? parseInt(match[1], 10) : 0; // Top of the tree is 0
+ }
+ // Use ps for macOS, Linux, and other Unix-like systems
+ else {
+ const command = `ps -o ppid= -p ${currentPid}`;
+ const { stdout } = await execAsync(command);
+ const ppid = parseInt(stdout.trim(), 10);
+ parentPid = isNaN(ppid) ? 1 : ppid; // Top of the tree is 1
+ }
+ } catch (_) {
+ // This can happen if a process in the chain dies during execution.
+ // We'll break the loop and return the last valid PID we found.
+ break;
+ }
+
+ // Define the root PID for the current OS
+ const rootPid = platform === 'win32' ? 0 : 1;
+
+ // If the parent is the root process or invalid, we've found our target.
+ if (parentPid === rootPid || parentPid <= 0) {
+ break;
+ }
+ // Move one level up the tree for the next iteration.
+ currentPid = parentPid;
+ }
+ return currentPid;
+}