ADAPT-Chase commited on
Commit
ba88683
·
verified ·
1 Parent(s): 1c71d54

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. projects/ui/DeepCode/.github/dependabot.yml +11 -0
  2. projects/ui/DeepCode/.github/pull_request_template.md +32 -0
  3. projects/ui/qwen-code/packages/core/src/utils/filesearch/result-cache.ts +67 -0
  4. projects/ui/qwen-code/packages/test-utils/src/file-system-test-helpers.ts +98 -0
  5. projects/ui/qwen-code/packages/test-utils/src/index.ts +7 -0
  6. projects/ui/qwen-code/packages/vscode-ide-companion/.vscode/launch.json +13 -0
  7. projects/ui/qwen-code/packages/vscode-ide-companion/.vscode/tasks.json +18 -0
  8. projects/ui/qwen-code/packages/vscode-ide-companion/assets/icon.png +0 -0
  9. projects/ui/qwen-code/packages/vscode-ide-companion/scripts/generate-notices.js +158 -0
  10. projects/ui/qwen-code/packages/vscode-ide-companion/src/diff-manager.ts +267 -0
  11. projects/ui/qwen-code/packages/vscode-ide-companion/src/extension-multi-folder.test.ts +211 -0
  12. projects/ui/qwen-code/packages/vscode-ide-companion/src/extension.test.ts +108 -0
  13. projects/ui/qwen-code/packages/vscode-ide-companion/src/extension.ts +145 -0
  14. projects/ui/qwen-code/packages/vscode-ide-companion/src/ide-server.ts +301 -0
  15. projects/ui/qwen-code/packages/vscode-ide-companion/src/open-files-manager.test.ts +440 -0
  16. projects/ui/qwen-code/packages/vscode-ide-companion/src/open-files-manager.ts +178 -0
  17. projects/ui/qwen-code/packages/vscode-ide-companion/src/utils/logger.ts +18 -0
  18. projects/ui/qwen-code/scripts/tests/get-release-version.test.js +110 -0
  19. projects/ui/qwen-code/scripts/tests/test-setup.ts +12 -0
  20. projects/ui/qwen-code/scripts/tests/vitest.config.ts +20 -0
projects/ui/DeepCode/.github/dependabot.yml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # To get started with Dependabot version updates, you'll need to specify which
2
+ # package ecosystems to update and where the package manifests are located.
3
+ # Please see the documentation for all configuration options:
4
+ # https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
5
+
6
+ version: 2
7
+ updates:
8
+ - package-ecosystem: "pip" # See documentation for possible values
9
+ directory: "/" # Location of package manifests
10
+ schedule:
11
+ interval: "weekly"
projects/ui/DeepCode/.github/pull_request_template.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--
2
+ Thanks for contributing to DeepCode!
3
+
4
+ Please ensure your pull request is ready for review before submitting.
5
+
6
+ About this template
7
+
8
+ This template helps contributors provide a clear and concise description of their changes. Feel free to adjust it as needed.
9
+ -->
10
+
11
+ ## Description
12
+
13
+ [Briefly describe the changes made in this pull request.]
14
+
15
+ ## Related Issues
16
+
17
+ [Reference any related issues or tasks addressed by this pull request.]
18
+
19
+ ## Changes Made
20
+
21
+ [List the specific changes made in this pull request.]
22
+
23
+ ## Checklist
24
+
25
+ - [ ] Changes tested locally
26
+ - [ ] Code reviewed
27
+ - [ ] Documentation updated (if necessary)
28
+ - [ ] Unit tests added (if applicable)
29
+
30
+ ## Additional Notes
31
+
32
+ [Add any additional notes or context for the reviewer(s).]
projects/ui/qwen-code/packages/core/src/utils/filesearch/result-cache.ts ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ /**
8
+ * Implements an in-memory cache for file search results.
9
+ * This cache optimizes subsequent searches by leveraging previously computed results.
10
+ */
11
+ export class ResultCache {
12
+ private readonly cache: Map<string, string[]>;
13
+ private hits = 0;
14
+ private misses = 0;
15
+
16
+ constructor(private readonly allFiles: string[]) {
17
+ this.cache = new Map();
18
+ }
19
+
20
+ /**
21
+ * Retrieves cached search results for a given query, or provides a base set
22
+ * of files to search from.
23
+ * @param query The search query pattern.
24
+ * @returns An object containing the files to search and a boolean indicating
25
+ * if the result is an exact cache hit.
26
+ */
27
+ async get(
28
+ query: string,
29
+ ): Promise<{ files: string[]; isExactMatch: boolean }> {
30
+ const isCacheHit = this.cache.has(query);
31
+
32
+ if (isCacheHit) {
33
+ this.hits++;
34
+ return { files: this.cache.get(query)!, isExactMatch: true };
35
+ }
36
+
37
+ this.misses++;
38
+
39
+ // This is the core optimization of the memory cache.
40
+ // If a user first searches for "foo", and then for "foobar",
41
+ // we don't need to search through all files again. We can start
42
+ // from the results of the "foo" search.
43
+ // This finds the most specific, already-cached query that is a prefix
44
+ // of the current query.
45
+ let bestBaseQuery = '';
46
+ for (const key of this.cache?.keys?.() ?? []) {
47
+ if (query.startsWith(key) && key.length > bestBaseQuery.length) {
48
+ bestBaseQuery = key;
49
+ }
50
+ }
51
+
52
+ const filesToSearch = bestBaseQuery
53
+ ? this.cache.get(bestBaseQuery)!
54
+ : this.allFiles;
55
+
56
+ return { files: filesToSearch, isExactMatch: false };
57
+ }
58
+
59
+ /**
60
+ * Stores search results in the cache.
61
+ * @param query The search query pattern.
62
+ * @param results The matching file paths to cache.
63
+ */
64
+ set(query: string, results: string[]): void {
65
+ this.cache.set(query, results);
66
+ }
67
+ }
projects/ui/qwen-code/packages/test-utils/src/file-system-test-helpers.ts ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import * as fs from 'fs/promises';
8
+ import * as path from 'path';
9
+ import * as os from 'os';
10
+
11
+ /**
12
+ * Defines the structure of a virtual file system to be created for testing.
13
+ * Keys are file or directory names, and values can be:
14
+ * - A string: The content of a file.
15
+ * - A `FileSystemStructure` object: Represents a subdirectory with its own structure.
16
+ * - An array of strings or `FileSystemStructure` objects: Represents a directory
17
+ * where strings are empty files and objects are subdirectories.
18
+ *
19
+ * @example
20
+ * // Example 1: Simple files and directories
21
+ * const structure1 = {
22
+ * 'file1.txt': 'Hello, world!',
23
+ * 'empty-dir': [],
24
+ * 'src': {
25
+ * 'main.js': '// Main application file',
26
+ * 'utils.ts': '// Utility functions',
27
+ * },
28
+ * };
29
+ *
30
+ * @example
31
+ * // Example 2: Nested directories and empty files within an array
32
+ * const structure2 = {
33
+ * 'config.json': '{ "port": 3000 }',
34
+ * 'data': [
35
+ * 'users.csv',
36
+ * 'products.json',
37
+ * {
38
+ * 'logs': [
39
+ * 'error.log',
40
+ * 'access.log',
41
+ * ],
42
+ * },
43
+ * ],
44
+ * };
45
+ */
46
+ export type FileSystemStructure = {
47
+ [name: string]:
48
+ | string
49
+ | FileSystemStructure
50
+ | Array<string | FileSystemStructure>;
51
+ };
52
+
53
+ /**
54
+ * Recursively creates files and directories based on the provided `FileSystemStructure`.
55
+ * @param dir The base directory where the structure will be created.
56
+ * @param structure The `FileSystemStructure` defining the files and directories.
57
+ */
58
+ async function create(dir: string, structure: FileSystemStructure) {
59
+ for (const [name, content] of Object.entries(structure)) {
60
+ const newPath = path.join(dir, name);
61
+ if (typeof content === 'string') {
62
+ await fs.writeFile(newPath, content);
63
+ } else if (Array.isArray(content)) {
64
+ await fs.mkdir(newPath, { recursive: true });
65
+ for (const item of content) {
66
+ if (typeof item === 'string') {
67
+ await fs.writeFile(path.join(newPath, item), '');
68
+ } else {
69
+ await create(newPath, item as FileSystemStructure);
70
+ }
71
+ }
72
+ } else if (typeof content === 'object' && content !== null) {
73
+ await fs.mkdir(newPath, { recursive: true });
74
+ await create(newPath, content as FileSystemStructure);
75
+ }
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Creates a temporary directory and populates it with a given file system structure.
81
+ * @param structure The `FileSystemStructure` to create within the temporary directory.
82
+ * @returns A promise that resolves to the absolute path of the created temporary directory.
83
+ */
84
+ export async function createTmpDir(
85
+ structure: FileSystemStructure,
86
+ ): Promise<string> {
87
+ const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'gemini-cli-test-'));
88
+ await create(tmpDir, structure);
89
+ return tmpDir;
90
+ }
91
+
92
+ /**
93
+ * Cleans up (deletes) a temporary directory and its contents.
94
+ * @param dir The absolute path to the temporary directory to clean up.
95
+ */
96
+ export async function cleanupTmpDir(dir: string) {
97
+ await fs.rm(dir, { recursive: true, force: true });
98
+ }
projects/ui/qwen-code/packages/test-utils/src/index.ts ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ export * from './file-system-test-helpers.js';
projects/ui/qwen-code/packages/vscode-ide-companion/.vscode/launch.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": "0.2.0",
3
+ "configurations": [
4
+ {
5
+ "name": "Run Extension",
6
+ "type": "extensionHost",
7
+ "request": "launch",
8
+ "args": ["--extensionDevelopmentPath=${workspaceFolder}"],
9
+ "outFiles": ["${workspaceFolder}/out/**/*.js"],
10
+ "preLaunchTask": "${defaultBuildTask}"
11
+ }
12
+ ]
13
+ }
projects/ui/qwen-code/packages/vscode-ide-companion/.vscode/tasks.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": "2.0.0",
3
+ "tasks": [
4
+ {
5
+ "type": "npm",
6
+ "script": "watch",
7
+ "problemMatcher": "$tsc-watch",
8
+ "isBackground": true,
9
+ "presentation": {
10
+ "reveal": "never"
11
+ },
12
+ "group": {
13
+ "kind": "build",
14
+ "isDefault": true
15
+ }
16
+ }
17
+ ]
18
+ }
projects/ui/qwen-code/packages/vscode-ide-companion/assets/icon.png ADDED
projects/ui/qwen-code/packages/vscode-ide-companion/scripts/generate-notices.js ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import fs from 'fs/promises';
8
+ import path from 'path';
9
+ import { fileURLToPath } from 'url';
10
+
11
+ const projectRoot = path.resolve(
12
+ path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..'),
13
+ );
14
+ const packagePath = path.join(projectRoot, 'packages', 'vscode-ide-companion');
15
+ const noticeFilePath = path.join(packagePath, 'NOTICES.txt');
16
+
17
+ async function getDependencyLicense(depName, depVersion) {
18
+ let depPackageJsonPath;
19
+ let licenseContent = 'License text not found.';
20
+ let repositoryUrl = 'No repository found';
21
+
22
+ try {
23
+ depPackageJsonPath = path.join(
24
+ projectRoot,
25
+ 'node_modules',
26
+ depName,
27
+ 'package.json',
28
+ );
29
+ if (!(await fs.stat(depPackageJsonPath).catch(() => false))) {
30
+ depPackageJsonPath = path.join(
31
+ packagePath,
32
+ 'node_modules',
33
+ depName,
34
+ 'package.json',
35
+ );
36
+ }
37
+
38
+ const depPackageJsonContent = await fs.readFile(
39
+ depPackageJsonPath,
40
+ 'utf-8',
41
+ );
42
+ const depPackageJson = JSON.parse(depPackageJsonContent);
43
+
44
+ repositoryUrl = depPackageJson.repository?.url || repositoryUrl;
45
+
46
+ const packageDir = path.dirname(depPackageJsonPath);
47
+ const licenseFileCandidates = [
48
+ depPackageJson.licenseFile,
49
+ 'LICENSE',
50
+ 'LICENSE.md',
51
+ 'LICENSE.txt',
52
+ 'LICENSE-MIT.txt',
53
+ ].filter(Boolean);
54
+
55
+ let licenseFile;
56
+ for (const candidate of licenseFileCandidates) {
57
+ const potentialFile = path.join(packageDir, candidate);
58
+ if (await fs.stat(potentialFile).catch(() => false)) {
59
+ licenseFile = potentialFile;
60
+ break;
61
+ }
62
+ }
63
+
64
+ if (licenseFile) {
65
+ try {
66
+ licenseContent = await fs.readFile(licenseFile, 'utf-8');
67
+ } catch (e) {
68
+ console.warn(
69
+ `Warning: Failed to read license file for ${depName}: ${e.message}`,
70
+ );
71
+ }
72
+ } else {
73
+ console.warn(`Warning: Could not find license file for ${depName}`);
74
+ }
75
+ } catch (e) {
76
+ console.warn(
77
+ `Warning: Could not find package.json for ${depName}: ${e.message}`,
78
+ );
79
+ }
80
+
81
+ return {
82
+ name: depName,
83
+ version: depVersion,
84
+ repository: repositoryUrl,
85
+ license: licenseContent,
86
+ };
87
+ }
88
+
89
+ function collectDependencies(packageName, packageLock, dependenciesMap) {
90
+ if (dependenciesMap.has(packageName)) {
91
+ return;
92
+ }
93
+
94
+ const packageInfo = packageLock.packages[`node_modules/${packageName}`];
95
+ if (!packageInfo) {
96
+ console.warn(
97
+ `Warning: Could not find package info for ${packageName} in package-lock.json.`,
98
+ );
99
+ return;
100
+ }
101
+
102
+ dependenciesMap.set(packageName, packageInfo.version);
103
+
104
+ if (packageInfo.dependencies) {
105
+ for (const depName of Object.keys(packageInfo.dependencies)) {
106
+ collectDependencies(depName, packageLock, dependenciesMap);
107
+ }
108
+ }
109
+ }
110
+
111
+ async function main() {
112
+ try {
113
+ const packageJsonPath = path.join(packagePath, 'package.json');
114
+ const packageJsonContent = await fs.readFile(packageJsonPath, 'utf-8');
115
+ const packageJson = JSON.parse(packageJsonContent);
116
+
117
+ const packageLockJsonPath = path.join(projectRoot, 'package-lock.json');
118
+ const packageLockJsonContent = await fs.readFile(
119
+ packageLockJsonPath,
120
+ 'utf-8',
121
+ );
122
+ const packageLockJson = JSON.parse(packageLockJsonContent);
123
+
124
+ const allDependencies = new Map();
125
+ const directDependencies = Object.keys(packageJson.dependencies);
126
+
127
+ for (const depName of directDependencies) {
128
+ collectDependencies(depName, packageLockJson, allDependencies);
129
+ }
130
+
131
+ const dependencyEntries = Array.from(allDependencies.entries());
132
+
133
+ const licensePromises = dependencyEntries.map(([depName, depVersion]) =>
134
+ getDependencyLicense(depName, depVersion),
135
+ );
136
+
137
+ const dependencyLicenses = await Promise.all(licensePromises);
138
+
139
+ let noticeText =
140
+ 'This file contains third-party software notices and license terms.\n\n';
141
+
142
+ for (const dep of dependencyLicenses) {
143
+ noticeText +=
144
+ '============================================================\n';
145
+ noticeText += `${dep.name}@${dep.version}\n`;
146
+ noticeText += `(${dep.repository})\n\n`;
147
+ noticeText += `${dep.license}\n\n`;
148
+ }
149
+
150
+ await fs.writeFile(noticeFilePath, noticeText);
151
+ console.log(`NOTICES.txt generated at ${noticeFilePath}`);
152
+ } catch (error) {
153
+ console.error('Error generating NOTICES.txt:', error);
154
+ process.exit(1);
155
+ }
156
+ }
157
+
158
+ main().catch(console.error);
projects/ui/qwen-code/packages/vscode-ide-companion/src/diff-manager.ts ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import {
8
+ IdeDiffAcceptedNotificationSchema,
9
+ IdeDiffClosedNotificationSchema,
10
+ } from '@qwen-code/qwen-code-core';
11
+ import { type JSONRPCNotification } from '@modelcontextprotocol/sdk/types.js';
12
+ import * as path from 'node:path';
13
+ import * as vscode from 'vscode';
14
+ import { DIFF_SCHEME } from './extension.js';
15
+
16
+ export class DiffContentProvider implements vscode.TextDocumentContentProvider {
17
+ private content = new Map<string, string>();
18
+ private onDidChangeEmitter = new vscode.EventEmitter<vscode.Uri>();
19
+
20
+ get onDidChange(): vscode.Event<vscode.Uri> {
21
+ return this.onDidChangeEmitter.event;
22
+ }
23
+
24
+ provideTextDocumentContent(uri: vscode.Uri): string {
25
+ return this.content.get(uri.toString()) ?? '';
26
+ }
27
+
28
+ setContent(uri: vscode.Uri, content: string): void {
29
+ this.content.set(uri.toString(), content);
30
+ this.onDidChangeEmitter.fire(uri);
31
+ }
32
+
33
+ deleteContent(uri: vscode.Uri): void {
34
+ this.content.delete(uri.toString());
35
+ }
36
+
37
+ getContent(uri: vscode.Uri): string | undefined {
38
+ return this.content.get(uri.toString());
39
+ }
40
+ }
41
+
42
+ // Information about a diff view that is currently open.
43
+ interface DiffInfo {
44
+ originalFilePath: string;
45
+ newContent: string;
46
+ rightDocUri: vscode.Uri;
47
+ }
48
+
49
+ /**
50
+ * Manages the state and lifecycle of diff views within the IDE.
51
+ */
52
+ export class DiffManager {
53
+ private readonly onDidChangeEmitter =
54
+ new vscode.EventEmitter<JSONRPCNotification>();
55
+ readonly onDidChange = this.onDidChangeEmitter.event;
56
+ private diffDocuments = new Map<string, DiffInfo>();
57
+ private readonly subscriptions: vscode.Disposable[] = [];
58
+
59
+ constructor(
60
+ private readonly log: (message: string) => void,
61
+ private readonly diffContentProvider: DiffContentProvider,
62
+ ) {
63
+ this.subscriptions.push(
64
+ vscode.window.onDidChangeActiveTextEditor((editor) => {
65
+ this.onActiveEditorChange(editor);
66
+ }),
67
+ );
68
+ this.onActiveEditorChange(vscode.window.activeTextEditor);
69
+ }
70
+
71
+ dispose() {
72
+ for (const subscription of this.subscriptions) {
73
+ subscription.dispose();
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Creates and shows a new diff view.
79
+ */
80
+ async showDiff(filePath: string, newContent: string) {
81
+ const fileUri = vscode.Uri.file(filePath);
82
+
83
+ const rightDocUri = vscode.Uri.from({
84
+ scheme: DIFF_SCHEME,
85
+ path: filePath,
86
+ // cache busting
87
+ query: `rand=${Math.random()}`,
88
+ });
89
+ this.diffContentProvider.setContent(rightDocUri, newContent);
90
+
91
+ this.addDiffDocument(rightDocUri, {
92
+ originalFilePath: filePath,
93
+ newContent,
94
+ rightDocUri,
95
+ });
96
+
97
+ const diffTitle = `${path.basename(filePath)} ↔ Modified`;
98
+ await vscode.commands.executeCommand(
99
+ 'setContext',
100
+ 'qwen.diff.isVisible',
101
+ true,
102
+ );
103
+
104
+ let leftDocUri;
105
+ try {
106
+ await vscode.workspace.fs.stat(fileUri);
107
+ leftDocUri = fileUri;
108
+ } catch {
109
+ // We need to provide an empty document to diff against.
110
+ // Using the 'untitled' scheme is one way to do this.
111
+ leftDocUri = vscode.Uri.from({
112
+ scheme: 'untitled',
113
+ path: filePath,
114
+ });
115
+ }
116
+
117
+ await vscode.commands.executeCommand(
118
+ 'vscode.diff',
119
+ leftDocUri,
120
+ rightDocUri,
121
+ diffTitle,
122
+ {
123
+ preview: false,
124
+ },
125
+ );
126
+ await vscode.commands.executeCommand(
127
+ 'workbench.action.files.setActiveEditorWriteableInSession',
128
+ );
129
+ }
130
+
131
+ /**
132
+ * Closes an open diff view for a specific file.
133
+ */
134
+ async closeDiff(filePath: string) {
135
+ let uriToClose: vscode.Uri | undefined;
136
+ for (const [uriString, diffInfo] of this.diffDocuments.entries()) {
137
+ if (diffInfo.originalFilePath === filePath) {
138
+ uriToClose = vscode.Uri.parse(uriString);
139
+ break;
140
+ }
141
+ }
142
+
143
+ if (uriToClose) {
144
+ const rightDoc = await vscode.workspace.openTextDocument(uriToClose);
145
+ const modifiedContent = rightDoc.getText();
146
+ await this.closeDiffEditor(uriToClose);
147
+ this.onDidChangeEmitter.fire(
148
+ IdeDiffClosedNotificationSchema.parse({
149
+ jsonrpc: '2.0',
150
+ method: 'ide/diffClosed',
151
+ params: {
152
+ filePath,
153
+ content: modifiedContent,
154
+ },
155
+ }),
156
+ );
157
+ return modifiedContent;
158
+ }
159
+ return;
160
+ }
161
+
162
+ /**
163
+ * User accepts the changes in a diff view. Does not apply changes.
164
+ */
165
+ async acceptDiff(rightDocUri: vscode.Uri) {
166
+ const diffInfo = this.diffDocuments.get(rightDocUri.toString());
167
+ if (!diffInfo) {
168
+ this.log(`No diff info found for ${rightDocUri.toString()}`);
169
+ return;
170
+ }
171
+
172
+ const rightDoc = await vscode.workspace.openTextDocument(rightDocUri);
173
+ const modifiedContent = rightDoc.getText();
174
+ await this.closeDiffEditor(rightDocUri);
175
+
176
+ this.onDidChangeEmitter.fire(
177
+ IdeDiffAcceptedNotificationSchema.parse({
178
+ jsonrpc: '2.0',
179
+ method: 'ide/diffAccepted',
180
+ params: {
181
+ filePath: diffInfo.originalFilePath,
182
+ content: modifiedContent,
183
+ },
184
+ }),
185
+ );
186
+ }
187
+
188
+ /**
189
+ * Called when a user cancels a diff view.
190
+ */
191
+ async cancelDiff(rightDocUri: vscode.Uri) {
192
+ const diffInfo = this.diffDocuments.get(rightDocUri.toString());
193
+ if (!diffInfo) {
194
+ this.log(`No diff info found for ${rightDocUri.toString()}`);
195
+ // Even if we don't have diff info, we should still close the editor.
196
+ await this.closeDiffEditor(rightDocUri);
197
+ return;
198
+ }
199
+
200
+ const rightDoc = await vscode.workspace.openTextDocument(rightDocUri);
201
+ const modifiedContent = rightDoc.getText();
202
+ await this.closeDiffEditor(rightDocUri);
203
+
204
+ this.onDidChangeEmitter.fire(
205
+ IdeDiffClosedNotificationSchema.parse({
206
+ jsonrpc: '2.0',
207
+ method: 'ide/diffClosed',
208
+ params: {
209
+ filePath: diffInfo.originalFilePath,
210
+ content: modifiedContent,
211
+ },
212
+ }),
213
+ );
214
+ }
215
+
216
+ private async onActiveEditorChange(editor: vscode.TextEditor | undefined) {
217
+ let isVisible = false;
218
+ if (editor) {
219
+ isVisible = this.diffDocuments.has(editor.document.uri.toString());
220
+ if (!isVisible) {
221
+ for (const document of this.diffDocuments.values()) {
222
+ if (document.originalFilePath === editor.document.uri.fsPath) {
223
+ isVisible = true;
224
+ break;
225
+ }
226
+ }
227
+ }
228
+ }
229
+ await vscode.commands.executeCommand(
230
+ 'setContext',
231
+ 'qwen.diff.isVisible',
232
+ isVisible,
233
+ );
234
+ }
235
+
236
+ private addDiffDocument(uri: vscode.Uri, diffInfo: DiffInfo) {
237
+ this.diffDocuments.set(uri.toString(), diffInfo);
238
+ }
239
+
240
+ private async closeDiffEditor(rightDocUri: vscode.Uri) {
241
+ const diffInfo = this.diffDocuments.get(rightDocUri.toString());
242
+ await vscode.commands.executeCommand(
243
+ 'setContext',
244
+ 'qwen.diff.isVisible',
245
+ false,
246
+ );
247
+
248
+ if (diffInfo) {
249
+ this.diffDocuments.delete(rightDocUri.toString());
250
+ this.diffContentProvider.deleteContent(rightDocUri);
251
+ }
252
+
253
+ // Find and close the tab corresponding to the diff view
254
+ for (const tabGroup of vscode.window.tabGroups.all) {
255
+ for (const tab of tabGroup.tabs) {
256
+ const input = tab.input as {
257
+ modified?: vscode.Uri;
258
+ original?: vscode.Uri;
259
+ };
260
+ if (input && input.modified?.toString() === rightDocUri.toString()) {
261
+ await vscode.window.tabGroups.close(tab);
262
+ return;
263
+ }
264
+ }
265
+ }
266
+ }
267
+ }
projects/ui/qwen-code/packages/vscode-ide-companion/src/extension-multi-folder.test.ts ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
8
+ import * as vscode from 'vscode';
9
+ import * as path from 'path';
10
+ import { activate } from './extension.js';
11
+
12
+ vi.mock('vscode', () => ({
13
+ window: {
14
+ createOutputChannel: vi.fn(() => ({
15
+ appendLine: vi.fn(),
16
+ })),
17
+ showInformationMessage: vi.fn(),
18
+ createTerminal: vi.fn(() => ({
19
+ show: vi.fn(),
20
+ sendText: vi.fn(),
21
+ })),
22
+ onDidChangeActiveTextEditor: vi.fn(),
23
+ activeTextEditor: undefined,
24
+ tabGroups: {
25
+ all: [],
26
+ close: vi.fn(),
27
+ },
28
+ showTextDocument: vi.fn(),
29
+ },
30
+ workspace: {
31
+ workspaceFolders: [],
32
+ onDidCloseTextDocument: vi.fn(),
33
+ registerTextDocumentContentProvider: vi.fn(),
34
+ onDidChangeWorkspaceFolders: vi.fn(),
35
+ },
36
+ commands: {
37
+ registerCommand: vi.fn(),
38
+ executeCommand: vi.fn(),
39
+ },
40
+ Uri: {
41
+ joinPath: vi.fn(),
42
+ file: (path: string) => ({ fsPath: path }),
43
+ },
44
+ ExtensionMode: {
45
+ Development: 1,
46
+ Production: 2,
47
+ },
48
+ EventEmitter: vi.fn(() => ({
49
+ event: vi.fn(),
50
+ fire: vi.fn(),
51
+ dispose: vi.fn(),
52
+ })),
53
+ }));
54
+
55
+ describe('activate with multiple folders', () => {
56
+ let context: vscode.ExtensionContext;
57
+ let onDidChangeWorkspaceFoldersCallback: (
58
+ e: vscode.WorkspaceFoldersChangeEvent,
59
+ ) => void;
60
+
61
+ beforeEach(() => {
62
+ context = {
63
+ subscriptions: [],
64
+ environmentVariableCollection: {
65
+ replace: vi.fn(),
66
+ },
67
+ globalState: {
68
+ get: vi.fn().mockReturnValue(true),
69
+ update: vi.fn(),
70
+ },
71
+ extensionUri: {
72
+ fsPath: '/path/to/extension',
73
+ },
74
+ } as unknown as vscode.ExtensionContext;
75
+
76
+ vi.mocked(vscode.workspace.onDidChangeWorkspaceFolders).mockImplementation(
77
+ (callback) => {
78
+ onDidChangeWorkspaceFoldersCallback = callback;
79
+ return { dispose: vi.fn() };
80
+ },
81
+ );
82
+ });
83
+
84
+ afterEach(() => {
85
+ vi.restoreAllMocks();
86
+ });
87
+
88
+ it('should set a single folder path', async () => {
89
+ const workspaceFoldersSpy = vi.spyOn(
90
+ vscode.workspace,
91
+ 'workspaceFolders',
92
+ 'get',
93
+ );
94
+ workspaceFoldersSpy.mockReturnValue([
95
+ { uri: { fsPath: '/foo/bar' } },
96
+ ] as vscode.WorkspaceFolder[]);
97
+
98
+ await activate(context);
99
+
100
+ expect(context.environmentVariableCollection.replace).toHaveBeenCalledWith(
101
+ 'QWEN_CODE_IDE_WORKSPACE_PATH',
102
+ '/foo/bar',
103
+ );
104
+ });
105
+
106
+ it('should set multiple folder paths, separated by OS-specific path delimiter', async () => {
107
+ const workspaceFoldersSpy = vi.spyOn(
108
+ vscode.workspace,
109
+ 'workspaceFolders',
110
+ 'get',
111
+ );
112
+ workspaceFoldersSpy.mockReturnValue([
113
+ { uri: { fsPath: '/foo/bar' } },
114
+ { uri: { fsPath: '/baz/qux' } },
115
+ ] as vscode.WorkspaceFolder[]);
116
+
117
+ await activate(context);
118
+
119
+ expect(context.environmentVariableCollection.replace).toHaveBeenCalledWith(
120
+ 'QWEN_CODE_IDE_WORKSPACE_PATH',
121
+ ['/foo/bar', '/baz/qux'].join(path.delimiter),
122
+ );
123
+ });
124
+
125
+ it('should set an empty string if no folders are open', async () => {
126
+ const workspaceFoldersSpy = vi.spyOn(
127
+ vscode.workspace,
128
+ 'workspaceFolders',
129
+ 'get',
130
+ );
131
+ workspaceFoldersSpy.mockReturnValue([]);
132
+
133
+ await activate(context);
134
+
135
+ expect(context.environmentVariableCollection.replace).toHaveBeenCalledWith(
136
+ 'QWEN_CODE_IDE_WORKSPACE_PATH',
137
+ '',
138
+ );
139
+ });
140
+
141
+ it('should update the path when workspace folders change', async () => {
142
+ const workspaceFoldersSpy = vi.spyOn(
143
+ vscode.workspace,
144
+ 'workspaceFolders',
145
+ 'get',
146
+ );
147
+ workspaceFoldersSpy.mockReturnValue([
148
+ { uri: { fsPath: '/foo/bar' } },
149
+ ] as vscode.WorkspaceFolder[]);
150
+
151
+ await activate(context);
152
+
153
+ expect(context.environmentVariableCollection.replace).toHaveBeenCalledWith(
154
+ 'QWEN_CODE_IDE_WORKSPACE_PATH',
155
+ '/foo/bar',
156
+ );
157
+
158
+ // Simulate adding a folder
159
+ workspaceFoldersSpy.mockReturnValue([
160
+ { uri: { fsPath: '/foo/bar' } },
161
+ { uri: { fsPath: '/baz/qux' } },
162
+ ] as vscode.WorkspaceFolder[]);
163
+ onDidChangeWorkspaceFoldersCallback({
164
+ added: [{ uri: { fsPath: '/baz/qux' } } as vscode.WorkspaceFolder],
165
+ removed: [],
166
+ });
167
+
168
+ expect(context.environmentVariableCollection.replace).toHaveBeenCalledWith(
169
+ 'QWEN_CODE_IDE_WORKSPACE_PATH',
170
+ ['/foo/bar', '/baz/qux'].join(path.delimiter),
171
+ );
172
+
173
+ // Simulate removing a folder
174
+ workspaceFoldersSpy.mockReturnValue([
175
+ { uri: { fsPath: '/baz/qux' } },
176
+ ] as vscode.WorkspaceFolder[]);
177
+ onDidChangeWorkspaceFoldersCallback({
178
+ added: [],
179
+ removed: [{ uri: { fsPath: '/foo/bar' } } as vscode.WorkspaceFolder],
180
+ });
181
+
182
+ expect(context.environmentVariableCollection.replace).toHaveBeenCalledWith(
183
+ 'QWEN_CODE_IDE_WORKSPACE_PATH',
184
+ '/baz/qux',
185
+ );
186
+ });
187
+
188
+ it.skipIf(process.platform !== 'win32')(
189
+ 'should handle windows paths',
190
+ async () => {
191
+ const workspaceFoldersSpy = vi.spyOn(
192
+ vscode.workspace,
193
+ 'workspaceFolders',
194
+ 'get',
195
+ );
196
+ workspaceFoldersSpy.mockReturnValue([
197
+ { uri: { fsPath: 'c:/foo/bar' } },
198
+ { uri: { fsPath: 'd:/baz/qux' } },
199
+ ] as vscode.WorkspaceFolder[]);
200
+
201
+ await activate(context);
202
+
203
+ expect(
204
+ context.environmentVariableCollection.replace,
205
+ ).toHaveBeenCalledWith(
206
+ 'QWEN_CODE_IDE_WORKSPACE_PATH',
207
+ 'c:/foo/bar;d:/baz/qux',
208
+ );
209
+ },
210
+ );
211
+ });
projects/ui/qwen-code/packages/vscode-ide-companion/src/extension.test.ts ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
8
+ import * as vscode from 'vscode';
9
+ import { activate } from './extension.js';
10
+
11
+ vi.mock('vscode', () => ({
12
+ window: {
13
+ createOutputChannel: vi.fn(() => ({
14
+ appendLine: vi.fn(),
15
+ })),
16
+ showInformationMessage: vi.fn(),
17
+ createTerminal: vi.fn(() => ({
18
+ show: vi.fn(),
19
+ sendText: vi.fn(),
20
+ })),
21
+ onDidChangeActiveTextEditor: vi.fn(),
22
+ activeTextEditor: undefined,
23
+ tabGroups: {
24
+ all: [],
25
+ close: vi.fn(),
26
+ },
27
+ showTextDocument: vi.fn(),
28
+ showWorkspaceFolderPick: vi.fn(),
29
+ },
30
+ workspace: {
31
+ workspaceFolders: [],
32
+ onDidCloseTextDocument: vi.fn(),
33
+ registerTextDocumentContentProvider: vi.fn(),
34
+ onDidChangeWorkspaceFolders: vi.fn(),
35
+ },
36
+ commands: {
37
+ registerCommand: vi.fn(),
38
+ executeCommand: vi.fn(),
39
+ },
40
+ Uri: {
41
+ joinPath: vi.fn(),
42
+ },
43
+ ExtensionMode: {
44
+ Development: 1,
45
+ Production: 2,
46
+ },
47
+ EventEmitter: vi.fn(() => ({
48
+ event: vi.fn(),
49
+ fire: vi.fn(),
50
+ dispose: vi.fn(),
51
+ })),
52
+ }));
53
+
54
+ describe('activate', () => {
55
+ let context: vscode.ExtensionContext;
56
+
57
+ beforeEach(() => {
58
+ context = {
59
+ subscriptions: [],
60
+ environmentVariableCollection: {
61
+ replace: vi.fn(),
62
+ },
63
+ globalState: {
64
+ get: vi.fn(),
65
+ update: vi.fn(),
66
+ },
67
+ extensionUri: {
68
+ fsPath: '/path/to/extension',
69
+ },
70
+ } as unknown as vscode.ExtensionContext;
71
+ });
72
+
73
+ afterEach(() => {
74
+ vi.restoreAllMocks();
75
+ });
76
+
77
+ it('should show the info message on first activation', async () => {
78
+ const showInformationMessageMock = vi
79
+ .mocked(vscode.window.showInformationMessage)
80
+ .mockResolvedValue(undefined as never);
81
+ vi.mocked(context.globalState.get).mockReturnValue(undefined);
82
+ await activate(context);
83
+ expect(showInformationMessageMock).toHaveBeenCalledWith(
84
+ 'Qwen Code Companion extension successfully installed.',
85
+ );
86
+ });
87
+
88
+ it('should not show the info message on subsequent activations', async () => {
89
+ vi.mocked(context.globalState.get).mockReturnValue(true);
90
+ await activate(context);
91
+ expect(vscode.window.showInformationMessage).not.toHaveBeenCalled();
92
+ });
93
+
94
+ it('should launch Qwen Code when the user clicks the button', async () => {
95
+ const showInformationMessageMock = vi
96
+ .mocked(vscode.window.showInformationMessage)
97
+ .mockResolvedValue('Run Qwen Code' as never);
98
+ vi.mocked(context.globalState.get).mockReturnValue(undefined);
99
+ await activate(context);
100
+ expect(showInformationMessageMock).toHaveBeenCalled();
101
+ await new Promise(process.nextTick); // Wait for the promise to resolve
102
+ const commandCallback = vi
103
+ .mocked(vscode.commands.registerCommand)
104
+ .mock.calls.find((call) => call[0] === 'qwen-code.runQwenCode')?.[1];
105
+
106
+ expect(commandCallback).toBeDefined();
107
+ });
108
+ });
projects/ui/qwen-code/packages/vscode-ide-companion/src/extension.ts ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import * as vscode from 'vscode';
8
+ import * as path from 'path';
9
+ import { IDEServer } from './ide-server.js';
10
+ import { DiffContentProvider, DiffManager } from './diff-manager.js';
11
+ import { createLogger } from './utils/logger.js';
12
+
13
+ const INFO_MESSAGE_SHOWN_KEY = 'qwenCodeInfoMessageShown';
14
+ const IDE_WORKSPACE_PATH_ENV_VAR = 'QWEN_CODE_IDE_WORKSPACE_PATH';
15
+ export const DIFF_SCHEME = 'qwen-diff';
16
+
17
+ let ideServer: IDEServer;
18
+ let logger: vscode.OutputChannel;
19
+
20
+ let log: (message: string) => void = () => {};
21
+
22
+ function updateWorkspacePath(context: vscode.ExtensionContext) {
23
+ const workspaceFolders = vscode.workspace.workspaceFolders;
24
+ if (workspaceFolders && workspaceFolders.length > 0) {
25
+ const workspacePaths = workspaceFolders
26
+ .map((folder) => folder.uri.fsPath)
27
+ .join(path.delimiter);
28
+ context.environmentVariableCollection.replace(
29
+ IDE_WORKSPACE_PATH_ENV_VAR,
30
+ workspacePaths,
31
+ );
32
+ } else {
33
+ context.environmentVariableCollection.replace(
34
+ IDE_WORKSPACE_PATH_ENV_VAR,
35
+ '',
36
+ );
37
+ }
38
+ }
39
+
40
+ export async function activate(context: vscode.ExtensionContext) {
41
+ logger = vscode.window.createOutputChannel('Qwen Code Companion');
42
+ log = createLogger(context, logger);
43
+ log('Extension activated');
44
+
45
+ updateWorkspacePath(context);
46
+
47
+ const diffContentProvider = new DiffContentProvider();
48
+ const diffManager = new DiffManager(log, diffContentProvider);
49
+
50
+ context.subscriptions.push(
51
+ vscode.workspace.onDidCloseTextDocument((doc) => {
52
+ if (doc.uri.scheme === DIFF_SCHEME) {
53
+ diffManager.cancelDiff(doc.uri);
54
+ }
55
+ }),
56
+ vscode.workspace.registerTextDocumentContentProvider(
57
+ DIFF_SCHEME,
58
+ diffContentProvider,
59
+ ),
60
+ vscode.commands.registerCommand('qwen.diff.accept', (uri?: vscode.Uri) => {
61
+ const docUri = uri ?? vscode.window.activeTextEditor?.document.uri;
62
+ if (docUri && docUri.scheme === DIFF_SCHEME) {
63
+ diffManager.acceptDiff(docUri);
64
+ }
65
+ }),
66
+ vscode.commands.registerCommand('qwen.diff.cancel', (uri?: vscode.Uri) => {
67
+ const docUri = uri ?? vscode.window.activeTextEditor?.document.uri;
68
+ if (docUri && docUri.scheme === DIFF_SCHEME) {
69
+ diffManager.cancelDiff(docUri);
70
+ }
71
+ }),
72
+ );
73
+
74
+ ideServer = new IDEServer(log, diffManager);
75
+ try {
76
+ await ideServer.start(context);
77
+ } catch (err) {
78
+ const message = err instanceof Error ? err.message : String(err);
79
+ log(`Failed to start IDE server: ${message}`);
80
+ }
81
+
82
+ if (!context.globalState.get(INFO_MESSAGE_SHOWN_KEY)) {
83
+ void vscode.window.showInformationMessage(
84
+ 'Qwen Code Companion extension successfully installed.',
85
+ );
86
+ context.globalState.update(INFO_MESSAGE_SHOWN_KEY, true);
87
+ }
88
+
89
+ context.subscriptions.push(
90
+ vscode.workspace.onDidChangeWorkspaceFolders(() => {
91
+ updateWorkspacePath(context);
92
+ }),
93
+ vscode.commands.registerCommand('qwen-code.runQwenCode', async () => {
94
+ const workspaceFolders = vscode.workspace.workspaceFolders;
95
+ if (!workspaceFolders || workspaceFolders.length === 0) {
96
+ vscode.window.showInformationMessage(
97
+ 'No folder open. Please open a folder to run Qwen Code.',
98
+ );
99
+ return;
100
+ }
101
+
102
+ let selectedFolder: vscode.WorkspaceFolder | undefined;
103
+ if (workspaceFolders.length === 1) {
104
+ selectedFolder = workspaceFolders[0];
105
+ } else {
106
+ selectedFolder = await vscode.window.showWorkspaceFolderPick({
107
+ placeHolder: 'Select a folder to run Qwen Code in',
108
+ });
109
+ }
110
+
111
+ if (selectedFolder) {
112
+ const qwenCmd = 'qwen';
113
+ const terminal = vscode.window.createTerminal({
114
+ name: `Qwen Code (${selectedFolder.name})`,
115
+ cwd: selectedFolder.uri.fsPath,
116
+ });
117
+ terminal.show();
118
+ terminal.sendText(qwenCmd);
119
+ }
120
+ }),
121
+ vscode.commands.registerCommand('qwen-code.showNotices', async () => {
122
+ const noticePath = vscode.Uri.joinPath(
123
+ context.extensionUri,
124
+ 'NOTICES.txt',
125
+ );
126
+ await vscode.window.showTextDocument(noticePath);
127
+ }),
128
+ );
129
+ }
130
+
131
+ export async function deactivate(): Promise<void> {
132
+ log('Extension deactivated');
133
+ try {
134
+ if (ideServer) {
135
+ await ideServer.stop();
136
+ }
137
+ } catch (err) {
138
+ const message = err instanceof Error ? err.message : String(err);
139
+ log(`Failed to stop IDE server during deactivation: ${message}`);
140
+ } finally {
141
+ if (logger) {
142
+ logger.dispose();
143
+ }
144
+ }
145
+ }
projects/ui/qwen-code/packages/vscode-ide-companion/src/ide-server.ts ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import * as vscode from 'vscode';
8
+ import { IdeContextNotificationSchema } from '@qwen-code/qwen-code-core';
9
+ import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
10
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
11
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
12
+ import express, { type Request, type Response } from 'express';
13
+ import { randomUUID } from 'node:crypto';
14
+ import { type Server as HTTPServer } from 'node:http';
15
+ import * as path from 'node:path';
16
+ import * as fs from 'node:fs/promises';
17
+ import * as os from 'node:os';
18
+ import { z } from 'zod';
19
+ import { DiffManager } from './diff-manager.js';
20
+ import { OpenFilesManager } from './open-files-manager.js';
21
+
22
+ const MCP_SESSION_ID_HEADER = 'mcp-session-id';
23
+ const IDE_SERVER_PORT_ENV_VAR = 'QWEN_CODE_IDE_SERVER_PORT';
24
+
25
+ function sendIdeContextUpdateNotification(
26
+ transport: StreamableHTTPServerTransport,
27
+ log: (message: string) => void,
28
+ openFilesManager: OpenFilesManager,
29
+ ) {
30
+ const ideContext = openFilesManager.state;
31
+
32
+ const notification = IdeContextNotificationSchema.parse({
33
+ jsonrpc: '2.0',
34
+ method: 'ide/contextUpdate',
35
+ params: ideContext,
36
+ });
37
+
38
+ log(
39
+ `Sending IDE context update notification: ${JSON.stringify(
40
+ notification,
41
+ null,
42
+ 2,
43
+ )}`,
44
+ );
45
+ transport.send(notification);
46
+ }
47
+
48
+ export class IDEServer {
49
+ private server: HTTPServer | undefined;
50
+ private context: vscode.ExtensionContext | undefined;
51
+ private log: (message: string) => void;
52
+ private portFile: string;
53
+ diffManager: DiffManager;
54
+
55
+ constructor(log: (message: string) => void, diffManager: DiffManager) {
56
+ this.log = log;
57
+ this.diffManager = diffManager;
58
+ this.portFile = path.join(
59
+ os.tmpdir(),
60
+ `gemini-ide-server-${process.ppid}.json`,
61
+ );
62
+ }
63
+
64
+ async start(context: vscode.ExtensionContext) {
65
+ this.context = context;
66
+ const sessionsWithInitialNotification = new Set<string>();
67
+ const transports: { [sessionId: string]: StreamableHTTPServerTransport } =
68
+ {};
69
+
70
+ const app = express();
71
+ app.use(express.json());
72
+ const mcpServer = createMcpServer(this.diffManager);
73
+
74
+ const openFilesManager = new OpenFilesManager(context);
75
+ const onDidChangeSubscription = openFilesManager.onDidChange(() => {
76
+ for (const transport of Object.values(transports)) {
77
+ sendIdeContextUpdateNotification(
78
+ transport,
79
+ this.log.bind(this),
80
+ openFilesManager,
81
+ );
82
+ }
83
+ });
84
+ context.subscriptions.push(onDidChangeSubscription);
85
+ const onDidChangeDiffSubscription = this.diffManager.onDidChange(
86
+ (notification) => {
87
+ for (const transport of Object.values(transports)) {
88
+ transport.send(notification);
89
+ }
90
+ },
91
+ );
92
+ context.subscriptions.push(onDidChangeDiffSubscription);
93
+
94
+ app.post('/mcp', async (req: Request, res: Response) => {
95
+ const sessionId = req.headers[MCP_SESSION_ID_HEADER] as
96
+ | string
97
+ | undefined;
98
+ let transport: StreamableHTTPServerTransport;
99
+
100
+ if (sessionId && transports[sessionId]) {
101
+ transport = transports[sessionId];
102
+ } else if (!sessionId && isInitializeRequest(req.body)) {
103
+ transport = new StreamableHTTPServerTransport({
104
+ sessionIdGenerator: () => randomUUID(),
105
+ onsessioninitialized: (newSessionId) => {
106
+ this.log(`New session initialized: ${newSessionId}`);
107
+ transports[newSessionId] = transport;
108
+ },
109
+ });
110
+ const keepAlive = setInterval(() => {
111
+ try {
112
+ transport.send({ jsonrpc: '2.0', method: 'ping' });
113
+ } catch (e) {
114
+ this.log(
115
+ 'Failed to send keep-alive ping, cleaning up interval.' + e,
116
+ );
117
+ clearInterval(keepAlive);
118
+ }
119
+ }, 60000); // 60 sec
120
+
121
+ transport.onclose = () => {
122
+ clearInterval(keepAlive);
123
+ if (transport.sessionId) {
124
+ this.log(`Session closed: ${transport.sessionId}`);
125
+ sessionsWithInitialNotification.delete(transport.sessionId);
126
+ delete transports[transport.sessionId];
127
+ }
128
+ };
129
+ mcpServer.connect(transport);
130
+ } else {
131
+ this.log(
132
+ 'Bad Request: No valid session ID provided for non-initialize request.',
133
+ );
134
+ res.status(400).json({
135
+ jsonrpc: '2.0',
136
+ error: {
137
+ code: -32000,
138
+ message:
139
+ 'Bad Request: No valid session ID provided for non-initialize request.',
140
+ },
141
+ id: null,
142
+ });
143
+ return;
144
+ }
145
+
146
+ try {
147
+ await transport.handleRequest(req, res, req.body);
148
+ } catch (error) {
149
+ const errorMessage =
150
+ error instanceof Error ? error.message : 'Unknown error';
151
+ this.log(`Error handling MCP request: ${errorMessage}`);
152
+ if (!res.headersSent) {
153
+ res.status(500).json({
154
+ jsonrpc: '2.0' as const,
155
+ error: {
156
+ code: -32603,
157
+ message: 'Internal server error',
158
+ },
159
+ id: null,
160
+ });
161
+ }
162
+ }
163
+ });
164
+
165
+ const handleSessionRequest = async (req: Request, res: Response) => {
166
+ const sessionId = req.headers[MCP_SESSION_ID_HEADER] as
167
+ | string
168
+ | undefined;
169
+ if (!sessionId || !transports[sessionId]) {
170
+ this.log('Invalid or missing session ID');
171
+ res.status(400).send('Invalid or missing session ID');
172
+ return;
173
+ }
174
+
175
+ const transport = transports[sessionId];
176
+ try {
177
+ await transport.handleRequest(req, res);
178
+ } catch (error) {
179
+ const errorMessage =
180
+ error instanceof Error ? error.message : 'Unknown error';
181
+ this.log(`Error handling session request: ${errorMessage}`);
182
+ if (!res.headersSent) {
183
+ res.status(400).send('Bad Request');
184
+ }
185
+ }
186
+
187
+ if (!sessionsWithInitialNotification.has(sessionId)) {
188
+ sendIdeContextUpdateNotification(
189
+ transport,
190
+ this.log.bind(this),
191
+ openFilesManager,
192
+ );
193
+ sessionsWithInitialNotification.add(sessionId);
194
+ }
195
+ };
196
+
197
+ app.get('/mcp', handleSessionRequest);
198
+
199
+ this.server = app.listen(0, () => {
200
+ const address = (this.server as HTTPServer).address();
201
+ if (address && typeof address !== 'string') {
202
+ const port = address.port;
203
+ context.environmentVariableCollection.replace(
204
+ IDE_SERVER_PORT_ENV_VAR,
205
+ port.toString(),
206
+ );
207
+ this.log(`IDE server listening on port ${port}`);
208
+ fs.writeFile(this.portFile, JSON.stringify({ port })).catch((err) => {
209
+ this.log(`Failed to write port to file: ${err}`);
210
+ });
211
+ this.log(this.portFile);
212
+ }
213
+ });
214
+ }
215
+
216
+ async stop(): Promise<void> {
217
+ if (this.server) {
218
+ await new Promise<void>((resolve, reject) => {
219
+ this.server!.close((err?: Error) => {
220
+ if (err) {
221
+ this.log(`Error shutting down IDE server: ${err.message}`);
222
+ return reject(err);
223
+ }
224
+ this.log(`IDE server shut down`);
225
+ resolve();
226
+ });
227
+ });
228
+ this.server = undefined;
229
+ }
230
+
231
+ if (this.context) {
232
+ this.context.environmentVariableCollection.clear();
233
+ }
234
+ try {
235
+ await fs.unlink(this.portFile);
236
+ } catch (_err) {
237
+ // Ignore errors if the file doesn't exist.
238
+ }
239
+ }
240
+ }
241
+
242
+ const createMcpServer = (diffManager: DiffManager) => {
243
+ const server = new McpServer(
244
+ {
245
+ name: 'qwen-code-companion-mcp-server',
246
+ version: '1.0.0',
247
+ },
248
+ { capabilities: { logging: {} } },
249
+ );
250
+ server.registerTool(
251
+ 'openDiff',
252
+ {
253
+ description:
254
+ '(IDE Tool) Open a diff view to create or modify a file. Returns a notification once the diff has been accepted or rejcted.',
255
+ inputSchema: z.object({
256
+ filePath: z.string(),
257
+ // TODO(chrstn): determine if this should be required or not.
258
+ newContent: z.string().optional(),
259
+ }).shape,
260
+ },
261
+ async ({
262
+ filePath,
263
+ newContent,
264
+ }: {
265
+ filePath: string;
266
+ newContent?: string;
267
+ }) => {
268
+ await diffManager.showDiff(filePath, newContent ?? '');
269
+ return {
270
+ content: [
271
+ {
272
+ type: 'text',
273
+ text: `Showing diff for ${filePath}`,
274
+ },
275
+ ],
276
+ };
277
+ },
278
+ );
279
+ server.registerTool(
280
+ 'closeDiff',
281
+ {
282
+ description: '(IDE Tool) Close an open diff view for a specific file.',
283
+ inputSchema: z.object({
284
+ filePath: z.string(),
285
+ }).shape,
286
+ },
287
+ async ({ filePath }: { filePath: string }) => {
288
+ const content = await diffManager.closeDiff(filePath);
289
+ const response = { content: content ?? undefined };
290
+ return {
291
+ content: [
292
+ {
293
+ type: 'text',
294
+ text: JSON.stringify(response),
295
+ },
296
+ ],
297
+ };
298
+ },
299
+ );
300
+ return server;
301
+ };
projects/ui/qwen-code/packages/vscode-ide-companion/src/open-files-manager.test.ts ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
8
+ import * as vscode from 'vscode';
9
+ import { OpenFilesManager, MAX_FILES } from './open-files-manager.js';
10
+
11
+ vi.mock('vscode', () => ({
12
+ EventEmitter: vi.fn(() => {
13
+ const listeners: Array<(e: void) => unknown> = [];
14
+ return {
15
+ event: vi.fn((listener) => {
16
+ listeners.push(listener);
17
+ return { dispose: vi.fn() };
18
+ }),
19
+ fire: vi.fn(() => {
20
+ listeners.forEach((listener) => listener(undefined));
21
+ }),
22
+ dispose: vi.fn(),
23
+ };
24
+ }),
25
+ window: {
26
+ onDidChangeActiveTextEditor: vi.fn(),
27
+ onDidChangeTextEditorSelection: vi.fn(),
28
+ },
29
+ workspace: {
30
+ onDidDeleteFiles: vi.fn(),
31
+ onDidCloseTextDocument: vi.fn(),
32
+ onDidRenameFiles: vi.fn(),
33
+ },
34
+ Uri: {
35
+ file: (path: string) => ({
36
+ fsPath: path,
37
+ scheme: 'file',
38
+ }),
39
+ },
40
+ TextEditorSelectionChangeKind: {
41
+ Mouse: 2,
42
+ },
43
+ }));
44
+
45
+ describe('OpenFilesManager', () => {
46
+ let context: vscode.ExtensionContext;
47
+ let onDidChangeActiveTextEditorListener: (
48
+ editor: vscode.TextEditor | undefined,
49
+ ) => void;
50
+ let onDidChangeTextEditorSelectionListener: (
51
+ e: vscode.TextEditorSelectionChangeEvent,
52
+ ) => void;
53
+ let onDidDeleteFilesListener: (e: vscode.FileDeleteEvent) => void;
54
+ let onDidCloseTextDocumentListener: (doc: vscode.TextDocument) => void;
55
+ let onDidRenameFilesListener: (e: vscode.FileRenameEvent) => void;
56
+
57
+ beforeEach(() => {
58
+ vi.useFakeTimers();
59
+
60
+ vi.mocked(vscode.window.onDidChangeActiveTextEditor).mockImplementation(
61
+ (listener) => {
62
+ onDidChangeActiveTextEditorListener = listener;
63
+ return { dispose: vi.fn() };
64
+ },
65
+ );
66
+ vi.mocked(vscode.window.onDidChangeTextEditorSelection).mockImplementation(
67
+ (listener) => {
68
+ onDidChangeTextEditorSelectionListener = listener;
69
+ return { dispose: vi.fn() };
70
+ },
71
+ );
72
+ vi.mocked(vscode.workspace.onDidDeleteFiles).mockImplementation(
73
+ (listener) => {
74
+ onDidDeleteFilesListener = listener;
75
+ return { dispose: vi.fn() };
76
+ },
77
+ );
78
+ vi.mocked(vscode.workspace.onDidCloseTextDocument).mockImplementation(
79
+ (listener) => {
80
+ onDidCloseTextDocumentListener = listener;
81
+ return { dispose: vi.fn() };
82
+ },
83
+ );
84
+ vi.mocked(vscode.workspace.onDidRenameFiles).mockImplementation(
85
+ (listener) => {
86
+ onDidRenameFilesListener = listener;
87
+ return { dispose: vi.fn() };
88
+ },
89
+ );
90
+
91
+ context = {
92
+ subscriptions: [],
93
+ } as unknown as vscode.ExtensionContext;
94
+ });
95
+
96
+ afterEach(() => {
97
+ vi.restoreAllMocks();
98
+ vi.useRealTimers();
99
+ });
100
+
101
+ const getUri = (path: string) =>
102
+ vscode.Uri.file(path) as unknown as vscode.Uri;
103
+
104
+ const addFile = (uri: vscode.Uri) => {
105
+ onDidChangeActiveTextEditorListener({
106
+ document: {
107
+ uri,
108
+ getText: () => '',
109
+ },
110
+ selection: {
111
+ active: { line: 0, character: 0 },
112
+ },
113
+ } as unknown as vscode.TextEditor);
114
+ };
115
+
116
+ it('adds a file to the list', async () => {
117
+ const manager = new OpenFilesManager(context);
118
+ const uri = getUri('/test/file1.txt');
119
+ addFile(uri);
120
+ await vi.advanceTimersByTimeAsync(100);
121
+ expect(manager.state.workspaceState!.openFiles).toHaveLength(1);
122
+ expect(manager.state.workspaceState!.openFiles![0].path).toBe(
123
+ '/test/file1.txt',
124
+ );
125
+ });
126
+
127
+ it('moves an existing file to the top', async () => {
128
+ const manager = new OpenFilesManager(context);
129
+ const uri1 = getUri('/test/file1.txt');
130
+ const uri2 = getUri('/test/file2.txt');
131
+ addFile(uri1);
132
+ addFile(uri2);
133
+ addFile(uri1);
134
+ await vi.advanceTimersByTimeAsync(100);
135
+ expect(manager.state.workspaceState!.openFiles).toHaveLength(2);
136
+ expect(manager.state.workspaceState!.openFiles![0].path).toBe(
137
+ '/test/file1.txt',
138
+ );
139
+ });
140
+
141
+ it('does not exceed the max number of files', async () => {
142
+ const manager = new OpenFilesManager(context);
143
+ for (let i = 0; i < MAX_FILES + 5; i++) {
144
+ const uri = getUri(`/test/file${i}.txt`);
145
+ addFile(uri);
146
+ }
147
+ await vi.advanceTimersByTimeAsync(100);
148
+ expect(manager.state.workspaceState!.openFiles).toHaveLength(MAX_FILES);
149
+ expect(manager.state.workspaceState!.openFiles![0].path).toBe(
150
+ `/test/file${MAX_FILES + 4}.txt`,
151
+ );
152
+ expect(manager.state.workspaceState!.openFiles![MAX_FILES - 1].path).toBe(
153
+ `/test/file5.txt`,
154
+ );
155
+ });
156
+
157
+ it('fires onDidChange when a file is added', async () => {
158
+ const manager = new OpenFilesManager(context);
159
+ const onDidChangeSpy = vi.fn();
160
+ manager.onDidChange(onDidChangeSpy);
161
+
162
+ const uri = getUri('/test/file1.txt');
163
+ addFile(uri);
164
+
165
+ await vi.advanceTimersByTimeAsync(100);
166
+ expect(onDidChangeSpy).toHaveBeenCalled();
167
+ });
168
+
169
+ it('removes a file when it is closed', async () => {
170
+ const manager = new OpenFilesManager(context);
171
+ const uri = getUri('/test/file1.txt');
172
+ addFile(uri);
173
+ await vi.advanceTimersByTimeAsync(100);
174
+ expect(manager.state.workspaceState!.openFiles).toHaveLength(1);
175
+
176
+ onDidCloseTextDocumentListener({ uri } as vscode.TextDocument);
177
+ await vi.advanceTimersByTimeAsync(100);
178
+
179
+ expect(manager.state.workspaceState!.openFiles).toHaveLength(0);
180
+ });
181
+
182
+ it('fires onDidChange when a file is removed', async () => {
183
+ const manager = new OpenFilesManager(context);
184
+ const uri = getUri('/test/file1.txt');
185
+ addFile(uri);
186
+ await vi.advanceTimersByTimeAsync(100);
187
+
188
+ const onDidChangeSpy = vi.fn();
189
+ manager.onDidChange(onDidChangeSpy);
190
+
191
+ onDidCloseTextDocumentListener({ uri } as vscode.TextDocument);
192
+ await vi.advanceTimersByTimeAsync(100);
193
+
194
+ expect(onDidChangeSpy).toHaveBeenCalled();
195
+ });
196
+
197
+ it('removes a file when it is deleted', async () => {
198
+ const manager = new OpenFilesManager(context);
199
+ const uri1 = getUri('/test/file1.txt');
200
+ const uri2 = getUri('/test/file2.txt');
201
+ addFile(uri1);
202
+ addFile(uri2);
203
+ await vi.advanceTimersByTimeAsync(100);
204
+ expect(manager.state.workspaceState!.openFiles).toHaveLength(2);
205
+
206
+ onDidDeleteFilesListener({ files: [uri1] });
207
+ await vi.advanceTimersByTimeAsync(100);
208
+
209
+ expect(manager.state.workspaceState!.openFiles).toHaveLength(1);
210
+ expect(manager.state.workspaceState!.openFiles![0].path).toBe(
211
+ '/test/file2.txt',
212
+ );
213
+ });
214
+
215
+ it('fires onDidChange when a file is deleted', async () => {
216
+ const manager = new OpenFilesManager(context);
217
+ const uri = getUri('/test/file1.txt');
218
+ addFile(uri);
219
+ await vi.advanceTimersByTimeAsync(100);
220
+
221
+ const onDidChangeSpy = vi.fn();
222
+ manager.onDidChange(onDidChangeSpy);
223
+
224
+ onDidDeleteFilesListener({ files: [uri] });
225
+ await vi.advanceTimersByTimeAsync(100);
226
+
227
+ expect(onDidChangeSpy).toHaveBeenCalled();
228
+ });
229
+
230
+ it('removes multiple files when they are deleted', async () => {
231
+ const manager = new OpenFilesManager(context);
232
+ const uri1 = getUri('/test/file1.txt');
233
+ const uri2 = getUri('/test/file2.txt');
234
+ const uri3 = getUri('/test/file3.txt');
235
+ addFile(uri1);
236
+ addFile(uri2);
237
+ addFile(uri3);
238
+ await vi.advanceTimersByTimeAsync(100);
239
+ expect(manager.state.workspaceState!.openFiles).toHaveLength(3);
240
+
241
+ onDidDeleteFilesListener({ files: [uri1, uri3] });
242
+ await vi.advanceTimersByTimeAsync(100);
243
+
244
+ expect(manager.state.workspaceState!.openFiles).toHaveLength(1);
245
+ expect(manager.state.workspaceState!.openFiles![0].path).toBe(
246
+ '/test/file2.txt',
247
+ );
248
+ });
249
+
250
+ it('fires onDidChange only once when adding an existing file', async () => {
251
+ const manager = new OpenFilesManager(context);
252
+ const uri = getUri('/test/file1.txt');
253
+ addFile(uri);
254
+ await vi.advanceTimersByTimeAsync(100);
255
+
256
+ const onDidChangeSpy = vi.fn();
257
+ manager.onDidChange(onDidChangeSpy);
258
+
259
+ addFile(uri);
260
+ await vi.advanceTimersByTimeAsync(100);
261
+ expect(onDidChangeSpy).toHaveBeenCalledTimes(1);
262
+ });
263
+
264
+ it('updates the file when it is renamed', async () => {
265
+ const manager = new OpenFilesManager(context);
266
+ const oldUri = getUri('/test/file1.txt');
267
+ const newUri = getUri('/test/file2.txt');
268
+ addFile(oldUri);
269
+ await vi.advanceTimersByTimeAsync(100);
270
+ expect(manager.state.workspaceState!.openFiles).toHaveLength(1);
271
+ expect(manager.state.workspaceState!.openFiles![0].path).toBe(
272
+ '/test/file1.txt',
273
+ );
274
+
275
+ onDidRenameFilesListener({ files: [{ oldUri, newUri }] });
276
+ await vi.advanceTimersByTimeAsync(100);
277
+
278
+ expect(manager.state.workspaceState!.openFiles).toHaveLength(1);
279
+ expect(manager.state.workspaceState!.openFiles![0].path).toBe(
280
+ '/test/file2.txt',
281
+ );
282
+ });
283
+
284
+ it('adds a file when the active editor changes', async () => {
285
+ const manager = new OpenFilesManager(context);
286
+ const uri = getUri('/test/file1.txt');
287
+
288
+ addFile(uri);
289
+ await vi.advanceTimersByTimeAsync(100);
290
+
291
+ expect(manager.state.workspaceState!.openFiles).toHaveLength(1);
292
+ expect(manager.state.workspaceState!.openFiles![0].path).toBe(
293
+ '/test/file1.txt',
294
+ );
295
+ });
296
+
297
+ it('updates the cursor position on selection change', async () => {
298
+ const manager = new OpenFilesManager(context);
299
+ const uri = getUri('/test/file1.txt');
300
+ addFile(uri);
301
+ await vi.advanceTimersByTimeAsync(100);
302
+
303
+ const selection = {
304
+ active: { line: 10, character: 20 },
305
+ } as vscode.Selection;
306
+
307
+ onDidChangeTextEditorSelectionListener({
308
+ textEditor: {
309
+ document: { uri, getText: () => '' },
310
+ selection,
311
+ } as vscode.TextEditor,
312
+ selections: [selection],
313
+ kind: vscode.TextEditorSelectionChangeKind.Mouse,
314
+ });
315
+
316
+ await vi.advanceTimersByTimeAsync(100);
317
+
318
+ const file = manager.state.workspaceState!.openFiles![0];
319
+ expect(file.cursor).toEqual({ line: 11, character: 20 });
320
+ });
321
+
322
+ it('updates the selected text on selection change', async () => {
323
+ const manager = new OpenFilesManager(context);
324
+ const uri = getUri('/test/file1.txt');
325
+ const selection = {
326
+ active: { line: 10, character: 20 },
327
+ } as vscode.Selection;
328
+
329
+ // We need to override the mock for getText for this test
330
+ const textEditor = {
331
+ document: {
332
+ uri,
333
+ getText: vi.fn().mockReturnValue('selected text'),
334
+ },
335
+ selection,
336
+ } as unknown as vscode.TextEditor;
337
+
338
+ onDidChangeActiveTextEditorListener(textEditor);
339
+ await vi.advanceTimersByTimeAsync(100);
340
+
341
+ onDidChangeTextEditorSelectionListener({
342
+ textEditor,
343
+ selections: [selection],
344
+ kind: vscode.TextEditorSelectionChangeKind.Mouse,
345
+ });
346
+
347
+ await vi.advanceTimersByTimeAsync(100);
348
+
349
+ const file = manager.state.workspaceState!.openFiles![0];
350
+ expect(file.selectedText).toBe('selected text');
351
+ expect(textEditor.document.getText).toHaveBeenCalledWith(selection);
352
+ });
353
+
354
+ it('truncates long selected text', async () => {
355
+ const manager = new OpenFilesManager(context);
356
+ const uri = getUri('/test/file1.txt');
357
+ const longText = 'a'.repeat(20000);
358
+ const truncatedText = longText.substring(0, 16384) + '... [TRUNCATED]';
359
+
360
+ const selection = {
361
+ active: { line: 10, character: 20 },
362
+ } as vscode.Selection;
363
+
364
+ const textEditor = {
365
+ document: {
366
+ uri,
367
+ getText: vi.fn().mockReturnValue(longText),
368
+ },
369
+ selection,
370
+ } as unknown as vscode.TextEditor;
371
+
372
+ onDidChangeActiveTextEditorListener(textEditor);
373
+ await vi.advanceTimersByTimeAsync(100);
374
+
375
+ onDidChangeTextEditorSelectionListener({
376
+ textEditor,
377
+ selections: [selection],
378
+ kind: vscode.TextEditorSelectionChangeKind.Mouse,
379
+ });
380
+
381
+ await vi.advanceTimersByTimeAsync(100);
382
+
383
+ const file = manager.state.workspaceState!.openFiles![0];
384
+ expect(file.selectedText).toBe(truncatedText);
385
+ });
386
+
387
+ it('deactivates the previously active file', async () => {
388
+ const manager = new OpenFilesManager(context);
389
+ const uri1 = getUri('/test/file1.txt');
390
+ const uri2 = getUri('/test/file2.txt');
391
+
392
+ addFile(uri1);
393
+ await vi.advanceTimersByTimeAsync(100);
394
+
395
+ const selection = {
396
+ active: { line: 10, character: 20 },
397
+ } as vscode.Selection;
398
+
399
+ onDidChangeTextEditorSelectionListener({
400
+ textEditor: {
401
+ document: { uri: uri1, getText: () => '' },
402
+ selection,
403
+ } as vscode.TextEditor,
404
+ selections: [selection],
405
+ kind: vscode.TextEditorSelectionChangeKind.Mouse,
406
+ });
407
+ await vi.advanceTimersByTimeAsync(100);
408
+
409
+ let file1 = manager.state.workspaceState!.openFiles![0];
410
+ expect(file1.isActive).toBe(true);
411
+ expect(file1.cursor).toBeDefined();
412
+
413
+ addFile(uri2);
414
+ await vi.advanceTimersByTimeAsync(100);
415
+
416
+ file1 = manager.state.workspaceState!.openFiles!.find(
417
+ (f) => f.path === '/test/file1.txt',
418
+ )!;
419
+ const file2 = manager.state.workspaceState!.openFiles![0];
420
+
421
+ expect(file1.isActive).toBe(false);
422
+ expect(file1.cursor).toBeUndefined();
423
+ expect(file1.selectedText).toBeUndefined();
424
+ expect(file2.path).toBe('/test/file2.txt');
425
+ expect(file2.isActive).toBe(true);
426
+ });
427
+
428
+ it('ignores non-file URIs', async () => {
429
+ const manager = new OpenFilesManager(context);
430
+ const uri = {
431
+ fsPath: '/test/file1.txt',
432
+ scheme: 'untitled',
433
+ } as vscode.Uri;
434
+
435
+ addFile(uri);
436
+ await vi.advanceTimersByTimeAsync(100);
437
+
438
+ expect(manager.state.workspaceState!.openFiles).toHaveLength(0);
439
+ });
440
+ });
projects/ui/qwen-code/packages/vscode-ide-companion/src/open-files-manager.ts ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import * as vscode from 'vscode';
8
+ import type { File, IdeContext } from '@qwen-code/qwen-code-core';
9
+
10
+ export const MAX_FILES = 10;
11
+ const MAX_SELECTED_TEXT_LENGTH = 16384; // 16 KiB limit
12
+
13
+ /**
14
+ * Keeps track of the workspace state, including open files, cursor position, and selected text.
15
+ */
16
+ export class OpenFilesManager {
17
+ private readonly onDidChangeEmitter = new vscode.EventEmitter<void>();
18
+ readonly onDidChange = this.onDidChangeEmitter.event;
19
+ private debounceTimer: NodeJS.Timeout | undefined;
20
+ private openFiles: File[] = [];
21
+
22
+ constructor(private readonly context: vscode.ExtensionContext) {
23
+ const editorWatcher = vscode.window.onDidChangeActiveTextEditor(
24
+ (editor) => {
25
+ if (editor && this.isFileUri(editor.document.uri)) {
26
+ this.addOrMoveToFront(editor);
27
+ this.fireWithDebounce();
28
+ }
29
+ },
30
+ );
31
+
32
+ const selectionWatcher = vscode.window.onDidChangeTextEditorSelection(
33
+ (event) => {
34
+ if (this.isFileUri(event.textEditor.document.uri)) {
35
+ this.updateActiveContext(event.textEditor);
36
+ this.fireWithDebounce();
37
+ }
38
+ },
39
+ );
40
+
41
+ const closeWatcher = vscode.workspace.onDidCloseTextDocument((document) => {
42
+ if (this.isFileUri(document.uri)) {
43
+ this.remove(document.uri);
44
+ this.fireWithDebounce();
45
+ }
46
+ });
47
+
48
+ const deleteWatcher = vscode.workspace.onDidDeleteFiles((event) => {
49
+ for (const uri of event.files) {
50
+ if (this.isFileUri(uri)) {
51
+ this.remove(uri);
52
+ }
53
+ }
54
+ this.fireWithDebounce();
55
+ });
56
+
57
+ const renameWatcher = vscode.workspace.onDidRenameFiles((event) => {
58
+ for (const { oldUri, newUri } of event.files) {
59
+ if (this.isFileUri(oldUri)) {
60
+ if (this.isFileUri(newUri)) {
61
+ this.rename(oldUri, newUri);
62
+ } else {
63
+ // The file was renamed to a non-file URI, so we should remove it.
64
+ this.remove(oldUri);
65
+ }
66
+ }
67
+ }
68
+ this.fireWithDebounce();
69
+ });
70
+
71
+ context.subscriptions.push(
72
+ editorWatcher,
73
+ selectionWatcher,
74
+ closeWatcher,
75
+ deleteWatcher,
76
+ renameWatcher,
77
+ );
78
+
79
+ // Just add current active file on start-up.
80
+ if (
81
+ vscode.window.activeTextEditor &&
82
+ this.isFileUri(vscode.window.activeTextEditor.document.uri)
83
+ ) {
84
+ this.addOrMoveToFront(vscode.window.activeTextEditor);
85
+ }
86
+ }
87
+
88
+ private isFileUri(uri: vscode.Uri): boolean {
89
+ return uri.scheme === 'file';
90
+ }
91
+
92
+ private addOrMoveToFront(editor: vscode.TextEditor) {
93
+ // Deactivate previous active file
94
+ const currentActive = this.openFiles.find((f) => f.isActive);
95
+ if (currentActive) {
96
+ currentActive.isActive = false;
97
+ currentActive.cursor = undefined;
98
+ currentActive.selectedText = undefined;
99
+ }
100
+
101
+ // Remove if it exists
102
+ const index = this.openFiles.findIndex(
103
+ (f) => f.path === editor.document.uri.fsPath,
104
+ );
105
+ if (index !== -1) {
106
+ this.openFiles.splice(index, 1);
107
+ }
108
+
109
+ // Add to the front as active
110
+ this.openFiles.unshift({
111
+ path: editor.document.uri.fsPath,
112
+ timestamp: Date.now(),
113
+ isActive: true,
114
+ });
115
+
116
+ // Enforce max length
117
+ if (this.openFiles.length > MAX_FILES) {
118
+ this.openFiles.pop();
119
+ }
120
+
121
+ this.updateActiveContext(editor);
122
+ }
123
+
124
+ private remove(uri: vscode.Uri) {
125
+ const index = this.openFiles.findIndex((f) => f.path === uri.fsPath);
126
+ if (index !== -1) {
127
+ this.openFiles.splice(index, 1);
128
+ }
129
+ }
130
+
131
+ private rename(oldUri: vscode.Uri, newUri: vscode.Uri) {
132
+ const index = this.openFiles.findIndex((f) => f.path === oldUri.fsPath);
133
+ if (index !== -1) {
134
+ this.openFiles[index].path = newUri.fsPath;
135
+ }
136
+ }
137
+
138
+ private updateActiveContext(editor: vscode.TextEditor) {
139
+ const file = this.openFiles.find(
140
+ (f) => f.path === editor.document.uri.fsPath,
141
+ );
142
+ if (!file || !file.isActive) {
143
+ return;
144
+ }
145
+
146
+ file.cursor = editor.selection.active
147
+ ? {
148
+ line: editor.selection.active.line + 1,
149
+ character: editor.selection.active.character,
150
+ }
151
+ : undefined;
152
+
153
+ let selectedText: string | undefined =
154
+ editor.document.getText(editor.selection) || undefined;
155
+ if (selectedText && selectedText.length > MAX_SELECTED_TEXT_LENGTH) {
156
+ selectedText =
157
+ selectedText.substring(0, MAX_SELECTED_TEXT_LENGTH) + '... [TRUNCATED]';
158
+ }
159
+ file.selectedText = selectedText;
160
+ }
161
+
162
+ private fireWithDebounce() {
163
+ if (this.debounceTimer) {
164
+ clearTimeout(this.debounceTimer);
165
+ }
166
+ this.debounceTimer = setTimeout(() => {
167
+ this.onDidChangeEmitter.fire();
168
+ }, 50); // 50ms
169
+ }
170
+
171
+ get state(): IdeContext {
172
+ return {
173
+ workspaceState: {
174
+ openFiles: [...this.openFiles],
175
+ },
176
+ };
177
+ }
178
+ }
projects/ui/qwen-code/packages/vscode-ide-companion/src/utils/logger.ts ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import * as vscode from 'vscode';
8
+
9
+ export function createLogger(
10
+ context: vscode.ExtensionContext,
11
+ logger: vscode.OutputChannel,
12
+ ) {
13
+ return (message: string) => {
14
+ if (context.extensionMode === vscode.ExtensionMode.Development) {
15
+ logger.appendLine(message);
16
+ }
17
+ };
18
+ }
projects/ui/qwen-code/scripts/tests/get-release-version.test.js ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
8
+ import { getReleaseVersion } from '../get-release-version';
9
+ import { execSync } from 'child_process';
10
+ import * as fs from 'fs';
11
+
12
+ vi.mock('child_process', () => ({
13
+ execSync: vi.fn(),
14
+ }));
15
+
16
+ vi.mock('fs', async (importOriginal) => {
17
+ const mod = await importOriginal();
18
+ return {
19
+ ...mod,
20
+ default: {
21
+ ...mod.default,
22
+ readFileSync: vi.fn(),
23
+ },
24
+ };
25
+ });
26
+
27
+ describe('getReleaseVersion', () => {
28
+ const originalEnv = { ...process.env };
29
+
30
+ beforeEach(() => {
31
+ vi.resetModules();
32
+ process.env = { ...originalEnv };
33
+ vi.useFakeTimers();
34
+ });
35
+
36
+ afterEach(() => {
37
+ process.env = originalEnv;
38
+ vi.clearAllMocks();
39
+ vi.useRealTimers();
40
+ });
41
+
42
+ it('should calculate nightly version when IS_NIGHTLY is true', () => {
43
+ process.env.IS_NIGHTLY = 'true';
44
+ vi.mocked(fs.default.readFileSync).mockReturnValue(
45
+ JSON.stringify({ version: '0.1.0' }),
46
+ );
47
+ // Mock git tag command to return empty (no existing nightly tags)
48
+ vi.mocked(execSync).mockReturnValue('');
49
+ const { releaseTag, releaseVersion, npmTag } = getReleaseVersion();
50
+ expect(releaseTag).toBe('v0.1.1-nightly.0');
51
+ expect(releaseVersion).toBe('0.1.1-nightly.0');
52
+ expect(npmTag).toBe('nightly');
53
+ });
54
+
55
+ it('should use manual version when provided', () => {
56
+ process.env.MANUAL_VERSION = '1.2.3';
57
+ const { releaseTag, releaseVersion, npmTag } = getReleaseVersion();
58
+ expect(releaseTag).toBe('v1.2.3');
59
+ expect(releaseVersion).toBe('1.2.3');
60
+ expect(npmTag).toBe('latest');
61
+ });
62
+
63
+ it('should prepend v to manual version if missing', () => {
64
+ process.env.MANUAL_VERSION = '1.2.3';
65
+ const { releaseTag } = getReleaseVersion();
66
+ expect(releaseTag).toBe('v1.2.3');
67
+ });
68
+
69
+ it('should handle pre-release versions correctly', () => {
70
+ process.env.MANUAL_VERSION = 'v1.2.3-beta.1';
71
+ const { releaseTag, releaseVersion, npmTag } = getReleaseVersion();
72
+ expect(releaseTag).toBe('v1.2.3-beta.1');
73
+ expect(releaseVersion).toBe('1.2.3-beta.1');
74
+ expect(npmTag).toBe('beta');
75
+ });
76
+
77
+ it('should throw an error for invalid version format', () => {
78
+ process.env.MANUAL_VERSION = '1.2';
79
+ expect(() => getReleaseVersion()).toThrow(
80
+ 'Error: Version must be in the format vX.Y.Z or vX.Y.Z-prerelease',
81
+ );
82
+ });
83
+
84
+ it('should throw an error if no version is provided for non-nightly release', () => {
85
+ expect(() => getReleaseVersion()).toThrow(
86
+ 'Error: No version specified and this is not a nightly release.',
87
+ );
88
+ });
89
+
90
+ it('should throw an error for versions with build metadata', () => {
91
+ process.env.MANUAL_VERSION = 'v1.2.3+build456';
92
+ expect(() => getReleaseVersion()).toThrow(
93
+ 'Error: Versions with build metadata (+) are not supported for releases.',
94
+ );
95
+ });
96
+ });
97
+
98
+ describe('get-release-version script', () => {
99
+ it('should print version JSON to stdout when executed directly', () => {
100
+ const expectedJson = {
101
+ releaseTag: 'v0.1.1-nightly.0',
102
+ releaseVersion: '0.1.1-nightly.0',
103
+ npmTag: 'nightly',
104
+ };
105
+ execSync.mockReturnValue(JSON.stringify(expectedJson));
106
+
107
+ const result = execSync('node scripts/get-release-version.js').toString();
108
+ expect(JSON.parse(result)).toEqual(expectedJson);
109
+ });
110
+ });
projects/ui/qwen-code/scripts/tests/test-setup.ts ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { vi } from 'vitest';
8
+
9
+ vi.mock('fs', () => ({
10
+ ...vi.importActual('fs'),
11
+ appendFileSync: vi.fn(),
12
+ }));
projects/ui/qwen-code/scripts/tests/vitest.config.ts ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { defineConfig } from 'vitest/config';
8
+
9
+ export default defineConfig({
10
+ test: {
11
+ globals: true,
12
+ environment: 'node',
13
+ include: ['scripts/tests/**/*.test.js'],
14
+ setupFiles: ['scripts/tests/test-setup.ts'],
15
+ coverage: {
16
+ provider: 'v8',
17
+ reporter: ['text', 'lcov'],
18
+ },
19
+ },
20
+ });