Adding Multi Root Workspace Support for a few different tool calls (#6228)

* Adding multi root workspace support for different tools

* fixing spacing

* fixing spacing

* fixing spacing
This commit is contained in:
Ara authored and GitHub committed 2025-09-17 10:04:30 -07:00
1 parent e9c8f67822
commit 4e7af6eb5d
17 files changed
+186 -41

No files matched your search

@@ -18,6 +18,9 @@ export async function getToolUseToolsSection(variant: PromptVariant, context: Sy
// (TODO tool is now dynamically added when focusChainEnabled is true)
const shouldIncludeTaskProgress = focusChainEnabled
// Define multi-root hint based on feature flag
const multiRootHint = context.isMultiRootEnabled ? MULTI_ROOT_HINT : ""
return new TemplateEngine().resolve(template, context, {
TASK_PROGRESS: shouldIncludeTaskProgress ? TASK_PROGRESS : "",
FOCUS_CHAIN_ATTEMPT: shouldIncludeTaskProgress ? FOCUS_CHAIN_ATTEMPT : "",
@@ -25,6 +28,7 @@ export async function getToolUseToolsSection(variant: PromptVariant, context: Sy
BROWSER_VIEWPORT_WIDTH: context.browserSettings?.viewport?.width || 0,
BROWSER_VIEWPORT_HEIGHT: context.browserSettings?.viewport?.height || 0,
CWD: context.cwd,
MULTI_ROOT_HINT: multiRootHint,
})
}
@@ -35,3 +39,4 @@ const FOCUS_CHAIN_USAGE = `<task_progress>
Checklist here (optional)
</task_progress>
`
const MULTI_ROOT_HINT = " Use @workspace:path syntax (e.g., @frontend:src/index.ts) to specify a workspace."
@@ -7,7 +7,7 @@ const generic: ClineToolSpec = {
variant: ModelFamily.GENERIC,
id: ClineDefaultTool.BASH,
name: "execute_command",
description: `Request to execute a CLI command on the system. Use this when you need to perform system operations or run specific commands to accomplish any step in the user's task. You must tailor your command to the user's system and provide a clear explanation of what the command does. For command chaining, use the appropriate chaining syntax for the user's shell. Prefer to execute complex CLI commands over creating executable scripts, as they are more flexible and easier to run. Commands will be executed in the current working directory: {{CWD}}`,
description: `Request to execute a CLI command on the system. Use this when you need to perform system operations or run specific commands to accomplish any step in the user's task. You must tailor your command to the user's system and provide a clear explanation of what the command does. For command chaining, use the appropriate chaining syntax for the user's shell. Prefer to execute complex CLI commands over creating executable scripts, as they are more flexible and easier to run. Commands will be executed in the current working directory: {{CWD}}{{MULTI_ROOT_HINT}}`,
parameters: [
{
name: "command",
@@ -15,7 +15,7 @@ const generic: ClineToolSpec = {
{
name: "path",
required: true,
instruction: `The path of the directory (relative to the current working directory {{CWD}}) to list top level source code definitions for.`,
instruction: `The path of the directory (relative to the current working directory {{CWD}}){{MULTI_ROOT_HINT}} to list top level source code definitions for.`,
usage: "Directory path here",
},
TASK_PROGRESS_PARAMETER,
@@ -15,7 +15,8 @@ const generic: ClineToolSpec = {
{
name: "path",
required: true,
instruction: "The path of the directory to list contents for (relative to the current working directory {{CWD}})",
instruction:
"The path of the directory to list contents for (relative to the current working directory {{CWD}}){{MULTI_ROOT_HINT}}",
usage: "Directory path here",
},
{
@@ -15,7 +15,7 @@ const generic: ClineToolSpec = {
{
name: "path",
required: true,
instruction: `The path of the file to read (relative to the current working directory {{CWD}})`,
instruction: `The path of the file to read (relative to the current working directory {{CWD}}){{MULTI_ROOT_HINT}}`,
usage: "File path here",
},
TASK_PROGRESS_PARAMETER,
@@ -34,7 +34,7 @@ const generic: ClineToolSpec = {
{
name: "path",
required: true,
instruction: `The path of the file to write to (relative to the current working directory {{CWD}})`,
instruction: `The path of the file to write to (relative to the current working directory {{CWD}}){{MULTI_ROOT_HINT}}`,
usage: "File path here",
},
{
+6 -1
View File
@@ -83,7 +83,12 @@ export class AutoApprove {
let isLocalRead: boolean = false
if (autoApproveActionpath) {
const cwd = await getCwd(getDesktopDir())
const absolutePath = resolveWorkspacePath(cwd, autoApproveActionpath, "AutoApprove.shouldAutoApproveToolWithPath")
// When called with a string cwd, resolveWorkspacePath returns a string
const absolutePath = resolveWorkspacePath(
cwd,
autoApproveActionpath,
"AutoApprove.shouldAutoApproveToolWithPath",
) as string
isLocalRead = isLocatedInPath(cwd, absolutePath)
} else {
// If we do not get a path for some reason, default to a (safer) false return
@@ -1,5 +1,6 @@
import type { ToolUse } from "@core/assistant-message"
import { formatResponse } from "@core/prompts/responses"
import { WorkspacePathAdapter } from "@core/workspace/WorkspacePathAdapter"
import { showSystemNotification } from "@integrations/notifications"
import { COMMAND_REQ_APP_STRING } from "@shared/combineCommandSequences"
import { ClineAsk } from "@shared/ExtensionMessage"
@@ -76,8 +77,37 @@ export class ExecuteCommandToolHandler implements IFullyManagedTool {
command = fixModelHtmlEscaping(command)
}
// Handle multi-workspace command execution
let executionDir: string = config.cwd
let actualCommand: string = command
if (config.isMultiRootEnabled && config.workspaceManager) {
// Check if command has a workspace hint prefix
// e.g., "@backend:npm install" or just "npm install"
const commandMatch = command.match(/^@(\w+):(.+)$/)
if (commandMatch) {
const workspaceHint = commandMatch[1]
actualCommand = commandMatch[2].trim()
// Find the workspace root for this hint
const adapter = new WorkspacePathAdapter({
cwd: config.cwd,
isMultiRootEnabled: true,
workspaceManager: config.workspaceManager,
})
// Resolve to get the workspace directory
executionDir = adapter.resolvePath(".", workspaceHint)
// Update command to remove the workspace prefix for display
command = actualCommand
}
// If no hint, use primary workspace (cwd)
}
// Check clineignore validation for command
const ignoredFileAttemptedToAccess = config.services.clineIgnoreController.validateCommand(command)
const ignoredFileAttemptedToAccess = config.services.clineIgnoreController.validateCommand(actualCommand)
if (ignoredFileAttemptedToAccess) {
await config.callbacks.say("clineignore_error", ignoredFileAttemptedToAccess)
return formatResponse.toolError(formatResponse.clineIgnoreError(ignoredFileAttemptedToAccess))
@@ -95,21 +125,21 @@ export class ExecuteCommandToolHandler implements IFullyManagedTool {
if ((!requiresApprovalPerLLM && autoApproveSafe) || (requiresApprovalPerLLM && autoApproveSafe && autoApproveAll)) {
// Auto-approve flow
await config.callbacks.removeLastPartialMessageIfExistsWithType("ask", "command")
await config.callbacks.say("command", command, undefined, undefined, false)
await config.callbacks.say("command", actualCommand, undefined, undefined, false)
config.taskState.consecutiveAutoApprovedRequestsCount++
didAutoApprove = true
telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, true, true)
} else {
// Manual approval flow
showNotificationForApprovalIfAutoApprovalEnabled(
`Cline wants to execute a command: ${command}`,
`Cline wants to execute a command: ${actualCommand}`,
config.autoApprovalSettings.enabled,
config.autoApprovalSettings.enableNotifications,
)
const didApprove = await ToolResultUtils.askApprovalAndPushFeedback(
"command",
command + `${autoApproveSafe && requiresApprovalPerLLM ? COMMAND_REQ_APP_STRING : ""}`,
actualCommand + `${autoApproveSafe && requiresApprovalPerLLM ? COMMAND_REQ_APP_STRING : ""}`,
config,
)
if (!didApprove) {
@@ -131,8 +161,15 @@ export class ExecuteCommandToolHandler implements IFullyManagedTool {
}, 30_000)
}
// Execute the command
const [userRejected, result] = await config.callbacks.executeCommandTool(command, timeoutSeconds)
// Execute the command in the correct directory
// If executionDir is different from cwd, prepend cd command
let finalCommand: string = actualCommand
if (executionDir !== config.cwd) {
// Use && to chain commands so they run in sequence
finalCommand = `cd "${executionDir}" && ${actualCommand}`
}
const [userRejected, result] = await config.callbacks.executeCommandTool(finalCommand, timeoutSeconds)
if (timeoutId) {
clearTimeout(timeoutId)
@@ -58,14 +58,19 @@ export class ListCodeDefinitionNamesToolHandler implements IFullyManagedTool {
}
config.taskState.consecutiveMistakeCount = 0
const absolutePath = resolveWorkspacePath(config.cwd, relDirPath!, "ListCodeDefinitionNamesToolHandler.execute")
// Resolve the absolute path based on multi-workspace configuration
const pathResult = resolveWorkspacePath(config, relDirPath!, "ListCodeDefinitionNamesToolHandler.execute")
const { absolutePath, displayPath } =
typeof pathResult === "string" ? { absolutePath: pathResult, displayPath: relDirPath! } : pathResult
// Execute the actual parse source code operation
const result = await parseSourceCodeForDefinitionsTopLevel(absolutePath, config.services.clineIgnoreController)
// Handle approval flow
const sharedMessageProps = {
tool: "listCodeDefinitionNames",
path: getReadablePath(config.cwd, relDirPath!),
path: getReadablePath(config.cwd, displayPath),
content: result,
operationIsLocatedInWorkspace: await isLocatedInWorkspace(relDirPath!),
}
@@ -63,7 +63,11 @@ export class ListFilesToolHandler implements IFullyManagedTool {
}
config.taskState.consecutiveMistakeCount = 0
const absolutePath = resolveWorkspacePath(config.cwd, relDirPath!, "ListFilesToolHandler.execute")
// Resolve the absolute path based on multi-workspace configuration
const pathResult = resolveWorkspacePath(config, relDirPath!, "ListFilesToolHandler.execute")
const { absolutePath, displayPath } =
typeof pathResult === "string" ? { absolutePath: pathResult, displayPath: relDirPath! } : pathResult
// Execute the actual list files operation
const [files, didHitLimit] = await listFiles(absolutePath, recursive, 200)
@@ -73,7 +77,7 @@ export class ListFilesToolHandler implements IFullyManagedTool {
// Handle approval flow
const sharedMessageProps = {
tool: recursive ? "listFilesRecursive" : "listFilesTopLevel",
path: getReadablePath(config.cwd, relDirPath!),
path: getReadablePath(config.cwd, displayPath),
content: result,
operationIsLocatedInWorkspace: await isLocatedInWorkspace(relDirPath!),
}
@@ -66,12 +66,16 @@ export class ReadFileToolHandler implements IFullyManagedTool {
}
config.taskState.consecutiveMistakeCount = 0
const absolutePath = resolveWorkspacePath(config.cwd, relPath!, "ReadFileToolHandler.execute")
// Resolve the absolute path based on multi-workspace configuration
const pathResult = resolveWorkspacePath(config, relPath!, "ReadFileToolHandler.execute")
const { absolutePath, displayPath } =
typeof pathResult === "string" ? { absolutePath: pathResult, displayPath: relPath! } : pathResult
// Handle approval flow
const sharedMessageProps = {
tool: "readFile",
path: getReadablePath(config.cwd, relPath!),
path: getReadablePath(config.cwd, displayPath),
content: absolutePath,
operationIsLocatedInWorkspace: await isLocatedInWorkspace(relPath!),
} satisfies ClineSayTool
@@ -110,16 +114,16 @@ export class ReadFileToolHandler implements IFullyManagedTool {
// Execute the actual file read operation
const supportsImages = config.api.getModel().info.supportsImages ?? false
const result = await extractFileContent(absolutePath, supportsImages)
const fileContent = await extractFileContent(absolutePath, supportsImages)
// Track file read operation
await config.services.fileContextTracker.trackFileContext(relPath!, "read_tool")
// Handle image blocks separately - they need to be pushed to userMessageContent
if (result.imageBlock) {
config.taskState.userMessageContent.push(result.imageBlock)
if (fileContent.imageBlock) {
config.taskState.userMessageContent.push(fileContent.imageBlock)
}
return result.text
return fileContent.text
}
}
@@ -73,7 +73,10 @@ export class SearchFilesToolHandler implements IFullyManagedTool {
}
config.taskState.consecutiveMistakeCount = 0
const absolutePath = resolveWorkspacePath(config.cwd, relDirPath!, "SearchFilesTool.execute")
// Resolve the absolute path based on multi-workspace configuration
const pathResult = resolveWorkspacePath(config, relDirPath!, "SearchFilesTool.execute")
const absolutePath = typeof pathResult === "string" ? pathResult : pathResult.absolutePath
// Execute the actual regex search operation
const results = await regexSearchFiles(
@@ -297,14 +297,21 @@ export class WriteToFileToolHandler implements IFullyManagedTool {
* or undefined if validation fails
*/
async validateAndPrepareFileOperation(config: TaskConfig, block: ToolUse, relPath: string, diff?: string, content?: string) {
// Parse workspace hint and resolve path for multi-workspace support
const pathResult = resolveWorkspacePath(config, relPath, "WriteToFileToolHandler.validateAndPrepareFileOperation")
const { absolutePath, resolvedPath } =
typeof pathResult === "string"
? { absolutePath: pathResult, resolvedPath: relPath }
: { absolutePath: pathResult.absolutePath, resolvedPath: pathResult.resolvedPath }
// Check clineignore access first
const accessValidation = this.validator.checkClineIgnorePath(relPath)
const accessValidation = this.validator.checkClineIgnorePath(resolvedPath)
if (!accessValidation.ok) {
// Show error and return early (full original behavior)
await config.callbacks.say("clineignore_error", relPath)
await config.callbacks.say("clineignore_error", resolvedPath)
// Push tool result and save checkpoint using existing utilities
const errorResponse = formatResponse.toolError(formatResponse.clineIgnoreError(relPath))
const errorResponse = formatResponse.toolError(formatResponse.clineIgnoreError(resolvedPath))
ToolResultUtils.pushToolResult(
errorResponse,
block,
@@ -324,11 +331,6 @@ export class WriteToFileToolHandler implements IFullyManagedTool {
if (config.services.diffViewProvider.editType !== undefined) {
fileExists = config.services.diffViewProvider.editType === "modify"
} else {
const absolutePath = resolveWorkspacePath(
config.cwd,
relPath,
"WriteToFileToolHandler.validateAndPrepareFileOperation",
)
fileExists = await fileExistsAtPath(absolutePath)
config.services.diffViewProvider.editType = fileExists ? "modify" : "create"
}
+3 -3
View File
@@ -30,7 +30,7 @@ export class WorkspacePathAdapter {
resolvePath(relativePath: string, workspaceHint?: string): string {
// Single-root mode (backward compatible)
if (!this.config.isMultiRootEnabled || !this.config.workspaceManager) {
return resolveWorkspacePath(this.config.cwd, relativePath, "WorkspacePathAdapter")
return resolveWorkspacePath(this.config.cwd, relativePath, "WorkspacePathAdapter") as string
}
// Multi-root mode
@@ -73,7 +73,7 @@ export class WorkspacePathAdapter {
// Fallback to cwd if no roots (shouldn't happen, but defensive)
console.warn(`[WorkspacePathAdapter] No workspace roots found, falling back to cwd`)
return resolveWorkspacePath(this.config.cwd, relativePath, "WorkspacePathAdapter-fallback")
return resolveWorkspacePath(this.config.cwd, relativePath, "WorkspacePathAdapter-fallback") as string
}
/**
@@ -86,7 +86,7 @@ export class WorkspacePathAdapter {
getAllPossiblePaths(relativePath: string): string[] {
// Single-root mode
if (!this.config.isMultiRootEnabled || !this.config.workspaceManager) {
return [resolveWorkspacePath(this.config.cwd, relativePath, "WorkspacePathAdapter-getAllPaths")]
return [resolveWorkspacePath(this.config.cwd, relativePath, "WorkspacePathAdapter-getAllPaths") as string]
}
// Multi-root mode
+72 -4
View File
@@ -7,6 +7,8 @@
import * as path from "path"
import { MigrationReporter, type UsageStats } from "./MigrationReporter"
import { parseWorkspaceInlinePath } from "./utils/parseWorkspaceInlinePath"
import { WorkspacePathAdapter } from "./WorkspacePathAdapter"
import { WorkspaceRoot } from "./WorkspaceRoot"
/**
@@ -251,11 +253,77 @@ export class WorkspaceResolver {
export const workspaceResolver = new WorkspaceResolver()
/**
* Phase 0: Convenience function for easy migration from path.resolve()
* This is what we'll use to replace existing path.resolve(cwd, ...) calls
* Result type for multi-root workspace path resolution
*/
export function resolveWorkspacePath(cwd: string, relativePath: string, context?: string): string {
return workspaceResolver.resolveWorkspacePath(cwd, relativePath, context) as string
export interface WorkspacePathResult {
absolutePath: string
displayPath: string
resolvedPath: string
}
/**
* Configuration for workspace path resolution
*/
export interface WorkspaceConfig {
cwd: string
isMultiRootEnabled?: boolean
workspaceManager?: any
}
/**
* Enhanced workspace path resolution that handles both single and multi-root workspaces
*
* @param cwdOrConfig - Either a string (for backward compatibility) or a config object
* @param relativePath - The relative path to resolve
* @param context - Component/handler name for tracking usage
* @returns Either a string (for backward compatibility) or a WorkspacePathResult object
*/
export function resolveWorkspacePath(
cwdOrConfig: string | WorkspaceConfig,
relativePath: string,
context?: string,
): string | WorkspacePathResult {
// Backward compatibility: if first param is a string, return string
if (typeof cwdOrConfig === "string") {
return workspaceResolver.resolveWorkspacePath(cwdOrConfig, relativePath, context) as string
}
// New behavior: handle multi-root workspaces
const config = cwdOrConfig
// If multi-root is enabled and we have a workspace manager
if (config.isMultiRootEnabled && config.workspaceManager) {
// Parse workspace hint from the path (e.g., @frontend:src/index.ts)
const { workspaceHint, relPath: parsedPath } = parseWorkspaceInlinePath(relativePath)
// Create adapter for multi-workspace path resolution
const adapter = new WorkspacePathAdapter({
cwd: config.cwd,
isMultiRootEnabled: true,
workspaceManager: config.workspaceManager,
})
// Resolve to the correct workspace root
const absolutePath = adapter.resolvePath(parsedPath, workspaceHint)
// Build display path with workspace hint if present
const displayPath = workspaceHint ? `@${workspaceHint}:${parsedPath}` : parsedPath
return {
absolutePath,
displayPath,
resolvedPath: parsedPath,
}
}
// Fallback to single-workspace behavior
const absolutePath = workspaceResolver.resolveWorkspacePath(config.cwd, relativePath, context) as string
return {
absolutePath,
displayPath: relativePath,
resolvedPath: relativePath,
}
}
/**
@@ -3,6 +3,7 @@ import { expect } from "chai"
import * as path from "path"
import sinon from "sinon"
import { HostProvider } from "@/hosts/host-provider"
import * as featureFlags from "@/services/feature-flags"
import * as telemetry from "@/services/telemetry"
import * as pathUtils from "@/utils/path"
import { setupWorkspaceManager } from "../setup"
@@ -97,6 +98,11 @@ describe("setupWorkspaceManager", () => {
const stateManager = makeStateManager({ multiRootEnabled: true })
const detectRoots = sandbox.stub().resolves(defaultRoots)
// Stub featureFlagsService to return true for multi-root
sandbox.stub(featureFlags, "featureFlagsService").value({
getMultiRootEnabled: () => true,
})
const manager = await setupWorkspaceManager({
stateManager: stateManager as any,
historyItem: undefined,
@@ -162,6 +168,11 @@ describe("setupWorkspaceManager", () => {
const stateManager = makeStateManager({ multiRootEnabled: true })
const detectRoots = sandbox.stub().rejects(new Error("boom"))
// Stub featureFlagsService to return true for multi-root
sandbox.stub(featureFlags, "featureFlagsService").value({
getMultiRootEnabled: () => true,
})
const manager = await setupWorkspaceManager({
stateManager: stateManager as any,
historyItem: undefined,
+3 -3
View File
@@ -1,4 +1,5 @@
import { HostProvider } from "@/hosts/host-provider"
import { featureFlagsService } from "@/services/feature-flags"
import { telemetryService } from "@/services/telemetry"
import type { HistoryItem } from "@/shared/HistoryItem"
import { ShowMessageType } from "@/shared/proto/host/window"
@@ -24,13 +25,12 @@ export async function setupWorkspaceManager({
detectRoots: DetectRoots
}): Promise<WorkspaceRootManager> {
const cwd = await getCwd(getDesktopDir())
const multiRootEnabled = stateManager.getGlobalStateKey("multiRootEnabled")
const startTime = performance.now()
const isMultiRootEnabled = featureFlagsService.getMultiRootEnabled()
try {
let manager: WorkspaceRootManager
// Multi-root mode condition which is always false for now as isMultiRootEnabled is hardcoded to false
if (multiRootEnabled) {
if (isMultiRootEnabled) {
// Multi-root: detect workspace folders
const roots = await detectRoots()
manager = new WorkspaceRootManager(roots, 0)