GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — claude-code-source-code/src/services/diagnosticTracking.ts at main · schelling/claude-code-source-code Expand file tree/ Copy pathdiagnosticTracking.tsMore file actions 397 lines (349 loc) · 12 KB / Copy pathdiagnosticTracking.tsFile metadata and controls397 lines (349 loc) · 12 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 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 import figures from 'figures' import { logError } from 'src/utils/log.js' import { callIdeRpc } from '../services/mcp/client.js' import type { MCPServerConnection } from '../services/mcp/types.js' import { ClaudeError } from '../utils/errors.js' import { normalizePathForComparison, pathsEqual } from '../utils/file.js' import { getConnectedIdeClient } from '../utils/ide.js' import { jsonParse } from '../utils/slowOperations.js' class DiagnosticsTrackingError extends ClaudeError {} const MAX_DIAGNOSTICS_SUMMARY_CHARS = 4000 export interface Diagnostic { message: string severity: 'Error' | 'Warning' | 'Info' | 'Hint' range: { start: { line: number; character: number } end: { line: number; character: number } } source?: string code?: string } export interface DiagnosticFile { uri: string diagnostics: Diagnostic[] } export class DiagnosticTrackingService { private static instance: DiagnosticTrackingService | undefined private baseline: Map<string, Diagnostic[]> = new Map() private initialized = false private mcpClient: MCPServerConnection | undefined // Track when files were last processed/fetched private lastProcessedTimestamps: Map<string, number> = new Map() // Track which files have received right file diagnostics and if they've changed // Map<normalizedPath, lastClaudeFsRightDiagnostics> private rightFileDiagnosticsState: Map<string, Diagnostic[]> = new Map() static getInstance(): DiagnosticTrackingService { if (!DiagnosticTrackingService.instance) { DiagnosticTrackingService.instance = new DiagnosticTrackingService() } return DiagnosticTrackingService.instance } initialize(mcpClient: MCPServerConnection) { if (this.initialized) { return } // TODO: Do not cache the connected mcpClient since it can change. this.mcpClient = mcpClient this.initialized = true } async shutdown(): Promise<void> { this.initialized = false this.baseline.clear() this.rightFileDiagnosticsState.clear() this.lastProcessedTimestamps.clear() } /** * Reset tracking state while keeping the service initialized. * This clears all tracked files and diagnostics. */ reset() { this.baseline.clear() this.rightFileDiagnosticsState.clear() this.lastProcessedTimestamps.clear() } private normalizeFileUri(fileUri: string): string { // Remove our protocol prefixes const protocolPrefixes = [ 'file://', '_claude_fs_right:', '_claude_fs_left:', ] let normalized = fileUri for (const prefix of protocolPrefixes) { if (fileUri.startsWith(prefix)) { normalized = fileUri.slice(prefix.length) break } } // Use shared utility for platform-aware path normalization // (handles Windows case-insensitivity and path separators) return normalizePathForComparison(normalized) } /** * Ensure a file is opened in the IDE before processing. * This is important for language services like diagnostics to work properly. */ async ensureFileOpened(fileUri: string): Promise<void> { if ( !this.initialized || !this.mcpClient || this.mcpClient.type !== 'connected' ) { return } try { // Call the openFile tool to ensure the file is loaded await callIdeRpc( 'openFile', { filePath: fileUri, preview: false, startText: '', endText: '', selectToEndOfLine: false, makeFrontmost: false, }, this.mcpClient, ) } catch (error) { logError(error as Error) } } /** * Capture baseline diagnostics for a specific file before editing. * This is called before editing a file to ensure we have a baseline to compare against. */ async beforeFileEdited(filePath: string): Promise<void> { if ( !this.initialized || !this.mcpClient || this.mcpClient.type !== 'connected' ) { return } const timestamp = Date.now() try { const result = await callIdeRpc( 'getDiagnostics', { uri: `file://${filePath}` }, this.mcpClient, ) const diagnosticFile = this.parseDiagnosticResult(result)[0] if (diagnosticFile) { // Compare normalized paths (handles protocol prefixes and Windows case-insensitivity) if ( !pathsEqual( this.normalizeFileUri(filePath), this.normalizeFileUri(diagnosticFile.uri), ) ) { logError( new DiagnosticsTrackingError( `Diagnostics file path mismatch: expected ${filePath}, got ${diagnosticFile.uri})`, ), ) return } // Store with normalized path key for consistent lookups on Windows const normalizedPath = this.normalizeFileUri(filePath) this.baseline.set(normalizedPath, diagnosticFile.diagnostics) this.lastProcessedTimestamps.set(normalizedPath, timestamp) } else { // No diagnostic file returned, store an empty baseline const normalizedPath = this.normalizeFileUri(filePath) this.baseline.set(normalizedPath, []) this.lastProcessedTimestamps.set(normalizedPath, timestamp) } } catch (_error) { // Fail silently if IDE doesn't support diagnostics } } /** * Get new diagnostics from file://, _claude_fs_right, and _claude_fs_ URIs that aren't in the baseline. * Only processes diagnostics for files that have been edited. */ async getNewDiagnostics(): Promise<DiagnosticFile[]> { if ( !this.initialized || !this.mcpClient || this.mcpClient.type !== 'connected' ) { return [] } // Check if we have any files with diagnostic changes let allDiagnosticFiles: DiagnosticFile[] = [] try { const result = await callIdeRpc( 'getDiagnostics', {}, // Empty params fetches all diagnostics this.mcpClient, ) allDiagnosticFiles = this.parseDiagnosticResult(result) } catch (_error) { // If fetching all diagnostics fails, return empty return [] } const diagnosticsForFileUrisWithBaselines = allDiagnosticFiles .filter(file => this.baseline.has(this.normalizeFileUri(file.uri))) .filter(file => file.uri.startsWith('file://')) const diagnosticsForClaudeFsRightUrisWithBaselinesMap = new Map< string, DiagnosticFile >() allDiagnosticFiles .filter(file => this.baseline.has(this.normalizeFileUri(file.uri))) .filter(file => file.uri.startsWith('_claude_fs_right:')) .forEach(file => { diagnosticsForClaudeFsRightUrisWithBaselinesMap.set( this.normalizeFileUri(file.uri), file, ) }) const newDiagnosticFiles: DiagnosticFile[] = [] // Process file:// protocol diagnostics for (const file of diagnosticsForFileUrisWithBaselines) { const normalizedPath = this.normalizeFileUri(file.uri) const baselineDiagnostics = this.baseline.get(normalizedPath) || [] // Get the _claude_fs_right file if it exists const claudeFsRightFile = diagnosticsForClaudeFsRightUrisWithBaselinesMap.get(normalizedPath) // Determine which file to use based on the state of right file diagnostics let fileToUse = file if (claudeFsRightFile) { const previousRightDiagnostics = this.rightFileDiagnosticsState.get(normalizedPath) // Use _claude_fs_right if: // 1. We've never gotten right file diagnostics for this file (previousRightDiagnostics === undefined) // 2. OR the right file diagnostics have just changed if ( !previousRightDiagnostics || !this.areDiagnosticArraysEqual( previousRightDiagnostics, claudeFsRightFile.diagnostics, ) ) { fileToUse = claudeFsRightFile } // Update our tracking of right file diagnostics this.rightFileDiagnosticsState.set( normalizedPath, claudeFsRightFile.diagnostics, ) } // Find new diagnostics that aren't in the baseline const newDiagnostics = fileToUse.diagnostics.filter( d => !baselineDiagnostics.some(b => this.areDiagnosticsEqual(d, b)), ) if (newDiagnostics.length > 0) { newDiagnosticFiles.push({ uri: file.uri, diagnostics: newDiagnostics, }) } // Update baseline with current diagnostics this.baseline.set(normalizedPath, fileToUse.diagnostics) } return newDiagnosticFiles } private parseDiagnosticResult(result: unknown): DiagnosticFile[] { if (Array.isArray(result)) { const textBlock = result.find(block => block.type === 'text') if (textBlock && 'text' in textBlock) { const parsed = jsonParse(textBlock.text) return parsed } } return [] } private areDiagnosticsEqual(a: Diagnostic, b: Diagnostic): boolean { return ( a.message === b.message && a.severity === b.severity && a.source === b.source && a.code === b.code && a.range.start.line === b.range.start.line && a.range.start.character === b.range.start.character && a.range.end.line === b.range.end.line && a.range.end.character === b.range.end.character ) } private areDiagnosticArraysEqual(a: Diagnostic[], b: Diagnostic[]): boolean { if (a.length !== b.length) return false // Check if every diagnostic in 'a' exists in 'b' return ( a.every(diagA => b.some(diagB => this.areDiagnosticsEqual(diagA, diagB)), ) && b.every(diagB => a.some(diagA => this.areDiagnosticsEqual(diagA, diagB))) ) } /** * Handle the start of a new query. This method: * - Initializes the diagnostic tracker if not already initialized * - Resets the tracker if already initialized (for new query loops) * - Automatically finds the IDE client from the provided clients list * * @param clients Array of MCP clients that may include an IDE client * @param shouldQuery Whether a query is actually being made (not just a command) */ async handleQueryStart(clients: MCPServerConnection[]): Promise<void> { // Only proceed if we should query and have clients if (!this.initialized) { // Find the connected IDE client const connectedIdeClient = getConnectedIdeClient(clients) if (connectedIdeClient) { this.initialize(connectedIdeClient) } } else { // Reset diagnostic tracking for new query loops this.reset() } } /** * Format diagnostics into a human-readable summary string. * This is useful for displaying diagnostics in messages or logs. * * @param files Array of diagnostic files to format * @returns Formatted string representation of the diagnostics */ static formatDiagnosticsSummary(files: DiagnosticFile[]): string { const truncationMarker = '…[truncated]' const result = files .map(file => { const filename = file.uri.split('/').pop() || file.uri const diagnostics = file.diagnostics .map(d => { const severitySymbol = DiagnosticTrackingService.getSeveritySymbol( d.severity, ) return ` ${severitySymbol} [Line ${d.range.start.line + 1}:${d.range.start.character + 1}] ${d.message}${d.code ? ` [${d.code}]` : ''}${d.source ? ` (${d.source})` : ''}` }) .join('\n') return `${filename}:\n${diagnostics}` }) .join('\n\n') if (result.length > MAX_DIAGNOSTICS_SUMMARY_CHARS) { return ( result.slice( 0, MAX_DIAGNOSTICS_SUMMARY_CHARS - truncationMarker.length, ) + truncationMarker ) } return result } /** * Get the severity symbol for a diagnostic */ static getSeveritySymbol(severity: Diagnostic['severity']): string { return ( { Error: figures.cross, Warning: figures.warning, Info: figures.info, Hint: figures.star, }[severity] || figures.bullet ) } } export const diagnosticTracker = DiagnosticTrackingService.getInstance() |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |