diff --git a/proto/cline/common.proto b/proto/cline/common.proto index 26ef8186..8513f0e0 100644 --- a/proto/cline/common.proto +++ b/proto/cline/common.proto @@ -55,6 +55,11 @@ message Boolean { bool value = 1; } +// the same as Boolean, but avoiding name conflicts +message BooleanResponse { + bool value = 1; +} + message StringArray { repeated string values = 1; } diff --git a/proto/cline/file.proto b/proto/cline/file.proto index 5afdf839..569793e4 100644 --- a/proto/cline/file.proto +++ b/proto/cline/file.proto @@ -57,6 +57,12 @@ service FileService { // Subscribe to workspace file updates rpc subscribeToWorkspaceUpdates(EmptyRequest) returns (stream StringArray); + + // Check if file exists in the project + rpc ifFileExistsRelativePath(StringRequest) returns (BooleanResponse); + + // Open a file in editor by a relative path + rpc openFileRelativePath(StringRequest) returns (Empty); } // Response for refreshRules operation diff --git a/src/core/controller/file/__tests__/ifFileExistsRelativePath.test.ts b/src/core/controller/file/__tests__/ifFileExistsRelativePath.test.ts new file mode 100644 index 00000000..9583fca8 --- /dev/null +++ b/src/core/controller/file/__tests__/ifFileExistsRelativePath.test.ts @@ -0,0 +1,101 @@ +import { describe, it, beforeEach, afterEach } from "mocha" +import { expect } from "chai" +import * as sinon from "sinon" +import { ifFileExistsRelativePath } from "../ifFileExistsRelativePath" +import { Controller } from "@core/controller" +import { StringRequest, BooleanResponse } from "@shared/proto/cline/common" +import * as pathUtils from "@utils/path" + +describe("ifFileExistsRelativePath", () => { + let sandbox: sinon.SinonSandbox + let mockController: Controller + let getWorkspacePathStub: sinon.SinonStub + let consoleErrorStub: sinon.SinonStub + + beforeEach(() => { + sandbox = sinon.createSandbox() + + // Create a mock controller + mockController = {} as any + + // Stub getWorkspacePath utility + getWorkspacePathStub = sandbox.stub(pathUtils, "getWorkspacePath") + + // Stub console.error to prevent test output pollution + consoleErrorStub = sandbox.stub(console, "error") + }) + + afterEach(() => { + sandbox.restore() + }) + + it("should return BooleanResponse with boolean value", async () => { + getWorkspacePathStub.resolves("/workspace") + + const request = StringRequest.create({ + value: "src/test.ts", + }) + + const result = await ifFileExistsRelativePath(mockController, request) + + // The result should be a BooleanResponse object + expect(result).to.have.property("value") + expect(typeof result.value).to.equal("boolean") + }) + + it("should return false and log error when no workspace path is available", async () => { + const noWorkspaceScenarios = [null, undefined] + + for (const workspaceValue of noWorkspaceScenarios) { + getWorkspacePathStub.resolves(workspaceValue) + consoleErrorStub.resetHistory() + + const request = StringRequest.create({ + value: "src/test.ts", + }) + + const result = await ifFileExistsRelativePath(mockController, request) + + expect(result).to.deep.equal(BooleanResponse.create({ value: false })) + expect(consoleErrorStub.called).to.be.true + } + }) + + it("should return false when path is invalid", async () => { + getWorkspacePathStub.resolves("/workspace") + + const invalidPaths = ["", undefined] + + for (const invalidPath of invalidPaths) { + const request = StringRequest.create({ + value: invalidPath, + }) + + const result = await ifFileExistsRelativePath(mockController, request) + + expect(result).to.deep.equal(BooleanResponse.create({ value: false })) + } + }) + + it("should handle valid relative paths correctly", async () => { + getWorkspacePathStub.resolves("/workspace") + + // Test with valid workspace-relative paths only + const validPaths = ["src/file.ts", "./src/file.ts", "package.json", ".gitignore", "src/components/ui/Button/Button.tsx"] + + for (const testPath of validPaths) { + const request = StringRequest.create({ + value: testPath, + }) + + const result = await ifFileExistsRelativePath(mockController, request) + + // Each should return a BooleanResponse + expect(result).to.have.property("value") + expect(typeof result.value).to.equal("boolean") + } + + // Verify that getWorkspacePath was called for each path + expect(getWorkspacePathStub.callCount).to.equal(validPaths.length) + }) +}) diff --git a/src/core/controller/file/__tests__/openFileRelativePath.test.ts b/src/core/controller/file/__tests__/openFileRelativePath.test.ts new file mode 100644 index 00000000..2c318995 --- /dev/null +++ b/src/core/controller/file/__tests__/openFileRelativePath.test.ts @@ -0,0 +1,117 @@ +import { describe, it, beforeEach, afterEach } from "mocha" +import { expect } from "chai" +import * as sinon from "sinon" +import { openFileRelativePath } from "../openFileRelativePath" +import { Controller } from "@core/controller" +import { StringRequest, Empty } from "@shared/proto/cline/common" +import * as openFileIntegration from "@integrations/misc/open-file" +import * as pathUtils from "@utils/path" +import * as path from "path" + +describe("openFileRelativePath", () => { + let sandbox: sinon.SinonSandbox + let mockController: Controller + let openFileIntegrationStub: sinon.SinonStub + let getWorkspacePathStub: sinon.SinonStub + let consoleErrorStub: sinon.SinonStub + + beforeEach(() => { + sandbox = sinon.createSandbox() + + // Create a mock controller + mockController = {} as any + + // Stub the openFileIntegration function + openFileIntegrationStub = sandbox.stub(openFileIntegration, "openFile") + + // Stub getWorkspacePath utility + getWorkspacePathStub = sandbox.stub(pathUtils, "getWorkspacePath") + + // Stub console.error to prevent test output pollution + consoleErrorStub = sandbox.stub(console, "error") + }) + + afterEach(() => { + sandbox.restore() + }) + + it("should return Empty response on successful execution", async () => { + getWorkspacePathStub.resolves("/workspace") + + const request = StringRequest.create({ + value: "src/test.ts", + }) + + const result = await openFileRelativePath(mockController, request) + + expect(result).to.deep.equal(Empty.create()) + }) + + it("should call openFileIntegration with absolute path when relative path is provided", async () => { + const workspacePath = "/workspace" + const relativePath = "src/components/Test.tsx" + const expectedAbsolutePath = path.resolve(workspacePath, relativePath) + + getWorkspacePathStub.resolves(workspacePath) + + const request = StringRequest.create({ + value: relativePath, + }) + + await openFileRelativePath(mockController, request) + + expect(openFileIntegrationStub.calledOnceWith(expectedAbsolutePath)).to.be.true + }) + + it("should not call openFileIntegration when path is invalid", async () => { + getWorkspacePathStub.resolves("/workspace") + + const invalidPaths = ["", undefined] + + for (const invalidPath of invalidPaths) { + const request = StringRequest.create({ + value: invalidPath, + }) + + await openFileRelativePath(mockController, request) + + expect(openFileIntegrationStub.called).to.be.false + openFileIntegrationStub.resetHistory() + } + }) + + it("should return Empty and log error when no workspace path is available", async () => { + const noWorkspaceScenarios = [null, undefined] + + for (const workspaceValue of noWorkspaceScenarios) { + getWorkspacePathStub.resolves(workspaceValue) + consoleErrorStub.resetHistory() + + const request = StringRequest.create({ + value: "src/test.ts", + }) + + const result = await openFileRelativePath(mockController, request) + + expect(result).to.deep.equal(Empty.create()) + expect(consoleErrorStub.called).to.be.true + expect(openFileIntegrationStub.called).to.be.false + } + }) + + it("should handle nested directory paths", async () => { + const workspacePath = "/workspace" + const relativePath = "src/components/ui/Button/Button.tsx" + const expectedAbsolutePath = path.resolve(workspacePath, relativePath) + + getWorkspacePathStub.resolves(workspacePath) + + const request = StringRequest.create({ + value: relativePath, + }) + + await openFileRelativePath(mockController, request) + + expect(openFileIntegrationStub.calledOnceWith(expectedAbsolutePath)).to.be.true + }) +}) diff --git a/src/core/controller/file/ifFileExistsRelativePath.ts b/src/core/controller/file/ifFileExistsRelativePath.ts new file mode 100644 index 00000000..2fe74519 --- /dev/null +++ b/src/core/controller/file/ifFileExistsRelativePath.ts @@ -0,0 +1,35 @@ +import * as path from "path" +import * as fs from "fs" +import { Controller } from ".." +import { StringRequest, BooleanResponse } from "@shared/proto/cline/common" +import { getWorkspacePath } from "@utils/path" + +/** + * Check if a file exists in the project using a relative path + * @param controller The controller instance + * @param request The request containing the relative file path to check + * @returns BooleanResponse indicating whether the file exists + */ +export async function ifFileExistsRelativePath(_controller: Controller, request: StringRequest): Promise { + const workspacePath = await getWorkspacePath() + + if (!workspacePath) { + // If no workspace is open, return false + console.error("Error in ifFileExistsRelativePath: No workspace path available") // TODO + return BooleanResponse.create({ value: false }) + } + + if (!request.value) { + // If no path provided, return false + return BooleanResponse.create({ value: false }) + } + + // Resolve the relative path to absolute path + const absolutePath = path.resolve(workspacePath, request.value) + // Check if the file exists + try { + return BooleanResponse.create({ value: fs.statSync(absolutePath).isFile() }) + } catch { + return BooleanResponse.create({ value: false }) + } +} diff --git a/src/core/controller/file/openFileRelativePath.ts b/src/core/controller/file/openFileRelativePath.ts new file mode 100644 index 00000000..20821969 --- /dev/null +++ b/src/core/controller/file/openFileRelativePath.ts @@ -0,0 +1,30 @@ +import * as path from "path" +import { Controller } from ".." +import { Empty, StringRequest } from "@shared/proto/cline/common" +import { openFile as openFileIntegration } from "@integrations/misc/open-file" +import { getWorkspacePath } from "@utils/path" + +/** + * Opens a file in the editor by a relative path + * @param controller The controller instance + * @param request The request message containing the relative file path in the 'value' field + * @returns Empty response + */ +export async function openFileRelativePath(_controller: Controller, request: StringRequest): Promise { + const workspacePath = await getWorkspacePath() + + if (!workspacePath) { + console.error("Error in openFileRelativePath: No workspace path available") + return Empty.create() + } + + if (request.value) { + // Resolve the relative path to absolute path + const absolutePath = path.resolve(workspacePath, request.value) + + // Open the file using the existing integration + openFileIntegration(absolutePath) + } + + return Empty.create() +} diff --git a/webview-ui/src/components/common/MarkdownBlock.tsx b/webview-ui/src/components/common/MarkdownBlock.tsx index 1cd24ab2..11df2592 100644 --- a/webview-ui/src/components/common/MarkdownBlock.tsx +++ b/webview-ui/src/components/common/MarkdownBlock.tsx @@ -9,8 +9,9 @@ import { useExtensionState } from "@/context/ExtensionStateContext" import CodeBlock, { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock" import MermaidBlock from "@/components/common/MermaidBlock" import { WithCopyButton } from "./CopyButton" -import { StateServiceClient } from "@/services/grpc-client" +import { FileServiceClient, StateServiceClient } from "@/services/grpc-client" import { PlanActMode, TogglePlanActModeRequest } from "@shared/proto/cline/state" +import { StringRequest, BooleanResponse } from "@shared/proto/cline/common" // Styled component for Act Mode text with more specific styling const ActModeHighlight: React.FC = () => { @@ -320,6 +321,39 @@ const PreWithCopyButton = ({ ) } +/** + * Custom remark plugin that detects file paths in inline code blocks + * and marks them with metadata for later rendering + */ +const remarkFilePathDetection = () => { + return async (tree: Node) => { + const fileNameRegex = /^(?!\/)[\w\-./]+(?[] = [] + + // Collect all inline code nodes that might be file paths + visit(tree, "inlineCode", (node: Node & { value: string; data?: any }) => { + if (fileNameRegex.test(node.value) && !node.value.includes("\n")) { + const promise = FileServiceClient.ifFileExistsRelativePath(StringRequest.create({ value: node.value })) + .then((exists) => { + if (exists.value) { + node.data = node.data || {} + node.data.hProperties = node.data.hProperties || {} + node.data.hProperties["data-is-file-path"] = "true" + } + }) + .catch((err) => { + console.debug(`Failed to check file existence for ${node.value}:`, err) + }) + + filePathPromises.push(promise) + } + }) + + await Promise.all(filePathPromises) + } +} + const MarkdownBlock = memo(({ markdown }: MarkdownBlockProps) => { const { theme } = useExtensionState() @@ -328,6 +362,7 @@ const MarkdownBlock = memo(({ markdown }: MarkdownBlockProps) => { remarkPreventBoldFilenames, remarkUrlToLink, remarkHighlightActMode, + remarkFilePathDetection, () => { return (tree) => { visit(tree, "code", (node: any) => { @@ -361,12 +396,31 @@ const MarkdownBlock = memo(({ markdown }: MarkdownBlockProps) => { ) }, - code: (props: ComponentProps<"code">) => { + code: (props: ComponentProps<"code"> & { [key: string]: any }) => { const className = props.className || "" if (className.includes("language-mermaid")) { const codeText = String(props.children || "") return } + + // Check if this is a file path (metadata is converted to data- attributes by rehype-react) + if (props["data-is-file-path"]) { + // Extract the file path from the code element's children + const filePath = typeof props.children === "string" ? props.children : String(props.children || "") + + return ( + <> + +