forked from QwenLM/qwen-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension-file-watcher.ts
More file actions
345 lines (319 loc) · 10.4 KB
/
Copy pathextension-file-watcher.ts
File metadata and controls
345 lines (319 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import * as fs from 'node:fs';
import * as path from 'node:path';
import { watch as watchFs, type FSWatcher } from 'chokidar';
import {
createDebugLogger,
isSubpath,
Storage,
type Config,
type ExtensionMutationEvent,
} from '@qwen-code/qwen-code-core';
import { ExtensionRefreshState } from './extension-refresh-state.js';
const debugLogger = createDebugLogger('EXTENSION_FILE_WATCHER');
const TOP_LEVEL_FILES = new Set(['extension-enablement.json']);
const EXTENSION_FILES = new Set([
'qwen-extension.json',
'.qwen-extension-install.json',
]);
// Keep these sets in sync with extension directory conventions. New runtime
// directories must be classified here as either content-auto-refreshable or
// package-stale.
const AUTO_REFRESH_DIRS = new Set(['commands', 'skills', 'agents']);
const STALE_DIRS = new Set(['hooks']);
type WatchEvent = 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir';
type RefreshAction = 'auto' | 'stale';
export class ExtensionFileWatcher {
private watcher?: FSWatcher;
private bootstrapWatcher?: FSWatcher;
private mutationListenerDisposer?: () => void;
private mutationSuppressionEnds = new Map<number, () => void>();
private staleFiles = new Set<string>();
private watching = false;
private watchGeneration = 0;
constructor(
private readonly config: Config,
private readonly extensionsDir = Storage.getUserExtensionsDir(),
private readonly refreshState = new ExtensionRefreshState(),
) {}
startWatching(): void {
this.stopWatching();
this.watching = true;
const generation = ++this.watchGeneration;
this.subscribeExtensionManagerMutations();
this.staleFiles = this.getStaleFiles();
const roots = this.getWatchRoots();
if (roots.length > 0) {
this.watcher = watchFs(roots, {
ignoreInitial: true,
followSymlinks: false,
awaitWriteFinish: {
stabilityThreshold: 200,
pollInterval: 50,
},
ignored: (filePath: string) => this.isIgnored(filePath),
})
.on('all', (event: string, changedPath: string) => {
if (generation !== this.watchGeneration) return;
const resolvedPath = path.resolve(changedPath);
const action = this.getRefreshAction(
event as WatchEvent,
resolvedPath,
);
let marked = false;
if (action === 'auto') {
marked = this.refreshState.markExtensionContentChanged(
'extension content files changed',
);
} else if (action === 'stale') {
marked = this.refreshState.markExtensionsChanged(
'extension files changed',
);
}
debugLogger.debug('Extension file event classified', {
event,
path: resolvedPath,
action,
marked,
});
})
.on('error', (error: unknown) => {
debugLogger.warn('Extension file watcher error:', error);
});
}
if (!fs.existsSync(this.extensionsDir)) {
this.watchExtensionsParent();
}
}
stopWatching(): void {
const watcher = this.watcher;
const bootstrapWatcher = this.bootstrapWatcher;
this.watcher = undefined;
this.bootstrapWatcher = undefined;
this.watching = false;
this.watchGeneration++;
this.mutationListenerDisposer?.();
this.mutationListenerDisposer = undefined;
this.endPendingMutationSuppressions();
watcher?.close().catch((error: unknown) => {
debugLogger.warn('Extension file watcher close error:', error);
});
bootstrapWatcher?.close().catch((error: unknown) => {
debugLogger.warn('Extension bootstrap watcher close error:', error);
});
}
restartWatching(): void {
this.startWatching();
}
private getWatchRoots(): string[] {
const roots = new Set<string>();
if (fs.existsSync(this.extensionsDir)) {
roots.add(this.extensionsDir);
}
for (const extension of this.config.getActiveExtensions()) {
if (extension.installMetadata?.type === 'link') {
const rawSource = extension.installMetadata.source;
const source = rawSource ? path.resolve(rawSource) : undefined;
if (source && fs.existsSync(source)) {
roots.add(source);
}
}
}
return [...roots];
}
private getStaleFiles(): Set<string> {
const files = new Set<string>();
for (const extension of this.config.getActiveExtensions()) {
for (const filePath of extension.contextFiles) {
files.add(path.resolve(filePath));
}
const configured = extension.config.contextFileName;
const names =
configured === undefined
? ['QWEN.md']
: Array.isArray(configured)
? configured
: [configured];
for (const name of names) {
files.add(path.resolve(extension.path, name));
}
this.addManifestFileReference(
files,
extension.path,
extension.config.hooks,
);
this.addManifestFileReference(
files,
extension.path,
extension.config.lspServers,
);
}
return files;
}
private addManifestFileReference(
files: Set<string>,
extensionPath: string,
value: unknown,
): void {
if (typeof value !== 'string') return;
files.add(
path.isAbsolute(value)
? path.resolve(value)
: path.resolve(extensionPath, value),
);
}
private watchExtensionsParent(): void {
this.closeBootstrapWatcher();
const parentDir = path.dirname(this.extensionsDir);
const dirBasename = path.basename(this.extensionsDir);
const generation = this.watchGeneration;
this.bootstrapWatcher = watchFs(parentDir, {
ignoreInitial: true,
followSymlinks: false,
depth: 0,
ignored: (filePath: string) =>
filePath !== parentDir && path.basename(filePath) !== dirBasename,
})
.on('all', (_event: string, changedPath: string) => {
if (generation !== this.watchGeneration) return;
if (path.basename(changedPath) !== dirBasename) return;
if (!fs.existsSync(this.extensionsDir)) return;
this.refreshState.markExtensionsChanged('extension directory created');
queueMicrotask(() => {
if (this.watching) {
this.restartWatching();
}
});
})
.on('error', (error: unknown) => {
debugLogger.warn('Extension bootstrap watcher error:', error);
});
}
private getRefreshAction(
event: WatchEvent,
changedPath: string,
): RefreshAction | false {
if (this.staleFiles.has(changedPath)) {
return 'stale';
}
if (changedPath === path.resolve(this.extensionsDir)) {
if (event === 'unlinkDir') {
this.watchExtensionsParent();
return 'stale';
}
return false;
}
if (isSubpath(this.extensionsDir, changedPath)) {
return this.getUserExtensionRefreshAction(event, changedPath);
}
return this.getLinkedExtensionRefreshAction(changedPath);
}
private getUserExtensionRefreshAction(
event: WatchEvent,
changedPath: string,
): RefreshAction | false {
const relative = path.relative(this.extensionsDir, changedPath);
const parts = relative.split(path.sep).filter(Boolean);
if (parts.length === 1) {
if (TOP_LEVEL_FILES.has(parts[0])) return 'stale';
if (event === 'addDir' || event === 'unlinkDir') return 'stale';
return false;
}
if (
!fs.existsSync(
path.join(this.extensionsDir, parts[0], 'qwen-extension.json'),
)
) {
return 'stale';
}
const runtimePath = parts.slice(1);
return this.getRuntimePathRefreshAction(runtimePath);
}
private getLinkedExtensionRefreshAction(
changedPath: string,
): RefreshAction | false {
for (const extension of this.config.getActiveExtensions()) {
if (extension.installMetadata?.type !== 'link') continue;
const rawSource = extension.installMetadata.source;
const source = rawSource ? path.resolve(rawSource) : undefined;
if (!source || !isSubpath(source, changedPath)) continue;
const relative = path.relative(source, changedPath);
const parts = relative.split(path.sep).filter(Boolean);
return parts.length === 0
? 'stale'
: this.getRuntimePathRefreshAction(parts);
}
return false;
}
private getRuntimePathRefreshAction(parts: string[]): RefreshAction | false {
if (EXTENSION_FILES.has(parts[0]) || STALE_DIRS.has(parts[0])) {
return 'stale';
}
if (AUTO_REFRESH_DIRS.has(parts[0])) {
return 'auto';
}
return false;
}
private isIgnored(filePath: string): boolean {
const normalized = filePath.replace(/\\/g, '/');
const searchablePath = `/${normalized}/`;
if (
searchablePath.includes('/node_modules/') ||
searchablePath.includes('/.git/')
) {
return true;
}
const basename = normalized.split('/').pop() ?? '';
return (
basename === '.DS_Store' ||
basename.endsWith('~') ||
basename.endsWith('.swp') ||
basename.endsWith('.tmp')
);
}
private subscribeExtensionManagerMutations(): void {
const manager = this.config.getExtensionManager();
this.mutationListenerDisposer = manager.addMutationListener(
(event: ExtensionMutationEvent) => {
if (event.phase === 'start') {
this.mutationSuppressionEnds.set(
event.id,
this.refreshState.beginSuppression(() =>
this.restartAfterMutation(),
),
);
return;
}
const endSuppression = this.mutationSuppressionEnds.get(event.id);
if (!endSuppression) {
return;
}
this.mutationSuppressionEnds.delete(event.id);
endSuppression();
},
);
}
private endPendingMutationSuppressions(): void {
const endSuppressions = [...this.mutationSuppressionEnds.values()];
this.mutationSuppressionEnds.clear();
for (const endSuppression of endSuppressions) {
endSuppression();
}
}
private restartAfterMutation(): void {
if (this.watching) {
this.restartWatching();
}
}
private closeBootstrapWatcher(): void {
const bootstrapWatcher = this.bootstrapWatcher;
this.bootstrapWatcher = undefined;
bootstrapWatcher?.close().catch((error: unknown) => {
debugLogger.warn('Extension bootstrap watcher close error:', error);
});
}
}