mirror of
https://github.com/QwenLM/qwen-code.git
synced 2025-12-19 09:33:53 +00:00
Merge tag 'v0.1.15' into feature/yiheng/sync-gemini-cli-0.1.15
This commit is contained in:
6
packages/vscode-ide-companion/.vscodeignore
Normal file
6
packages/vscode-ide-companion/.vscodeignore
Normal file
@@ -0,0 +1,6 @@
|
||||
**
|
||||
!dist/
|
||||
../
|
||||
../../
|
||||
!LICENSE
|
||||
!assets/
|
||||
202
packages/vscode-ide-companion/LICENSE
Normal file
202
packages/vscode-ide-companion/LICENSE
Normal file
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2025 Google LLC
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,9 +1,20 @@
|
||||
# IDE Companion
|
||||
# Qwen Code Companion
|
||||
|
||||
## Local Development
|
||||
The Qwen Code Companion extension seamlessly integrates [Qwen Code](https://github.com/QwenLM/qwen-code) into your VS Code environment. This integration enables Qwen Code to access active information like your open files.
|
||||
|
||||
To test the extension locally, follow these steps:
|
||||
# Features
|
||||
|
||||
1. Open the `packages/vscode-ide-companion` directory in VS Code.
|
||||
2. Run `npm install`.
|
||||
3. Run the extension development host via Run + Debug -> Extension
|
||||
- Open Editor File Context: Qwen Code gains awareness of the files you have open in your editor, providing it with a richer understanding of your project's structure and content.
|
||||
|
||||
- Selection Context: Qwen Code can easily access your cursor's position and selected text within the editor, giving it valuable context directly from your current work.
|
||||
|
||||
# Requirements
|
||||
|
||||
To use this extension, you'll need:
|
||||
|
||||
- VS Code version 1.101.0 or newer
|
||||
- Qwen Code (installed separately) running within the VS Code integrated terminal
|
||||
|
||||
# Terms of Service and Privacy Notice
|
||||
|
||||
By installing this extension, you agree to the [Terms of Service](https://github.com/QwenLM/qwen-code/blob/main/docs/tos-privacy.md).
|
||||
|
||||
BIN
packages/vscode-ide-companion/assets/icon.png
Normal file
BIN
packages/vscode-ide-companion/assets/icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 46 KiB |
@@ -1,3 +1,9 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import typescriptEslint from '@typescript-eslint/eslint-plugin';
|
||||
import tsParser from '@typescript-eslint/parser';
|
||||
|
||||
|
||||
4986
packages/vscode-ide-companion/package-lock.json
generated
4986
packages/vscode-ide-companion/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,28 +1,56 @@
|
||||
{
|
||||
"name": "@qwen-code/qwen-code-vscode-ide-companion",
|
||||
"displayName": "Qwen Code VSCode IDE Companion",
|
||||
"description": "",
|
||||
"name": "qwen-code-vscode-ide-companion",
|
||||
"displayName": "Qwen Code Companion",
|
||||
"description": "Enable Qwen Code with direct access to your VS Code workspace.",
|
||||
"version": "0.0.3",
|
||||
"publisher": "qwenlm",
|
||||
"icon": "assets/icon.png",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/QwenLM/qwen-code.git",
|
||||
"directory": "packages/vscode-ide-companion"
|
||||
},
|
||||
"engines": {
|
||||
"vscode": "^1.101.0"
|
||||
},
|
||||
"license": "LICENSE",
|
||||
"preview": true,
|
||||
"categories": [
|
||||
"Other"
|
||||
"AI"
|
||||
],
|
||||
"keywords": [
|
||||
"qwen-code",
|
||||
"qwen code",
|
||||
"qwen",
|
||||
"qwen code",
|
||||
"cli",
|
||||
"ide integration",
|
||||
"ide companion"
|
||||
],
|
||||
"activationEvents": [
|
||||
"onStartupFinished"
|
||||
],
|
||||
"contributes": {
|
||||
"commands": [
|
||||
{
|
||||
"command": "qwen-code.runQwenCode",
|
||||
"title": "Qwen Code: Run"
|
||||
}
|
||||
]
|
||||
},
|
||||
"main": "./dist/extension.js",
|
||||
"scripts": {
|
||||
"vscode:prepublish": "npm run package",
|
||||
"vscode:prepublish": "npm run check-types && npm run lint && node esbuild.js --production",
|
||||
"build": "npm run compile",
|
||||
"compile": "npm run check-types && npm run lint && node esbuild.js",
|
||||
"watch": "npm-run-all -p watch:*",
|
||||
"watch:esbuild": "node esbuild.js --watch",
|
||||
"watch:tsc": "tsc --noEmit --watch --project tsconfig.json",
|
||||
"package": "npm run check-types && npm run lint && node esbuild.js --production",
|
||||
"package": "vsce package --no-dependencies",
|
||||
"check-types": "tsc --noEmit",
|
||||
"lint": "eslint src"
|
||||
"lint": "eslint src",
|
||||
"test": "vitest run",
|
||||
"test:ci": "vitest run --coverage"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/cors": "^2.8.19",
|
||||
@@ -34,7 +62,8 @@
|
||||
"esbuild": "^0.25.3",
|
||||
"eslint": "^9.25.1",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"typescript": "^5.8.3"
|
||||
"typescript": "^5.8.3",
|
||||
"vitest": "^3.2.4"
|
||||
},
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "^1.15.1",
|
||||
|
||||
@@ -5,10 +5,47 @@
|
||||
*/
|
||||
|
||||
import * as vscode from 'vscode';
|
||||
import { startIDEServer } from './ide-server';
|
||||
import { IDEServer } from './ide-server';
|
||||
import { createLogger } from './utils/logger';
|
||||
|
||||
let ideServer: IDEServer;
|
||||
let logger: vscode.OutputChannel;
|
||||
let log: (message: string) => void = () => {};
|
||||
|
||||
export async function activate(context: vscode.ExtensionContext) {
|
||||
startIDEServer(context);
|
||||
logger = vscode.window.createOutputChannel('Gemini CLI IDE Companion');
|
||||
log = createLogger(context, logger);
|
||||
log('Extension activated');
|
||||
ideServer = new IDEServer(log);
|
||||
try {
|
||||
await ideServer.start(context);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
log(`Failed to start IDE server: ${message}`);
|
||||
}
|
||||
|
||||
context.subscriptions.push(
|
||||
vscode.commands.registerCommand('gemini-cli.runGeminiCLI', () => {
|
||||
const geminiCmd = 'gemini';
|
||||
const terminal = vscode.window.createTerminal(`Gemini CLI`);
|
||||
terminal.show();
|
||||
terminal.sendText(geminiCmd);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function deactivate() {}
|
||||
export async function deactivate(): Promise<void> {
|
||||
log('Extension deactivated');
|
||||
try {
|
||||
if (ideServer) {
|
||||
await ideServer.stop();
|
||||
}
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
log(`Failed to stop IDE server during deactivation: ${message}`);
|
||||
} finally {
|
||||
if (logger) {
|
||||
logger.dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,102 +8,241 @@ import * as vscode from 'vscode';
|
||||
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
||||
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
||||
import express, { Request, Response } from 'express';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import {
|
||||
isInitializeRequest,
|
||||
type JSONRPCNotification,
|
||||
} from '@modelcontextprotocol/sdk/types.js';
|
||||
import { Server as HTTPServer } from 'node:http';
|
||||
import { RecentFilesManager } from './recent-files-manager.js';
|
||||
|
||||
export async function startIDEServer(_context: vscode.ExtensionContext) {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
const MCP_SESSION_ID_HEADER = 'mcp-session-id';
|
||||
const IDE_SERVER_PORT_ENV_VAR = 'GEMINI_CLI_IDE_SERVER_PORT';
|
||||
const MAX_SELECTED_TEXT_LENGTH = 16384; // 16 KiB limit
|
||||
|
||||
const mcpServer = createMcpServer();
|
||||
const transport = new StreamableHTTPServerTransport({
|
||||
sessionIdGenerator: undefined,
|
||||
enableJsonResponse: true,
|
||||
});
|
||||
function sendOpenFilesChangedNotification(
|
||||
transport: StreamableHTTPServerTransport,
|
||||
log: (message: string) => void,
|
||||
recentFilesManager: RecentFilesManager,
|
||||
) {
|
||||
const editor = vscode.window.activeTextEditor;
|
||||
const filePath =
|
||||
editor && editor.document.uri.scheme === 'file'
|
||||
? editor.document.uri.fsPath
|
||||
: '';
|
||||
const selection = editor?.selection;
|
||||
const cursor = selection
|
||||
? {
|
||||
// This value is a zero-based index, but the vscode IDE is one-based.
|
||||
line: selection.active.line + 1,
|
||||
character: selection.active.character,
|
||||
}
|
||||
: undefined;
|
||||
let selectedText = editor?.document.getText(selection) ?? undefined;
|
||||
if (selectedText && selectedText.length > MAX_SELECTED_TEXT_LENGTH) {
|
||||
selectedText =
|
||||
selectedText.substring(0, MAX_SELECTED_TEXT_LENGTH) + '... [TRUNCATED]';
|
||||
}
|
||||
const notification: JSONRPCNotification = {
|
||||
jsonrpc: '2.0',
|
||||
method: 'ide/openFilesChanged',
|
||||
params: {
|
||||
activeFile: filePath,
|
||||
recentOpenFiles: recentFilesManager.recentFiles.filter(
|
||||
(file) => file.filePath !== filePath,
|
||||
),
|
||||
cursor,
|
||||
selectedText,
|
||||
},
|
||||
};
|
||||
log(
|
||||
`Sending active file changed notification: ${JSON.stringify(
|
||||
notification,
|
||||
null,
|
||||
2,
|
||||
)}`,
|
||||
);
|
||||
transport.send(notification);
|
||||
}
|
||||
|
||||
mcpServer.connect(transport);
|
||||
export class IDEServer {
|
||||
private server: HTTPServer | undefined;
|
||||
private context: vscode.ExtensionContext | undefined;
|
||||
private log: (message: string) => void;
|
||||
|
||||
app.post('/mcp', async (req: Request, res: Response) => {
|
||||
console.log('Received MCP request:', req.body);
|
||||
try {
|
||||
await transport.handleRequest(req, res, req.body);
|
||||
} catch (error) {
|
||||
console.error('Error handling MCP request:', error);
|
||||
if (!res.headersSent) {
|
||||
res.status(500).json({
|
||||
constructor(log: (message: string) => void) {
|
||||
this.log = log;
|
||||
}
|
||||
|
||||
async start(context: vscode.ExtensionContext) {
|
||||
this.context = context;
|
||||
const transports: { [sessionId: string]: StreamableHTTPServerTransport } =
|
||||
{};
|
||||
const sessionsWithInitialNotification = new Set<string>();
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
const mcpServer = createMcpServer();
|
||||
|
||||
const recentFilesManager = new RecentFilesManager(context);
|
||||
const onDidChangeSubscription = recentFilesManager.onDidChange(() => {
|
||||
for (const transport of Object.values(transports)) {
|
||||
sendOpenFilesChangedNotification(
|
||||
transport,
|
||||
this.log.bind(this),
|
||||
recentFilesManager,
|
||||
);
|
||||
}
|
||||
});
|
||||
context.subscriptions.push(onDidChangeSubscription);
|
||||
|
||||
app.post('/mcp', async (req: Request, res: Response) => {
|
||||
const sessionId = req.headers[MCP_SESSION_ID_HEADER] as
|
||||
| string
|
||||
| undefined;
|
||||
let transport: StreamableHTTPServerTransport;
|
||||
|
||||
if (sessionId && transports[sessionId]) {
|
||||
transport = transports[sessionId];
|
||||
} else if (!sessionId && isInitializeRequest(req.body)) {
|
||||
transport = new StreamableHTTPServerTransport({
|
||||
sessionIdGenerator: () => randomUUID(),
|
||||
onsessioninitialized: (newSessionId) => {
|
||||
this.log(`New session initialized: ${newSessionId}`);
|
||||
transports[newSessionId] = transport;
|
||||
},
|
||||
});
|
||||
|
||||
const keepAlive = setInterval(() => {
|
||||
try {
|
||||
transport.send({ jsonrpc: '2.0', method: 'ping' });
|
||||
} catch (e) {
|
||||
this.log(
|
||||
'Failed to send keep-alive ping, cleaning up interval.' + e,
|
||||
);
|
||||
clearInterval(keepAlive);
|
||||
}
|
||||
}, 60000); // 60 sec
|
||||
|
||||
transport.onclose = () => {
|
||||
clearInterval(keepAlive);
|
||||
if (transport.sessionId) {
|
||||
this.log(`Session closed: ${transport.sessionId}`);
|
||||
sessionsWithInitialNotification.delete(transport.sessionId);
|
||||
delete transports[transport.sessionId];
|
||||
}
|
||||
};
|
||||
mcpServer.connect(transport);
|
||||
} else {
|
||||
this.log(
|
||||
'Bad Request: No valid session ID provided for non-initialize request.',
|
||||
);
|
||||
res.status(400).json({
|
||||
jsonrpc: '2.0',
|
||||
error: {
|
||||
code: -32603,
|
||||
message: 'Internal server error',
|
||||
code: -32000,
|
||||
message:
|
||||
'Bad Request: No valid session ID provided for non-initialize request.',
|
||||
},
|
||||
id: null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Handle GET requests for SSE streams
|
||||
app.get('/mcp', async (req: Request, res: Response) => {
|
||||
res.status(405).set('Allow', 'POST').send('Method Not Allowed');
|
||||
});
|
||||
try {
|
||||
await transport.handleRequest(req, res, req.body);
|
||||
} catch (error) {
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : 'Unknown error';
|
||||
this.log(`Error handling MCP request: ${errorMessage}`);
|
||||
if (!res.headersSent) {
|
||||
res.status(500).json({
|
||||
jsonrpc: '2.0' as const,
|
||||
error: {
|
||||
code: -32603,
|
||||
message: 'Internal server error',
|
||||
},
|
||||
id: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Start the server
|
||||
// TODO(#3918): Generate dynamically and write to env variable
|
||||
const PORT = 3000;
|
||||
app.listen(PORT, (error) => {
|
||||
if (error) {
|
||||
console.error('Failed to start server:', error);
|
||||
vscode.window.showErrorMessage(
|
||||
`Companion server failed to start on port ${PORT}: ${error.message}`,
|
||||
);
|
||||
const handleSessionRequest = async (req: Request, res: Response) => {
|
||||
const sessionId = req.headers[MCP_SESSION_ID_HEADER] as
|
||||
| string
|
||||
| undefined;
|
||||
if (!sessionId || !transports[sessionId]) {
|
||||
this.log('Invalid or missing session ID');
|
||||
res.status(400).send('Invalid or missing session ID');
|
||||
return;
|
||||
}
|
||||
|
||||
const transport = transports[sessionId];
|
||||
try {
|
||||
await transport.handleRequest(req, res);
|
||||
} catch (error) {
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : 'Unknown error';
|
||||
this.log(`Error handling session request: ${errorMessage}`);
|
||||
if (!res.headersSent) {
|
||||
res.status(400).send('Bad Request');
|
||||
}
|
||||
}
|
||||
|
||||
if (!sessionsWithInitialNotification.has(sessionId)) {
|
||||
sendOpenFilesChangedNotification(
|
||||
transport,
|
||||
this.log.bind(this),
|
||||
recentFilesManager,
|
||||
);
|
||||
sessionsWithInitialNotification.add(sessionId);
|
||||
}
|
||||
};
|
||||
|
||||
app.get('/mcp', handleSessionRequest);
|
||||
|
||||
this.server = app.listen(0, () => {
|
||||
const address = (this.server as HTTPServer).address();
|
||||
if (address && typeof address !== 'string') {
|
||||
const port = address.port;
|
||||
context.environmentVariableCollection.replace(
|
||||
IDE_SERVER_PORT_ENV_VAR,
|
||||
port.toString(),
|
||||
);
|
||||
this.log(`IDE server listening on port ${port}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
if (this.server) {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
this.server!.close((err?: Error) => {
|
||||
if (err) {
|
||||
this.log(`Error shutting down IDE server: ${err.message}`);
|
||||
return reject(err);
|
||||
}
|
||||
this.log(`IDE server shut down`);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
this.server = undefined;
|
||||
}
|
||||
console.log(`MCP Streamable HTTP Server listening on port ${PORT}`);
|
||||
});
|
||||
|
||||
if (this.context) {
|
||||
this.context.environmentVariableCollection.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const createMcpServer = () => {
|
||||
const server = new McpServer({
|
||||
name: 'vscode-ide-server',
|
||||
version: '1.0.0',
|
||||
});
|
||||
server.registerTool(
|
||||
'getActiveFile',
|
||||
const server = new McpServer(
|
||||
{
|
||||
description:
|
||||
'(IDE Tool) Get the path of the file currently active in VS Code.',
|
||||
inputSchema: {},
|
||||
},
|
||||
async () => {
|
||||
try {
|
||||
const activeEditor = vscode.window.activeTextEditor;
|
||||
const filePath = activeEditor
|
||||
? activeEditor.document.uri.fsPath
|
||||
: undefined;
|
||||
if (filePath) {
|
||||
return {
|
||||
content: [{ type: 'text', text: `Active file: ${filePath}` }],
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: 'No file is currently active in the editor.',
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `Failed to get active file: ${
|
||||
(error as Error).message || 'Unknown error'
|
||||
}`,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
name: 'gemini-cli-companion-mcp-server',
|
||||
version: '1.0.0',
|
||||
},
|
||||
{ capabilities: { logging: {} } },
|
||||
);
|
||||
return server;
|
||||
};
|
||||
|
||||
278
packages/vscode-ide-companion/src/recent-files-manager.test.ts
Normal file
278
packages/vscode-ide-companion/src/recent-files-manager.test.ts
Normal file
@@ -0,0 +1,278 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import * as vscode from 'vscode';
|
||||
import {
|
||||
RecentFilesManager,
|
||||
MAX_FILES,
|
||||
MAX_FILE_AGE_MINUTES,
|
||||
} from './recent-files-manager.js';
|
||||
|
||||
vi.mock('vscode', () => ({
|
||||
EventEmitter: vi.fn(() => {
|
||||
const listeners: Array<(e: void) => unknown> = [];
|
||||
return {
|
||||
event: vi.fn((listener) => {
|
||||
listeners.push(listener);
|
||||
return { dispose: vi.fn() };
|
||||
}),
|
||||
fire: vi.fn(() => {
|
||||
listeners.forEach((listener) => listener(undefined));
|
||||
}),
|
||||
dispose: vi.fn(),
|
||||
};
|
||||
}),
|
||||
window: {
|
||||
onDidChangeActiveTextEditor: vi.fn(),
|
||||
onDidChangeTextEditorSelection: vi.fn(),
|
||||
},
|
||||
workspace: {
|
||||
onDidDeleteFiles: vi.fn(),
|
||||
onDidCloseTextDocument: vi.fn(),
|
||||
onDidRenameFiles: vi.fn(),
|
||||
},
|
||||
Uri: {
|
||||
file: (path: string) => ({
|
||||
fsPath: path,
|
||||
scheme: 'file',
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('RecentFilesManager', () => {
|
||||
let context: vscode.ExtensionContext;
|
||||
let onDidChangeActiveTextEditorListener: (
|
||||
editor: vscode.TextEditor | undefined,
|
||||
) => void;
|
||||
let onDidDeleteFilesListener: (e: vscode.FileDeleteEvent) => void;
|
||||
let onDidCloseTextDocumentListener: (doc: vscode.TextDocument) => void;
|
||||
let onDidRenameFilesListener: (e: vscode.FileRenameEvent) => void;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
vi.mocked(vscode.window.onDidChangeActiveTextEditor).mockImplementation(
|
||||
(listener) => {
|
||||
onDidChangeActiveTextEditorListener = listener;
|
||||
return { dispose: vi.fn() };
|
||||
},
|
||||
);
|
||||
vi.mocked(vscode.workspace.onDidDeleteFiles).mockImplementation(
|
||||
(listener) => {
|
||||
onDidDeleteFilesListener = listener;
|
||||
return { dispose: vi.fn() };
|
||||
},
|
||||
);
|
||||
vi.mocked(vscode.workspace.onDidCloseTextDocument).mockImplementation(
|
||||
(listener) => {
|
||||
onDidCloseTextDocumentListener = listener;
|
||||
return { dispose: vi.fn() };
|
||||
},
|
||||
);
|
||||
vi.mocked(vscode.workspace.onDidRenameFiles).mockImplementation(
|
||||
(listener) => {
|
||||
onDidRenameFilesListener = listener;
|
||||
return { dispose: vi.fn() };
|
||||
},
|
||||
);
|
||||
|
||||
context = {
|
||||
subscriptions: [],
|
||||
} as unknown as vscode.ExtensionContext;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
const getUri = (path: string) =>
|
||||
vscode.Uri.file(path) as unknown as vscode.Uri;
|
||||
|
||||
it('adds a file to the list', async () => {
|
||||
const manager = new RecentFilesManager(context);
|
||||
const uri = getUri('/test/file1.txt');
|
||||
manager.add(uri);
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
expect(manager.recentFiles).toHaveLength(1);
|
||||
expect(manager.recentFiles[0].filePath).toBe('/test/file1.txt');
|
||||
});
|
||||
|
||||
it('moves an existing file to the top', async () => {
|
||||
const manager = new RecentFilesManager(context);
|
||||
const uri1 = getUri('/test/file1.txt');
|
||||
const uri2 = getUri('/test/file2.txt');
|
||||
manager.add(uri1);
|
||||
manager.add(uri2);
|
||||
manager.add(uri1);
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
expect(manager.recentFiles).toHaveLength(2);
|
||||
expect(manager.recentFiles[0].filePath).toBe('/test/file1.txt');
|
||||
});
|
||||
|
||||
it('does not exceed the max number of files', async () => {
|
||||
const manager = new RecentFilesManager(context);
|
||||
for (let i = 0; i < MAX_FILES + 5; i++) {
|
||||
const uri = getUri(`/test/file${i}.txt`);
|
||||
manager.add(uri);
|
||||
}
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
expect(manager.recentFiles).toHaveLength(MAX_FILES);
|
||||
expect(manager.recentFiles[0].filePath).toBe(
|
||||
`/test/file${MAX_FILES + 4}.txt`,
|
||||
);
|
||||
expect(manager.recentFiles[MAX_FILES - 1].filePath).toBe(`/test/file5.txt`);
|
||||
});
|
||||
|
||||
it('fires onDidChange when a file is added', async () => {
|
||||
const manager = new RecentFilesManager(context);
|
||||
const onDidChangeSpy = vi.fn();
|
||||
manager.onDidChange(onDidChangeSpy);
|
||||
|
||||
const uri = getUri('/test/file1.txt');
|
||||
manager.add(uri);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
expect(onDidChangeSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('removes a file when it is closed', async () => {
|
||||
const manager = new RecentFilesManager(context);
|
||||
const uri = getUri('/test/file1.txt');
|
||||
manager.add(uri);
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
expect(manager.recentFiles).toHaveLength(1);
|
||||
|
||||
onDidCloseTextDocumentListener({ uri } as vscode.TextDocument);
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
|
||||
expect(manager.recentFiles).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('fires onDidChange when a file is removed', async () => {
|
||||
const manager = new RecentFilesManager(context);
|
||||
const uri = getUri('/test/file1.txt');
|
||||
manager.add(uri);
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
|
||||
const onDidChangeSpy = vi.fn();
|
||||
manager.onDidChange(onDidChangeSpy);
|
||||
|
||||
onDidCloseTextDocumentListener({ uri } as vscode.TextDocument);
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
|
||||
expect(onDidChangeSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('removes a file when it is deleted', async () => {
|
||||
const manager = new RecentFilesManager(context);
|
||||
const uri1 = getUri('/test/file1.txt');
|
||||
const uri2 = getUri('/test/file2.txt');
|
||||
manager.add(uri1);
|
||||
manager.add(uri2);
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
expect(manager.recentFiles).toHaveLength(2);
|
||||
|
||||
onDidDeleteFilesListener({ files: [uri1] });
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
|
||||
expect(manager.recentFiles).toHaveLength(1);
|
||||
expect(manager.recentFiles[0].filePath).toBe('/test/file2.txt');
|
||||
});
|
||||
|
||||
it('fires onDidChange when a file is deleted', async () => {
|
||||
const manager = new RecentFilesManager(context);
|
||||
const uri = getUri('/test/file1.txt');
|
||||
manager.add(uri);
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
|
||||
const onDidChangeSpy = vi.fn();
|
||||
manager.onDidChange(onDidChangeSpy);
|
||||
|
||||
onDidDeleteFilesListener({ files: [uri] });
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
|
||||
expect(onDidChangeSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('removes multiple files when they are deleted', async () => {
|
||||
const manager = new RecentFilesManager(context);
|
||||
const uri1 = getUri('/test/file1.txt');
|
||||
const uri2 = getUri('/test/file2.txt');
|
||||
const uri3 = getUri('/test/file3.txt');
|
||||
manager.add(uri1);
|
||||
manager.add(uri2);
|
||||
manager.add(uri3);
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
expect(manager.recentFiles).toHaveLength(3);
|
||||
|
||||
onDidDeleteFilesListener({ files: [uri1, uri3] });
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
|
||||
expect(manager.recentFiles).toHaveLength(1);
|
||||
expect(manager.recentFiles[0].filePath).toBe('/test/file2.txt');
|
||||
});
|
||||
|
||||
it('prunes files older than the max age', () => {
|
||||
const manager = new RecentFilesManager(context);
|
||||
const uri1 = getUri('/test/file1.txt');
|
||||
manager.add(uri1);
|
||||
|
||||
// Advance time by more than the max age
|
||||
const twoMinutesMs = (MAX_FILE_AGE_MINUTES + 1) * 60 * 1000;
|
||||
vi.advanceTimersByTime(twoMinutesMs);
|
||||
|
||||
const uri2 = getUri('/test/file2.txt');
|
||||
manager.add(uri2);
|
||||
|
||||
expect(manager.recentFiles).toHaveLength(1);
|
||||
expect(manager.recentFiles[0].filePath).toBe('/test/file2.txt');
|
||||
});
|
||||
|
||||
it('fires onDidChange only once when adding an existing file', async () => {
|
||||
const manager = new RecentFilesManager(context);
|
||||
const uri = getUri('/test/file1.txt');
|
||||
manager.add(uri);
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
|
||||
const onDidChangeSpy = vi.fn();
|
||||
manager.onDidChange(onDidChangeSpy);
|
||||
|
||||
manager.add(uri);
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
expect(onDidChangeSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('updates the file when it is renamed', async () => {
|
||||
const manager = new RecentFilesManager(context);
|
||||
const oldUri = getUri('/test/file1.txt');
|
||||
const newUri = getUri('/test/file2.txt');
|
||||
manager.add(oldUri);
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
expect(manager.recentFiles).toHaveLength(1);
|
||||
expect(manager.recentFiles[0].filePath).toBe('/test/file1.txt');
|
||||
|
||||
onDidRenameFilesListener({ files: [{ oldUri, newUri }] });
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
|
||||
expect(manager.recentFiles).toHaveLength(1);
|
||||
expect(manager.recentFiles[0].filePath).toBe('/test/file2.txt');
|
||||
});
|
||||
|
||||
it('adds a file when the active editor changes', async () => {
|
||||
const manager = new RecentFilesManager(context);
|
||||
const uri = getUri('/test/file1.txt');
|
||||
|
||||
onDidChangeActiveTextEditorListener({
|
||||
document: { uri },
|
||||
} as vscode.TextEditor);
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
|
||||
expect(manager.recentFiles).toHaveLength(1);
|
||||
expect(manager.recentFiles[0].filePath).toBe('/test/file1.txt');
|
||||
});
|
||||
});
|
||||
111
packages/vscode-ide-companion/src/recent-files-manager.ts
Normal file
111
packages/vscode-ide-companion/src/recent-files-manager.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import * as vscode from 'vscode';
|
||||
|
||||
export const MAX_FILES = 10;
|
||||
export const MAX_FILE_AGE_MINUTES = 5;
|
||||
|
||||
interface RecentFile {
|
||||
uri: vscode.Uri;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps track of the 10 most recently-opened files
|
||||
* opened less than 5 min ago. If a file is closed or deleted,
|
||||
* it will be removed. If the max length is reached, older files will get removed first.
|
||||
*/
|
||||
export class RecentFilesManager {
|
||||
private readonly files: RecentFile[] = [];
|
||||
private readonly onDidChangeEmitter = new vscode.EventEmitter<void>();
|
||||
readonly onDidChange = this.onDidChangeEmitter.event;
|
||||
private debounceTimer: NodeJS.Timeout | undefined;
|
||||
|
||||
constructor(private readonly context: vscode.ExtensionContext) {
|
||||
const editorWatcher = vscode.window.onDidChangeActiveTextEditor(
|
||||
(editor) => {
|
||||
if (editor) {
|
||||
this.add(editor.document.uri);
|
||||
}
|
||||
},
|
||||
);
|
||||
const deleteWatcher = vscode.workspace.onDidDeleteFiles((event) => {
|
||||
for (const uri of event.files) {
|
||||
this.remove(uri);
|
||||
}
|
||||
});
|
||||
const closeWatcher = vscode.workspace.onDidCloseTextDocument((document) => {
|
||||
this.remove(document.uri);
|
||||
});
|
||||
const renameWatcher = vscode.workspace.onDidRenameFiles((event) => {
|
||||
for (const { oldUri, newUri } of event.files) {
|
||||
this.remove(oldUri, false);
|
||||
this.add(newUri);
|
||||
}
|
||||
});
|
||||
|
||||
const selectionWatcher = vscode.window.onDidChangeTextEditorSelection(
|
||||
() => {
|
||||
this.fireWithDebounce();
|
||||
},
|
||||
);
|
||||
|
||||
context.subscriptions.push(
|
||||
editorWatcher,
|
||||
deleteWatcher,
|
||||
closeWatcher,
|
||||
renameWatcher,
|
||||
selectionWatcher,
|
||||
);
|
||||
}
|
||||
|
||||
private fireWithDebounce() {
|
||||
if (this.debounceTimer) {
|
||||
clearTimeout(this.debounceTimer);
|
||||
}
|
||||
this.debounceTimer = setTimeout(() => {
|
||||
this.onDidChangeEmitter.fire();
|
||||
}, 50); // 50ms
|
||||
}
|
||||
|
||||
private remove(uri: vscode.Uri, fireEvent = true) {
|
||||
const index = this.files.findIndex(
|
||||
(file) => file.uri.fsPath === uri.fsPath,
|
||||
);
|
||||
if (index !== -1) {
|
||||
this.files.splice(index, 1);
|
||||
if (fireEvent) {
|
||||
this.fireWithDebounce();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
add(uri: vscode.Uri) {
|
||||
if (uri.scheme !== 'file') {
|
||||
return;
|
||||
}
|
||||
|
||||
this.remove(uri, false);
|
||||
this.files.unshift({ uri, timestamp: Date.now() });
|
||||
|
||||
if (this.files.length > MAX_FILES) {
|
||||
this.files.pop();
|
||||
}
|
||||
this.fireWithDebounce();
|
||||
}
|
||||
|
||||
get recentFiles(): Array<{ filePath: string; timestamp: number }> {
|
||||
const now = Date.now();
|
||||
const maxAgeInMs = MAX_FILE_AGE_MINUTES * 60 * 1000;
|
||||
return this.files
|
||||
.filter((file) => now - file.timestamp < maxAgeInMs)
|
||||
.map((file) => ({
|
||||
filePath: file.uri.fsPath,
|
||||
timestamp: file.timestamp,
|
||||
}));
|
||||
}
|
||||
}
|
||||
18
packages/vscode-ide-companion/src/utils/logger.ts
Normal file
18
packages/vscode-ide-companion/src/utils/logger.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import * as vscode from 'vscode';
|
||||
|
||||
export function createLogger(
|
||||
context: vscode.ExtensionContext,
|
||||
logger: vscode.OutputChannel,
|
||||
) {
|
||||
return (message: string) => {
|
||||
if (context.extensionMode === vscode.ExtensionMode.Development) {
|
||||
logger.appendLine(message);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "Node16",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2022", "dom"],
|
||||
"sourceMap": true,
|
||||
|
||||
Reference in New Issue
Block a user