Skip to content

Commit 78c712a

Browse files
zoomote[bot]roomote
andauthored
[Fix] Background service failures can surface as unhandled rejections (#1352)
* fix(services): handle background promise failures * test(code-index): cover threshold batch cleanup --------- Co-authored-by: Roomote <[email protected]>
1 parent 87077e1 commit 78c712a

7 files changed

Lines changed: 88 additions & 8 deletions

File tree

‎src/eslint.config.mjs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ export default [
5959
"core/tools/**/*.ts",
6060
"core/webview/**/*.ts",
6161
"integrations/**/*.ts",
62+
"services/**/*.ts",
6263
],
6364
languageOptions: {
6465
parserOptions: {

‎src/services/code-index/__tests__/manager.spec.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,25 @@ describe("CodeIndexManager - handleSettingsChange regression", () => {
168168
})
169169

170170
describe("handleSettingsChange", () => {
171+
it("should log background indexing failures", async () => {
172+
const indexingError = new Error("indexing startup failed")
173+
const startIndexing = vi.fn().mockRejectedValue(indexingError)
174+
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined)
175+
Object.defineProperty(manager, "_orchestrator", {
176+
value: { startIndexing, stopIndexing: vi.fn() },
177+
configurable: true,
178+
})
179+
180+
manager["startIndexingInBackground"]()
181+
await Promise.resolve()
182+
183+
expect(consoleErrorSpy).toHaveBeenCalledWith(
184+
"[CodeIndexManager] Background indexing failed:",
185+
indexingError,
186+
)
187+
consoleErrorSpy.mockRestore()
188+
})
189+
171190
it("should not throw when called on uninitialized manager (regression test)", async () => {
172191
// This is the core regression test: handleSettingsChange() should not throw
173192
// when called before the manager is initialized (during first-time configuration)

‎src/services/code-index/manager.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,13 +227,19 @@ export class CodeIndexManager {
227227
(needsServiceRecreation && (!this._orchestrator || this._orchestrator.state !== "Indexing"))
228228

229229
if (shouldStartOrRestartIndexing) {
230-
this._orchestrator?.startIndexing()
230+
this.startIndexingInBackground()
231231
}
232232
}
233233

234234
return { requiresRestart }
235235
}
236236

237+
private startIndexingInBackground(): void {
238+
void this._orchestrator?.startIndexing().catch((error) => {
239+
console.error("[CodeIndexManager] Background indexing failed:", error)
240+
})
241+
}
242+
237243
/**
238244
* Initiates the indexing process (initial scan and starts watcher).
239245
* Automatically recovers from error state if needed before starting.

‎src/services/code-index/processors/__tests__/scanner.spec.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,36 @@ describe("DirectoryScanner", () => {
220220
expect(mockVectorStore.upsertPoints).toHaveBeenCalled()
221221
})
222222

223+
it("should clean up a threshold-triggered batch", async () => {
224+
const thresholdScanner = new DirectoryScanner(
225+
mockEmbedder,
226+
mockVectorStore,
227+
mockCodeParser,
228+
mockCacheManager,
229+
mockIgnoreInstance,
230+
1,
231+
)
232+
const { listFiles } = await import("../../../glob/list-files")
233+
vi.mocked(listFiles).mockResolvedValue([["test/file1.js"], false])
234+
mockCodeParser.parseFile.mockResolvedValue([
235+
{
236+
file_path: "test/file1.js",
237+
content: "test content",
238+
start_line: 1,
239+
end_line: 5,
240+
identifier: "test",
241+
type: "function",
242+
fileHash: "hash",
243+
segmentHash: "threshold-segment",
244+
},
245+
])
246+
247+
await thresholdScanner.scanDirectory("/test")
248+
249+
expect(mockEmbedder.createEmbeddings).toHaveBeenCalledTimes(1)
250+
expect(mockVectorStore.upsertPoints).toHaveBeenCalledTimes(1)
251+
})
252+
223253
it("should delete points for removed files", async () => {
224254
;(mockCacheManager.getAllHashes as any).mockReturnValue({ "old/file.js": "old-hash" })
225255

‎src/services/code-index/processors/scanner.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -216,10 +216,11 @@ export class DirectoryScanner implements IDirectoryScanner {
216216
activeBatchPromises.add(batchPromise)
217217

218218
// Clean up completed promises to prevent memory accumulation
219-
batchPromise.finally(() => {
219+
const cleanupBatch = () => {
220220
activeBatchPromises.delete(batchPromise)
221221
pendingBatchCount--
222-
})
222+
}
223+
void batchPromise.then(cleanupBatch, cleanupBatch)
223224
}
224225
} finally {
225226
release()
@@ -306,10 +307,11 @@ export class DirectoryScanner implements IDirectoryScanner {
306307
activeBatchPromises.add(batchPromise)
307308

308309
// Clean up completed promises to prevent memory accumulation
309-
batchPromise.finally(() => {
310+
const cleanupBatch = () => {
310311
activeBatchPromises.delete(batchPromise)
311312
pendingBatchCount--
312-
})
313+
}
314+
void batchPromise.then(cleanupBatch, cleanupBatch)
313315
} finally {
314316
release()
315317
}

‎src/services/mcp/McpHub.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,9 @@ export class McpHub {
176176
if (secretStorage) {
177177
this.secretStorage = secretStorage
178178
}
179-
this.watchMcpSettingsFile()
179+
void this.watchMcpSettingsFile().catch((error) => {
180+
console.error("[McpHub] Failed to watch MCP settings file:", error)
181+
})
180182
this.watchProjectMcpFile().catch(console.error)
181183
this.setupWorkspaceFoldersWatcher()
182184
this.initializationPromise = Promise.all([

‎src/services/mcp/__tests__/McpHub.spec.ts‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ import { ServerConfigSchema, McpHub } from "../McpHub"
1010
import { OAUTH_FLOW_TIMEOUT_MS } from "../constants"
1111
import { t } from "../../../i18n"
1212

13+
type McpHubPrivate = {
14+
watchMcpSettingsFile: () => Promise<void>
15+
}
16+
1317
// Mock fs/promises before importing anything that uses it.
1418
// Named exports and the default export must share the same vi.fn() instances so that
1519
// `import * as fs` (used by McpHub.ts) and `import fs` (default) both see the same mocks.
@@ -192,6 +196,22 @@ describe("McpHub", () => {
192196
}
193197
})
194198

199+
it("should log settings watcher startup failures", async () => {
200+
const watcherError = new Error("watcher startup failed")
201+
const watchSpy = vi
202+
.spyOn(McpHub.prototype as unknown as McpHubPrivate, "watchMcpSettingsFile")
203+
.mockRejectedValueOnce(watcherError)
204+
vi.mocked(console.error).mockClear()
205+
206+
const failingHub = new McpHub(mockProvider as ClineProvider)
207+
await failingHub.waitUntilReady()
208+
await Promise.resolve()
209+
210+
expect(console.error).toHaveBeenCalledWith("[McpHub] Failed to watch MCP settings file:", watcherError)
211+
await failingHub.dispose()
212+
watchSpy.mockRestore()
213+
})
214+
195215
describe("Discriminated union type handling", () => {
196216
it("should create connected connections with proper type", async () => {
197217
// Mock StdioClientTransport
@@ -2526,7 +2546,7 @@ describe("McpHub", () => {
25262546
})
25272547

25282548
mockSecretStorage.onDidChange.mockImplementation((_key: string, cb: () => void) => {
2529-
Promise.resolve().then(() => {
2549+
queueMicrotask(() => {
25302550
mockSecretStorage.getOAuthData.mockResolvedValue({
25312551
expires_at: Date.now() + 10 * 60 * 1000,
25322552
})
@@ -2811,7 +2831,7 @@ describe("McpHub", () => {
28112831
})
28122832

28132833
mockSecretStorage.onDidChange.mockImplementation((_key: string, cb: () => void) => {
2814-
Promise.resolve().then(() => {
2834+
queueMicrotask(() => {
28152835
// Dispose the hub before the token callback runs
28162836
;(mcpHub as any).isDisposed = true
28172837
mockSecretStorage.getOAuthData.mockResolvedValue({

0 commit comments

Comments
 (0)