Skip to content

Commit c028d24

Browse files
authored
fix(code-index): initialize external task managers before search (Zoo-Code-Org#1725)
* fix(code-index): distinguish unloaded configuration from disabled indexing (Zoo-Code-Org#1722) * fix(code-index): clarify search readiness errors
1 parent c8c3926 commit c028d24

7 files changed

Lines changed: 232 additions & 13 deletions

File tree

‎src/core/tools/CodebaseSearchTool.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,12 +63,21 @@ export class CodebaseSearchTool extends BaseTool<"codebase_search"> {
6363
throw new Error("CodeIndexManager is not available.")
6464
}
6565

66+
// Settings defaults are not evidence that a fresh manager is explicitly disabled.
67+
// Initialization belongs to the manager's owner, not the search tool.
68+
if (!manager.isConfigurationLoaded) {
69+
throw new Error("Code Indexing configuration has not been loaded for this workspace.")
70+
}
71+
6672
if (!manager.isFeatureEnabled) {
6773
throw new Error("Code Indexing is disabled in the settings.")
6874
}
6975
if (!manager.isFeatureConfigured) {
7076
throw new Error("Code Indexing is not configured (Missing OpenAI Key or Qdrant URL).")
7177
}
78+
if (!manager.isInitialized) {
79+
throw new Error("Code Indexing is not initialized for this workspace.")
80+
}
7281

7382
const searchResults: VectorStoreSearchResult[] = await manager.searchIndex(query, directoryPrefix)
7483

‎src/core/tools/__tests__/CodebaseSearchTool.spec.ts‎

Lines changed: 65 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,15 @@ describe("CodebaseSearchTool", () => {
2525
let task: Task
2626
let context: vscode.ExtensionContext
2727
let callbacks: ToolCallbacks
28-
let manager: Pick<CodeIndexManager, "isFeatureEnabled" | "isFeatureConfigured" | "searchIndex">
28+
let manager: Pick<
29+
CodeIndexManager,
30+
| "isFeatureEnabled"
31+
| "isFeatureConfigured"
32+
| "isConfigurationLoaded"
33+
| "isInitialized"
34+
| "initialize"
35+
| "searchIndex"
36+
>
2937
let deref: ReturnType<typeof vi.fn<Task["providerRef"]["deref"]>>
3038

3139
beforeEach(() => {
@@ -61,16 +69,22 @@ describe("CodebaseSearchTool", () => {
6169
pushToolResult: vi.fn<ToolCallbacks["pushToolResult"]>(),
6270
}
6371
manager = {
72+
isConfigurationLoaded: true,
6473
isFeatureEnabled: true,
6574
isFeatureConfigured: true,
75+
isInitialized: true,
76+
initialize: vi.fn<CodeIndexManager["initialize"]>().mockResolvedValue({ requiresRestart: false }),
6677
searchIndex: vi.fn<CodeIndexManager["searchIndex"]>().mockResolvedValue([]),
6778
}
6879
vi.mocked(CodeIndexManagerRegistry.getOrCreate).mockReturnValue(manager as CodeIndexManager)
6980
vi.mocked(getWorkspacePath).mockReturnValue("/fallback")
7081
vi.mocked(vscode.workspace.asRelativePath).mockReturnValue("src/result.ts")
7182
})
7283

73-
afterEach(() => vi.restoreAllMocks())
84+
afterEach(() => {
85+
expect(manager.initialize).not.toHaveBeenCalled()
86+
vi.restoreAllMocks()
87+
})
7488

7589
function result(overrides: Partial<VectorStoreSearchResult> = {}): VectorStoreSearchResult {
7690
return {
@@ -174,7 +188,27 @@ describe("CodebaseSearchTool", () => {
174188
expect(task.say).not.toHaveBeenCalled()
175189
})
176190

177-
it("reports disabled indexing without searching", async () => {
191+
it("reports configuration that has never loaded before checking settings or services", async () => {
192+
Object.defineProperties(manager, {
193+
isConfigurationLoaded: { value: false },
194+
isFeatureEnabled: { value: false },
195+
isFeatureConfigured: { value: false },
196+
isInitialized: { value: false },
197+
})
198+
199+
await tool.execute({ query }, task, callbacks)
200+
201+
expect(callbacks.handleError).toHaveBeenCalledExactlyOnceWith(
202+
toolNamesSchema.enum.codebase_search,
203+
new Error("Code Indexing configuration has not been loaded for this workspace."),
204+
)
205+
expect(manager.initialize).not.toHaveBeenCalled()
206+
expect(manager.searchIndex).not.toHaveBeenCalled()
207+
expect(callbacks.pushToolResult).not.toHaveBeenCalled()
208+
})
209+
210+
it.each([true, false])("reports disabled indexing without searching (initialized: %s)", async (initialized) => {
211+
Object.defineProperty(manager, "isInitialized", { value: initialized })
178212
Object.defineProperty(manager, "isFeatureEnabled", { value: false })
179213

180214
await tool.execute({ query }, task, callbacks)
@@ -190,20 +224,38 @@ describe("CodebaseSearchTool", () => {
190224
expect(task.say).not.toHaveBeenCalled()
191225
})
192226

193-
it("reports missing index configuration without searching", async () => {
194-
Object.defineProperty(manager, "isFeatureConfigured", { value: false })
227+
it.each([true, false])(
228+
"reports missing index configuration without searching (initialized: %s)",
229+
async (initialized) => {
230+
Object.defineProperty(manager, "isInitialized", { value: initialized })
231+
Object.defineProperty(manager, "isFeatureConfigured", { value: false })
232+
233+
await tool.execute({ query }, task, callbacks)
234+
235+
expect(callbacks.handleError).toHaveBeenCalledExactlyOnceWith(
236+
toolNamesSchema.enum.codebase_search,
237+
new Error("Code Indexing is not configured (Missing OpenAI Key or Qdrant URL)."),
238+
)
239+
expect(callbacks.pushToolResult).not.toHaveBeenCalled()
240+
expect(task.consecutiveMistakeCount).toBe(0)
241+
expect(manager.searchIndex).not.toHaveBeenCalled()
242+
expect(vscode.workspace.asRelativePath).not.toHaveBeenCalled()
243+
expect(task.say).not.toHaveBeenCalled()
244+
},
245+
)
246+
247+
it("reports configured but unready services without initializing or searching", async () => {
248+
Object.defineProperty(manager, "isInitialized", { value: false })
195249

196250
await tool.execute({ query }, task, callbacks)
197251

252+
expect(manager.initialize).not.toHaveBeenCalled()
198253
expect(callbacks.handleError).toHaveBeenCalledExactlyOnceWith(
199254
toolNamesSchema.enum.codebase_search,
200-
new Error("Code Indexing is not configured (Missing OpenAI Key or Qdrant URL)."),
255+
new Error("Code Indexing is not initialized for this workspace."),
201256
)
202-
expect(callbacks.pushToolResult).not.toHaveBeenCalled()
203-
expect(task.consecutiveMistakeCount).toBe(0)
204257
expect(manager.searchIndex).not.toHaveBeenCalled()
205-
expect(vscode.workspace.asRelativePath).not.toHaveBeenCalled()
206-
expect(task.say).not.toHaveBeenCalled()
258+
expect(callbacks.pushToolResult).not.toHaveBeenCalled()
207259
})
208260

209261
it.each([undefined, "src", ""])(
@@ -214,6 +266,7 @@ describe("CodebaseSearchTool", () => {
214266
return []
215267
})
216268
await tool.execute({ query, path }, task, callbacks)
269+
expect(CodeIndexManagerRegistry.getOrCreate).toHaveBeenCalledExactlyOnceWith(context, "/task")
217270
expect(manager.searchIndex).toHaveBeenCalledExactlyOnceWith(query, path)
218271
expect(callbacks.pushToolResult).toHaveBeenCalledExactlyOnceWith(
219272
`No relevant code snippets found for the query: "${query}"`,
@@ -253,6 +306,8 @@ describe("CodebaseSearchTool", () => {
253306
.mockReturnValueOnce("src/result.ts")
254307
.mockReturnValueOnce("lib/other.ts")
255308
await tool.execute({ query }, task, callbacks)
309+
expect(CodeIndexManagerRegistry.getOrCreate).toHaveBeenCalledExactlyOnceWith(context, "/task")
310+
expect(manager.searchIndex).toHaveBeenCalledExactlyOnceWith(query, undefined)
256311
expect(vscode.workspace.asRelativePath).toHaveBeenCalledTimes(2)
257312
expect(vscode.workspace.asRelativePath).toHaveBeenNthCalledWith(1, "/task/src/result.ts", false)
258313
expect(vscode.workspace.asRelativePath).toHaveBeenNthCalledWith(2, "/task/lib/other.ts", false)

‎src/core/tools/__tests__/CodebaseSearchTool.workspace.spec.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ vi.mock("../../../services/code-index/manager", () => ({
1919
CodeIndexManager: vi.fn().mockImplementation(function (workspacePath: string) {
2020
let initialized = false
2121
return {
22+
get isConfigurationLoaded() {
23+
return initialized
24+
},
2225
get isInitialized() {
2326
return initialized
2427
},
@@ -184,7 +187,7 @@ describe("CodebaseSearchTool workspace selection", () => {
184187
expect(callbacks.pushToolResult).toHaveBeenCalledTimes(3)
185188
})
186189

187-
it("creates a manager for an external task path without initializing it", async () => {
190+
it("reports a fresh external task manager as uninitialized without initializing or searching", async () => {
188191
Object.defineProperty(task, "cwd", { value: "/external-task" })
189192

190193
await new CodebaseSearchTool().execute({ query: "external match" }, task, callbacks)
@@ -201,9 +204,24 @@ describe("CodebaseSearchTool workspace selection", () => {
201204
expect(getWorkspacePath).not.toHaveBeenCalled()
202205
expect(callbacks.handleError).toHaveBeenCalledExactlyOnceWith(
203206
toolNamesSchema.enum.codebase_search,
204-
new Error("Code Indexing is disabled in the settings."),
207+
new Error("Code Indexing configuration has not been loaded for this workspace."),
205208
)
206209
expect(callbacks.pushToolResult).not.toHaveBeenCalled()
207210
expect(task.say).not.toHaveBeenCalled()
208211
})
212+
213+
it("searches an initialized external manager while background indexing is ongoing", async () => {
214+
Object.defineProperty(task, "cwd", { value: "/external-task" })
215+
const manager = CodeIndexManagerRegistry.getOrCreate(provider.context, task.cwd)!
216+
await manager.initialize(provider.contextProxy)
217+
vi.mocked(manager.initialize).mockClear()
218+
Object.defineProperty(manager, "state", { get: () => "Indexing" })
219+
220+
await new CodebaseSearchTool().execute({ query: "external match" }, task, callbacks)
221+
222+
expect(manager.state).toBe("Indexing")
223+
expect(manager.initialize).not.toHaveBeenCalled()
224+
expect(manager.searchIndex).toHaveBeenCalledExactlyOnceWith("external match", undefined)
225+
expect(callbacks.handleError).not.toHaveBeenCalled()
226+
})
209227
})

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

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,67 @@ describe("CodeIndexConfigManager", () => {
115115
})
116116

117117
describe("loadConfiguration", () => {
118+
it("does not mark the synchronous constructor snapshot as loaded", () => {
119+
expect(configManager.isConfigurationLoaded).toBe(false)
120+
})
121+
122+
it("marks disabled configuration loaded only after secrets refresh completes", async () => {
123+
let finishRefresh!: () => void
124+
mockContextProxy.refreshSecrets.mockReturnValue(
125+
new Promise<void>((resolve) => {
126+
finishRefresh = resolve
127+
}),
128+
)
129+
130+
const loading = configManager.loadConfiguration()
131+
expect(configManager.isConfigurationLoaded).toBe(false)
132+
finishRefresh()
133+
await loading
134+
expect(configManager.isConfigurationLoaded).toBe(true)
135+
expect(configManager.isFeatureEnabled).toBe(false)
136+
})
137+
138+
it("marks enabled but unconfigured settings as loaded", async () => {
139+
mockContextProxy.getGlobalState.mockReturnValue({ codebaseIndexEnabled: true })
140+
await configManager.loadConfiguration()
141+
expect(configManager.isConfigurationLoaded).toBe(true)
142+
expect(configManager.isFeatureEnabled).toBe(true)
143+
expect(configManager.isFeatureConfigured).toBe(false)
144+
})
145+
146+
it.each(["secrets", "configuration", "restart", "payload"] as const)(
147+
"retains the last successful load state when %s fails",
148+
async (stage) => {
149+
const error = new Error(`${stage} failed`)
150+
const failNextLoad = () => {
151+
if (stage === "secrets") {
152+
mockContextProxy.refreshSecrets.mockRejectedValueOnce(error)
153+
} else if (stage === "configuration") {
154+
mockContextProxy.getGlobalState.mockImplementationOnce(() => {
155+
throw error
156+
})
157+
} else if (stage === "restart") {
158+
vi.spyOn(configManager, "doesConfigChangeRequireRestart").mockImplementationOnce(() => {
159+
throw error
160+
})
161+
} else {
162+
vi.spyOn(configManager, "currentSearchMinScore", "get").mockImplementationOnce(() => {
163+
throw error
164+
})
165+
}
166+
}
167+
168+
failNextLoad()
169+
await expect(configManager.loadConfiguration()).rejects.toThrow(error)
170+
expect(configManager.isConfigurationLoaded).toBe(false)
171+
await configManager.loadConfiguration()
172+
expect(configManager.isConfigurationLoaded).toBe(true)
173+
failNextLoad()
174+
await expect(configManager.loadConfiguration()).rejects.toThrow(error)
175+
expect(configManager.isConfigurationLoaded).toBe(true)
176+
},
177+
)
178+
118179
it("should load default configuration when no state exists", async () => {
119180
mockContextProxy.getGlobalState.mockReturnValue(undefined)
120181
mockContextProxy.getSecret.mockReturnValue(undefined)

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

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { ContextProxy } from "../../../core/config/ContextProxy"
2+
import { makeExtensionContext } from "../../../test-utils/vscode"
13
import { CodeIndexManager } from "../manager"
24
import { CodeIndexManagerRegistry } from "../code-index-manager-registry"
35
import { CodeIndexServiceFactory } from "../service-factory"
@@ -168,6 +170,66 @@ describe("CodeIndexManager - handleSettingsChange regression", () => {
168170
CodeIndexManagerRegistry.disposeAll()
169171
})
170172

173+
describe("configuration readiness", () => {
174+
it("does not regain readiness when a detached configuration finishes loading", async () => {
175+
let finishRefresh!: () => void
176+
const contextProxy = new ContextProxy(makeExtensionContext())
177+
vi.spyOn(contextProxy, "getGlobalState").mockReturnValue({ codebaseIndexEnabled: false })
178+
vi.spyOn(contextProxy, "getSecret").mockReturnValue(undefined)
179+
vi.spyOn(contextProxy, "refreshSecrets").mockReturnValue(
180+
new Promise<void>((resolve) => {
181+
finishRefresh = resolve
182+
}),
183+
)
184+
185+
const initialization = manager.initialize(contextProxy)
186+
expect(manager.isConfigurationLoaded).toBe(false)
187+
await manager.recoverFromError()
188+
finishRefresh()
189+
await initialization
190+
expect(manager.isConfigurationLoaded).toBe(false)
191+
})
192+
193+
it("keeps failed configuration unloaded until a settings refresh succeeds", async () => {
194+
const error = new Error("secrets refresh failed")
195+
const contextProxy = new ContextProxy(makeExtensionContext())
196+
vi.spyOn(contextProxy, "getGlobalState").mockReturnValue({ codebaseIndexEnabled: false })
197+
vi.spyOn(contextProxy, "getSecret").mockReturnValue(undefined)
198+
vi.spyOn(contextProxy, "refreshSecrets").mockRejectedValueOnce(error).mockResolvedValue(undefined)
199+
200+
await expect(manager.initialize(contextProxy)).rejects.toThrow(error)
201+
expect(manager.isConfigurationLoaded).toBe(false)
202+
await manager.handleSettingsChange()
203+
expect(manager.isConfigurationLoaded).toBe(true)
204+
expect(manager.isInitialized).toBe(false)
205+
})
206+
207+
it("marks disabled configuration loaded only after secrets refresh completes", async () => {
208+
let finishRefresh!: () => void
209+
const refresh = new Promise<void>((resolve) => {
210+
finishRefresh = resolve
211+
})
212+
const contextProxy = new ContextProxy(makeExtensionContext())
213+
vi.spyOn(contextProxy, "getGlobalState").mockReturnValue({ codebaseIndexEnabled: false })
214+
vi.spyOn(contextProxy, "getSecret").mockReturnValue(undefined)
215+
vi.spyOn(contextProxy, "refreshSecrets").mockReturnValue(refresh)
216+
217+
expect(manager.isConfigurationLoaded).toBe(false)
218+
const initialization = manager.initialize(contextProxy)
219+
expect(contextProxy.refreshSecrets).toHaveBeenCalledOnce()
220+
expect(manager.isConfigurationLoaded).toBe(false)
221+
finishRefresh()
222+
await initialization
223+
224+
expect(manager.isConfigurationLoaded).toBe(true)
225+
expect(manager.isFeatureEnabled).toBe(false)
226+
expect(manager.isInitialized).toBe(false)
227+
228+
await manager.recoverFromError()
229+
expect(manager.isConfigurationLoaded).toBe(false)
230+
})
231+
})
232+
171233
describe("handleSettingsChange", () => {
172234
it("should log background indexing failures", async () => {
173235
const indexingError = new Error("indexing startup failed")

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

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,13 @@ import { providerIdentifiers } from "@roo-code/types/provider-identifiers"
1111
* Handles loading, validating, and providing access to configuration values.
1212
*/
1313
export class CodeIndexConfigManager {
14+
private _isConfigurationLoaded = false
15+
16+
/** Whether at least one full asynchronous configuration load has succeeded. */
17+
public get isConfigurationLoaded(): boolean {
18+
return this._isConfigurationLoaded
19+
}
20+
1421
private codebaseIndexEnabled: boolean = false
1522
private embedderProvider: EmbedderProvider = providerIdentifiers.openai
1623
private modelId?: string
@@ -207,7 +214,7 @@ export class CodeIndexConfigManager {
207214

208215
const requiresRestart = this.doesConfigChangeRequireRestart(previousConfigSnapshot)
209216

210-
return {
217+
const result = {
211218
configSnapshot: previousConfigSnapshot,
212219
currentConfig: {
213220
isConfigured: this.isConfigured(),
@@ -228,6 +235,8 @@ export class CodeIndexConfigManager {
228235
},
229236
requiresRestart,
230237
}
238+
this._isConfigurationLoaded = true
239+
return result
231240
}
232241

233242
/**

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,11 @@ export class CodeIndexManager {
103103
return this._configManager?.isFeatureConfigured ?? false
104104
}
105105

106+
/** Whether configuration loading has succeeded, independently of service or indexing readiness. */
107+
public get isConfigurationLoaded(): boolean {
108+
return this._configManager?.isConfigurationLoaded ?? false
109+
}
110+
106111
public get isInitialized(): boolean {
107112
try {
108113
this.assertInitialized()

0 commit comments

Comments
 (0)