forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanager.ts
More file actions
289 lines (261 loc) · 9.83 KB
/
Copy pathmanager.ts
File metadata and controls
289 lines (261 loc) · 9.83 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
import { logForDebugging } from '../../utils/debug.js'
import { isBareMode } from '../../utils/envUtils.js'
import { errorMessage } from '../../utils/errors.js'
import { logError } from '../../utils/log.js'
import {
createLSPServerManager,
type LSPServerManager,
} from './LSPServerManager.js'
import { registerLSPNotificationHandlers } from './passiveFeedback.js'
/**
* Initialization state of the LSP server manager
*/
type InitializationState = 'not-started' | 'pending' | 'success' | 'failed'
/**
* Global singleton instance of the LSP server manager.
* Initialized during Claude Code startup.
*/
let lspManagerInstance: LSPServerManager | undefined
/**
* Current initialization state
*/
let initializationState: InitializationState = 'not-started'
/**
* Error from last initialization attempt, if any
*/
let initializationError: Error | undefined
/**
* Generation counter to prevent stale initialization promises from updating state
*/
let initializationGeneration = 0
/**
* Promise that resolves when initialization completes (success or failure)
*/
let initializationPromise: Promise<void> | undefined
/**
* Test-only sync reset. shutdownLspServerManager() is async and tears down
* real connections; this only clears the module-scope singleton state so
* reinitializeLspServerManager() early-returns on 'not-started' in downstream
* tests on the same shard.
*/
export function _resetLspManagerForTesting(): void {
initializationState = 'not-started'
initializationError = undefined
initializationPromise = undefined
initializationGeneration++
}
/**
* Get the singleton LSP server manager instance.
* Returns undefined if not yet initialized, initialization failed, or still pending.
*
* Callers should check for undefined and handle gracefully, as initialization happens
* asynchronously during Claude Code startup. Use getInitializationStatus() to
* distinguish between pending, failed, and not-started states.
*/
export function getLspServerManager(): LSPServerManager | undefined {
// Don't return a broken instance if initialization failed
if (initializationState === 'failed') {
return undefined
}
return lspManagerInstance
}
/**
* Get the current initialization status of the LSP server manager.
*
* @returns Status object with current state and error (if failed)
*/
export function getInitializationStatus():
| { status: 'not-started' }
| { status: 'pending' }
| { status: 'success' }
| { status: 'failed'; error: Error } {
if (initializationState === 'failed') {
return {
status: 'failed',
error: initializationError || new Error('Initialization failed'),
}
}
if (initializationState === 'not-started') {
return { status: 'not-started' }
}
if (initializationState === 'pending') {
return { status: 'pending' }
}
return { status: 'success' }
}
/**
* Check whether at least one language server is connected and healthy.
* Backs LSPTool.isEnabled().
*/
export function isLspConnected(): boolean {
if (initializationState === 'failed') return false
const manager = getLspServerManager()
if (!manager) return false
const servers = manager.getAllServers()
if (servers.size === 0) return false
for (const server of servers.values()) {
if (server.state !== 'error') return true
}
return false
}
/**
* Wait for LSP server manager initialization to complete.
*
* Returns immediately if initialization has already completed (success or failure).
* If initialization is pending, waits for it to complete.
* If initialization hasn't started, returns immediately.
*
* @returns Promise that resolves when initialization is complete
*/
export async function waitForInitialization(): Promise<void> {
// If already initialized or failed, return immediately
if (initializationState === 'success' || initializationState === 'failed') {
return
}
// If pending and we have a promise, wait for it
if (initializationState === 'pending' && initializationPromise) {
await initializationPromise
}
// If not started, return immediately (nothing to wait for)
}
/**
* Initialize the LSP server manager singleton.
*
* This function is called during Claude Code startup. It synchronously creates
* the manager instance, then starts async initialization (loading LSP configs)
* in the background without blocking the startup process.
*
* Safe to call multiple times - will only initialize once (idempotent).
* However, if initialization previously failed, calling again will retry.
*/
export function initializeLspServerManager(): void {
// --bare / SIMPLE: no LSP. LSP is for editor integration (diagnostics,
// hover, go-to-def in the REPL). Scripted -p calls have no use for it.
if (isBareMode()) {
return
}
logForDebugging('[LSP MANAGER] initializeLspServerManager() called')
// Skip if already initialized or currently initializing
if (lspManagerInstance !== undefined && initializationState !== 'failed') {
logForDebugging(
'[LSP MANAGER] Already initialized or initializing, skipping',
)
return
}
// Reset state for retry if previous initialization failed
if (initializationState === 'failed') {
lspManagerInstance = undefined
initializationError = undefined
}
// Create the manager instance and mark as pending
lspManagerInstance = createLSPServerManager()
initializationState = 'pending'
logForDebugging('[LSP MANAGER] Created manager instance, state=pending')
// Increment generation to invalidate any pending initializations
const currentGeneration = ++initializationGeneration
logForDebugging(
`[LSP MANAGER] Starting async initialization (generation ${currentGeneration})`,
)
// Start initialization asynchronously without blocking
// Store the promise so callers can await it via waitForInitialization()
initializationPromise = lspManagerInstance
.initialize()
.then(() => {
// Only update state if this is still the current initialization
if (currentGeneration === initializationGeneration) {
initializationState = 'success'
logForDebugging('LSP server manager initialized successfully')
// Register passive notification handlers for diagnostics
if (lspManagerInstance) {
registerLSPNotificationHandlers(lspManagerInstance)
}
}
})
.catch((error: unknown) => {
// Only update state if this is still the current initialization
if (currentGeneration === initializationGeneration) {
initializationState = 'failed'
initializationError = error as Error
// Clear the instance since it's not usable
lspManagerInstance = undefined
logError(error as Error)
logForDebugging(
`Failed to initialize LSP server manager: ${errorMessage(error)}`,
)
}
})
}
/**
* Force re-initialization of the LSP server manager, even after a prior
* successful init. Called from refreshActivePlugins() after plugin caches
* are cleared, so newly-loaded plugin LSP servers are picked up.
*
* Fixes https://github.com/anthropics/claude-code/issues/15521:
* loadAllPlugins() is memoized and can be called very early in startup
* (via getCommands prefetch in setup.ts) before marketplaces are reconciled,
* caching an empty plugin list. initializeLspServerManager() then reads that
* stale memoized result and initializes with 0 servers. Unlike commands/agents/
* hooks/MCP, LSP was never re-initialized on plugin refresh.
*
* Safe to call when no LSP plugins changed: initialize() is just config
* parsing (servers are lazy-started on first use). Also safe during pending
* init: the generation counter invalidates the in-flight promise.
*/
export function reinitializeLspServerManager(): void {
if (initializationState === 'not-started') {
// initializeLspServerManager() was never called (e.g. headless subcommand
// path). Don't start it now.
return
}
logForDebugging('[LSP MANAGER] reinitializeLspServerManager() called')
// Best-effort shutdown of any running servers on the old instance so
// /reload-plugins doesn't leak child processes. Fire-and-forget: the
// primary use case (issue #15521) has 0 servers so this is usually a no-op.
if (lspManagerInstance) {
void lspManagerInstance.shutdown().catch(err => {
logForDebugging(
`[LSP MANAGER] old instance shutdown during reinit failed: ${errorMessage(err)}`,
)
})
}
// Force the idempotence check in initializeLspServerManager() to fall
// through. Generation counter handles invalidating any in-flight init.
lspManagerInstance = undefined
initializationState = 'not-started'
initializationError = undefined
initializeLspServerManager()
}
/**
* Shutdown the LSP server manager and clean up resources.
*
* This should be called during Claude Code shutdown. Stops all running LSP servers
* and clears internal state. Safe to call when not initialized (no-op).
*
* NOTE: Errors during shutdown are logged for monitoring but NOT propagated to the caller.
* State is always cleared even if shutdown fails, to prevent resource accumulation.
* This is acceptable during application exit when recovery is not possible.
*
* @returns Promise that resolves when shutdown completes (errors are swallowed)
*/
export async function shutdownLspServerManager(): Promise<void> {
if (lspManagerInstance === undefined) {
return
}
try {
await lspManagerInstance.shutdown()
logForDebugging('LSP server manager shut down successfully')
} catch (error: unknown) {
logError(error as Error)
logForDebugging(
`Failed to shutdown LSP server manager: ${errorMessage(error)}`,
)
} finally {
// Always clear state even if shutdown failed
lspManagerInstance = undefined
initializationState = 'not-started'
initializationError = undefined
initializationPromise = undefined
// Increment generation to invalidate any pending initializations
initializationGeneration++
}
}