Skip to content

Commit 312ab94

Browse files
committed
refactor(code-index): scope state ownership and workspace status delivery
1 parent c641a6f commit 312ab94

13 files changed

Lines changed: 635 additions & 76 deletions

‎src/__tests__/extension.spec.ts‎

Lines changed: 125 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ vi.mock("vscode", () => ({
1212
tabGroups: {
1313
onDidChangeTabs: vi.fn(),
1414
},
15-
onDidChangeActiveTextEditor: vi.fn(),
15+
onDidChangeActiveTextEditor: vi.fn().mockReturnValue({ dispose: vi.fn() }),
1616
},
1717
workspace: {
1818
registerTextDocumentContentProvider: vi.fn(),
@@ -205,6 +205,7 @@ vi.mock("../core/webview/ClineProvider", async () => {
205205
{
206206
// Static method used by extension.ts
207207
getVisibleInstance: vi.fn().mockReturnValue(mockInstance),
208+
getAllInstances: vi.fn().mockReturnValue([]),
208209
sideBarId: "zoo-code.SidebarProvider",
209210
},
210211
),
@@ -238,6 +239,129 @@ describe("extension.ts", () => {
238239
settingsUpdatedHandler = undefined
239240
})
240241

242+
test("initializes the code index scope and registers it for extension cleanup", async () => {
243+
vi.resetModules()
244+
const { CodeIndexScope } = await import("../services/code-index/code-index-scope")
245+
const init = vi.spyOn(CodeIndexScope.prototype, "init")
246+
const dispose = vi.spyOn(CodeIndexScope.prototype, "dispose")
247+
try {
248+
const { activate } = await import("../extension")
249+
await activate(mockContext)
250+
251+
const scopes = mockContext.subscriptions.filter((entry) => entry instanceof CodeIndexScope)
252+
expect(scopes).toHaveLength(1)
253+
expect(init).toHaveBeenCalledExactlyOnceWith()
254+
expect(init.mock.contexts[0]).toBe(scopes[0])
255+
expect(dispose).not.toHaveBeenCalled()
256+
scopes[0].dispose()
257+
expect(dispose).toHaveBeenCalledExactlyOnceWith()
258+
} finally {
259+
init.mockRestore()
260+
dispose.mockRestore()
261+
}
262+
})
263+
264+
test("publishes indexing status to matching providers and logs delivery failures", async () => {
265+
vi.resetModules()
266+
const { CodeIndexScope } = await import("../services/code-index/code-index-scope")
267+
const { ClineProvider } = await import("../core/webview/ClineProvider")
268+
const log = vi.spyOn(console, "error").mockImplementation(() => {})
269+
const provider = ClineProvider.getVisibleInstance()!
270+
Object.defineProperty(provider, "workspacePath", { configurable: true, value: "/workspace" })
271+
const getAll = vi.mocked(ClineProvider.getAllInstances)
272+
const post = vi.mocked(provider.postMessageToWebview)
273+
getAll.mockReturnValue([provider, provider])
274+
post.mockRejectedValueOnce(new Error("delivery failed")).mockResolvedValue(undefined)
275+
try {
276+
const { activate } = await import("../extension")
277+
await activate(mockContext)
278+
const scope = mockContext.subscriptions.find((entry) => entry instanceof CodeIndexScope)!
279+
const status = {
280+
systemStatus: "Standby" as const,
281+
message: "Ready",
282+
processedItems: 0,
283+
totalItems: 0,
284+
currentItemUnit: "blocks",
285+
workspacePath: "/workspace",
286+
workspaceEnabled: true,
287+
autoEnableDefault: true,
288+
}
289+
scope["statusManager"]!["publishStatus"](status)
290+
await Promise.resolve()
291+
expect(post).toHaveBeenCalledTimes(2)
292+
expect(post).toHaveBeenCalledWith({ type: "indexingStatusUpdate", values: status })
293+
expect(log).toHaveBeenCalledWith(
294+
"[CodeIndexStatusManager] Failed to publish indexing status:",
295+
expect.objectContaining({ message: "delivery failed" }),
296+
)
297+
scope.dispose()
298+
} finally {
299+
log.mockRestore()
300+
getAll.mockReturnValue([])
301+
post.mockReset()
302+
Reflect.deleteProperty(provider, "workspacePath")
303+
}
304+
})
305+
306+
test.each(["/other-workspace", undefined, ""])(
307+
"does not publish workspace metadata to a provider bound to %s",
308+
async (workspacePath) => {
309+
vi.resetModules()
310+
const { CodeIndexScope } = await import("../services/code-index/code-index-scope")
311+
const { ClineProvider } = await import("../core/webview/ClineProvider")
312+
const provider = ClineProvider.getVisibleInstance()!
313+
Object.defineProperty(provider, "workspacePath", { configurable: true, value: workspacePath })
314+
const getAll = vi.mocked(ClineProvider.getAllInstances)
315+
getAll.mockReturnValue([provider])
316+
try {
317+
const { activate } = await import("../extension")
318+
await activate(mockContext)
319+
const scope = mockContext.subscriptions.find((entry) => entry instanceof CodeIndexScope)!
320+
const status = {
321+
systemStatus: "Indexing" as const,
322+
message: "Processing confidential.ts",
323+
processedItems: 1,
324+
totalItems: 2,
325+
currentItemUnit: "files",
326+
workspacePath: "/workspace",
327+
workspaceEnabled: true,
328+
autoEnableDefault: true,
329+
}
330+
scope["statusManager"]!["publishStatus"](status)
331+
await Promise.resolve()
332+
expect(provider.postMessageToWebview).not.toHaveBeenCalled()
333+
scope.dispose()
334+
} finally {
335+
getAll.mockReturnValue([])
336+
Reflect.deleteProperty(provider, "workspacePath")
337+
}
338+
},
339+
)
340+
341+
test.each([new Error("scope initialization failed"), "scope initialization failed"])(
342+
"continues activation and logs code index scope initialization failure: %s",
343+
async (error) => {
344+
vi.resetModules()
345+
const { CodeIndexScope } = await import("../services/code-index/code-index-scope")
346+
const init = vi.spyOn(CodeIndexScope.prototype, "init").mockImplementationOnce(() => {
347+
throw error
348+
})
349+
try {
350+
const { activate } = await import("../extension")
351+
await expect(activate(mockContext)).resolves.toBeDefined()
352+
353+
const vscode = await import("vscode")
354+
const channel = vi.mocked(vscode.window.createOutputChannel).mock.results.at(-1)?.value
355+
expect(channel?.appendLine).toHaveBeenCalledWith(
356+
"[CodeIndexScope] Failed to initialize: scope initialization failed",
357+
)
358+
expect(mockContext.subscriptions.filter((entry) => entry instanceof CodeIndexScope)).toHaveLength(1)
359+
} finally {
360+
init.mockRestore()
361+
}
362+
},
363+
)
364+
241365
test("does not call dotenv.config when optional .env does not exist", async () => {
242366
vi.resetModules()
243367
vi.clearAllMocks()

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type { ToolCallbacks } from "../BaseTool"
66
import { CodebaseSearchTool } from "../CodebaseSearchTool"
77
import { CodeIndexManagerRegistry } from "../../../services/code-index/code-index-manager-registry"
88
import { CodeIndexManager } from "../../../services/code-index/manager"
9+
import { CodeIndexStateManager } from "../../../services/code-index/state-manager"
910
import { getWorkspacePath } from "../../../utils/path"
1011
import { makeExtensionContext, makeTextDocument, makeTextEditor, makeUri } from "../../../test-utils/vscode"
1112

@@ -15,6 +16,7 @@ vi.mock("vscode", () => ({
1516
Uri: { file: vi.fn() },
1617
}))
1718
vi.mock("../../../utils/path", () => ({ getWorkspacePath: vi.fn() }))
19+
vi.mock("../../../services/code-index/state-manager")
1820
vi.mock("../../../services/code-index/manager", () => ({
1921
CodeIndexManager: vi.fn().mockImplementation(function (workspacePath: string) {
2022
let initialized = false
@@ -193,6 +195,7 @@ describe("CodebaseSearchTool workspace selection", () => {
193195
"/external-task",
194196
expect.objectContaining({ fsPath: "/external-task" }),
195197
provider.context,
198+
expect.any(CodeIndexStateManager),
196199
)
197200
expect(vscode.Uri.file).toHaveBeenCalledExactlyOnceWith("/external-task")
198201
const manager = CodeIndexManagerRegistry.getOrCreate(provider.context, "/external-task")!

‎src/core/webview/ClineProvider.ts‎

Lines changed: 5 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,6 @@ import { MarketplaceManager } from "../../services/marketplace"
9292
import { ShadowCheckpointService } from "../../services/checkpoints/ShadowCheckpointService"
9393
import type { CodeIndexManager } from "../../services/code-index/manager"
9494
import { CodeIndexManagerRegistry } from "../../services/code-index/code-index-manager-registry"
95-
import type { IndexProgressUpdate } from "../../services/code-index/interfaces/manager"
9695
import { MdmService } from "../../services/mdm/MdmService"
9796
import { SkillsManager } from "../../services/skills/SkillsManager"
9897

@@ -212,8 +211,6 @@ export class ClineProvider
212211
private taskScheduler = new TaskScheduler()
213212
private static readonly delegationTransitionLocks = new Map<string, Promise<void>>()
214213
private cancelledDelegationChildIds = new Set<string>()
215-
private codeIndexStatusSubscription?: vscode.Disposable
216-
private codeIndexManager?: CodeIndexManager
217214
private _workspaceTracker?: WorkspaceTracker // workSpaceTracker read-only for access outside this class
218215
protected mcpHub?: McpHub // Change from private to protected
219216
protected skillsManager?: SkillsManager
@@ -1082,17 +1079,6 @@ export class ClineProvider
10821079
// and executes code based on the message that is received.
10831080
this.setWebviewMessageListener(webviewView.webview)
10841081

1085-
// Initialize code index status subscription for the current workspace.
1086-
this.updateCodeIndexStatusSubscription()
1087-
1088-
// Listen for active editor changes to update code index status for the
1089-
// current workspace.
1090-
const activeEditorSubscription = vscode.window.onDidChangeActiveTextEditor(() => {
1091-
// Update subscription when workspace might have changed.
1092-
this.updateCodeIndexStatusSubscription()
1093-
})
1094-
this.webviewDisposables.push(activeEditorSubscription)
1095-
10961082
// Listen for when the panel becomes visible.
10971083
// https://github.com/microsoft/vscode-discussions/discussions/840
10981084
if ("onDidChangeViewState" in webviewView) {
@@ -1130,8 +1116,6 @@ export class ClineProvider
11301116
} else {
11311117
this.log("Clearing webview resources for sidebar view")
11321118
this.clearWebviewResources()
1133-
// Reset current workspace manager reference when view is disposed
1134-
this.codeIndexManager = undefined
11351119
}
11361120
},
11371121
null,
@@ -3311,53 +3295,6 @@ export class ClineProvider
33113295
return CodeIndexManagerRegistry.getOrCreate(this.context)
33123296
}
33133297

3314-
/**
3315-
* Updates the code index status subscription to listen to the current workspace manager
3316-
*/
3317-
private updateCodeIndexStatusSubscription(): void {
3318-
// Get the current workspace manager
3319-
const currentManager = this.getCurrentWorkspaceCodeIndexManager()
3320-
3321-
// If the manager hasn't changed, no need to update subscription
3322-
if (currentManager === this.codeIndexManager) {
3323-
return
3324-
}
3325-
3326-
// Dispose the old subscription if it exists
3327-
if (this.codeIndexStatusSubscription) {
3328-
this.codeIndexStatusSubscription.dispose()
3329-
this.codeIndexStatusSubscription = undefined
3330-
}
3331-
3332-
// Update the current workspace manager reference
3333-
this.codeIndexManager = currentManager
3334-
3335-
// Subscribe to the new manager's progress updates if it exists
3336-
if (currentManager) {
3337-
this.codeIndexStatusSubscription = currentManager.onProgressUpdate((update: IndexProgressUpdate) => {
3338-
// Only send updates if this manager is still the current one
3339-
if (currentManager === this.getCurrentWorkspaceCodeIndexManager()) {
3340-
// Get the full status from the manager to ensure we have all fields correctly formatted
3341-
const fullStatus = currentManager.getCurrentStatus()
3342-
void this.postMessageToWebview({
3343-
type: "indexingStatusUpdate",
3344-
values: fullStatus,
3345-
})
3346-
}
3347-
})
3348-
3349-
if (this.view) {
3350-
this.webviewDisposables.push(this.codeIndexStatusSubscription)
3351-
}
3352-
3353-
// Send initial status for the current workspace
3354-
void this.postMessageToWebview({
3355-
type: "indexingStatusUpdate",
3356-
values: currentManager.getCurrentStatus(),
3357-
})
3358-
}
3359-
}
3360-
33613298
/**
33623299
* TaskProviderLike, TelemetryPropertiesProvider
33633300
*/
@@ -3845,6 +3782,11 @@ export class ClineProvider
38453782
}
38463783
}
38473784

3785+
/** Workspace explicitly associated with this provider, without an active-editor fallback. */
3786+
public get workspacePath(): string | undefined {
3787+
return this.currentWorkspacePath
3788+
}
3789+
38483790
public get cwd() {
38493791
return this.currentWorkspacePath || getWorkspacePath()
38503792
}

‎src/core/webview/__tests__/ClineProvider.spec.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -561,6 +561,15 @@ describe("ClineProvider", () => {
561561
})
562562
})
563563

564+
test("exposes only the explicitly associated workspace without a fallback", () => {
565+
provider["currentWorkspacePath"] = "/workspace-a"
566+
expect(provider.workspacePath).toBe("/workspace-a")
567+
provider["currentWorkspacePath"] = "/workspace-b"
568+
expect(provider.workspacePath).toBe("/workspace-b")
569+
provider["currentWorkspacePath"] = undefined
570+
expect(provider.workspacePath).toBeUndefined()
571+
})
572+
564573
test("constructor initializes correctly", () => {
565574
expect(provider).toBeInstanceOf(ClineProvider)
566575
// Since getVisibleInstance returns the last instance where view.visible is true

‎src/extension.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import { openAiCodexOAuthManager } from "./integrations/openai-codex/oauth"
3535
import { kimiCodeOAuthManager } from "./integrations/kimi-code/oauth"
3636
import { McpServerManager } from "./services/mcp/McpServerManager"
3737
import { CodeIndexManagerRegistry } from "./services/code-index/code-index-manager-registry"
38+
import { CodeIndexScope } from "./services/code-index/code-index-scope"
3839
import { MdmService } from "./services/mdm/MdmService"
3940
import { migrateSettings } from "./utils/migrateSettings"
4041
import { autoImportSettings } from "./utils/autoImportSettings"
@@ -195,6 +196,15 @@ export async function activate(context: vscode.ExtensionContext) {
195196
}),
196197
)
197198

199+
const codeIndexScope = new CodeIndexScope(context)
200+
context.subscriptions.push(codeIndexScope)
201+
try {
202+
codeIndexScope.init()
203+
} catch (error) {
204+
const message = error instanceof Error ? error.message : String(error)
205+
outputChannel.appendLine(`[CodeIndexScope] Failed to initialize: ${message}`)
206+
}
207+
198208
// Initialize code index managers for all workspace folders.
199209
if (vscode.workspace.workspaceFolders) {
200210
for (const folder of vscode.workspace.workspaceFolders) {

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

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@ import { makeExtensionContext, makeTextDocument, makeTextEditor, makeUri } from
33
import { CodeIndexManager } from "../manager"
44
import { CodeIndexManagerRegistry } from "../code-index-manager-registry"
55
import { CodeIndexWorkspaceScope } from "../code-index-workspace-scope"
6+
import { CodeIndexStateManager } from "../state-manager"
7+
8+
vi.mock("../state-manager")
69

710
vi.mock("vscode", () => ({
811
workspace: { workspaceFolders: undefined, getWorkspaceFolder: vi.fn() },
@@ -45,28 +48,28 @@ describe("CodeIndexManagerRegistry", () => {
4548

4649
it("uses the first workspace when there is no active editor", () => {
4750
CodeIndexManagerRegistry.getOrCreate(context)
48-
expect(CodeIndexManager).toHaveBeenCalledWith("/first", first.uri, context)
51+
expect(CodeIndexManager).toHaveBeenCalledWith("/first", first.uri, context, expect.any(CodeIndexStateManager))
4952
})
5053

5154
it("prefers the active editor's workspace", () => {
5255
const editor = makeTextEditor({ document: makeTextDocument({ uri: makeUri("/second/file.ts") }) })
5356
Object.defineProperty(vscode.window, "activeTextEditor", { configurable: true, value: editor })
5457
vi.mocked(vscode.workspace.getWorkspaceFolder).mockReturnValue(second)
5558
expect(CodeIndexManagerRegistry.getOrCreate(context)).toBeDefined()
56-
expect(CodeIndexManager).toHaveBeenCalledWith("/second", second.uri, context)
59+
expect(CodeIndexManager).toHaveBeenCalledWith("/second", second.uri, context, expect.any(CodeIndexStateManager))
5760
})
5861

5962
it("falls back to the first workspace for an editor outside all folders", () => {
6063
Object.defineProperty(vscode.window, "activeTextEditor", { configurable: true, value: makeTextEditor() })
6164
CodeIndexManagerRegistry.getOrCreate(context)
62-
expect(CodeIndexManager).toHaveBeenCalledWith("/first", first.uri, context)
65+
expect(CodeIndexManager).toHaveBeenCalledWith("/first", first.uri, context, expect.any(CodeIndexStateManager))
6366
})
6467

6568
it("gives an explicit path priority over the active editor", () => {
6669
Object.defineProperty(vscode.window, "activeTextEditor", { configurable: true, value: makeTextEditor() })
6770
vi.mocked(vscode.workspace.getWorkspaceFolder).mockReturnValue(first)
6871
expect(CodeIndexManagerRegistry.getOrCreate(context, "/second")).toBeDefined()
69-
expect(CodeIndexManager).toHaveBeenCalledWith("/second", second.uri, context)
72+
expect(CodeIndexManager).toHaveBeenCalledWith("/second", second.uri, context, expect.any(CodeIndexStateManager))
7073
})
7174

7275
it("preserves the actual remote workspace URI", () => {
@@ -76,7 +79,7 @@ describe("CodeIndexManagerRegistry", () => {
7679
value: [{ uri, name: "remote", index: 0 }],
7780
})
7881
CodeIndexManagerRegistry.getOrCreate(context, "/remote")
79-
expect(CodeIndexManager).toHaveBeenCalledWith("/remote", uri, context)
82+
expect(CodeIndexManager).toHaveBeenCalledWith("/remote", uri, context, expect.any(CodeIndexStateManager))
8083
expect(vi.mocked(CodeIndexManager).mock.calls[0][1]).toBe(uri)
8184
expect(vscode.Uri.file).not.toHaveBeenCalled()
8285
})
@@ -87,7 +90,7 @@ describe("CodeIndexManagerRegistry", () => {
8790
vi.mocked(vscode.Uri.file).mockReturnValue(uri)
8891
CodeIndexManagerRegistry.getOrCreate(context, uri.fsPath)
8992
expect(vscode.Uri.file).toHaveBeenCalledWith(uri.fsPath)
90-
expect(CodeIndexManager).toHaveBeenCalledWith(uri.fsPath, uri, context)
93+
expect(CodeIndexManager).toHaveBeenCalledWith(uri.fsPath, uri, context, expect.any(CodeIndexStateManager))
9194
})
9295

9396
it("constructs a file URI for an explicit path not matching any open workspace folder", () => {
@@ -96,7 +99,12 @@ describe("CodeIndexManagerRegistry", () => {
9699
vi.mocked(vscode.Uri.file).mockReturnValue(uri)
97100
CodeIndexManagerRegistry.getOrCreate(context, "/outside/project")
98101
expect(vscode.Uri.file).toHaveBeenCalledWith("/outside/project")
99-
expect(CodeIndexManager).toHaveBeenCalledWith("/outside/project", uri, context)
102+
expect(CodeIndexManager).toHaveBeenCalledWith(
103+
"/outside/project",
104+
uri,
105+
context,
106+
expect.any(CodeIndexStateManager),
107+
)
100108
})
101109

102110
it("reuses the same path and keeps different paths isolated", () => {

0 commit comments

Comments
 (0)