chore: Prettier fix formatting

This commit is contained in:
Saoud Rizwan committed 2025-01-06 12:41:33 -08:00
1 parent 9de7253998
commit 25cd7cc8e2
106 files changed
+1624 -5278

No files matched your search

@@ -21,15 +21,10 @@ class CheckpointTracker {
this.cwd = cwd
}
public static async create(
taskId: string,
provider?: ClineProvider,
): Promise<CheckpointTracker> {
public static async create(taskId: string, provider?: ClineProvider): Promise<CheckpointTracker> {
try {
if (!provider) {
throw new Error(
"Provider is required to create a checkpoint tracker",
)
throw new Error("Provider is required to create a checkpoint tracker")
}
// Check if git is installed by attempting to get version
@@ -50,13 +45,9 @@ class CheckpointTracker {
}
private static async getWorkingDirectory(): Promise<string> {
const cwd = vscode.workspace.workspaceFolders
?.map((folder) => folder.uri.fsPath)
.at(0)
const cwd = vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0)
if (!cwd) {
throw new Error(
"No workspace detected. Please open Cline in a workspace to use checkpoints.",
)
throw new Error("No workspace detected. Please open Cline in a workspace to use checkpoints.")
}
const homedir = os.homedir()
const desktopPath = path.join(homedir, "Desktop")
@@ -78,37 +69,22 @@ class CheckpointTracker {
}
private async getShadowGitPath(): Promise<string> {
const globalStoragePath =
this.providerRef.deref()?.context.globalStorageUri.fsPath
const globalStoragePath = this.providerRef.deref()?.context.globalStorageUri.fsPath
if (!globalStoragePath) {
throw new Error("Global storage uri is invalid")
}
const checkpointsDir = path.join(
globalStoragePath,
"tasks",
this.taskId,
"checkpoints",
)
const checkpointsDir = path.join(globalStoragePath, "tasks", this.taskId, "checkpoints")
await fs.mkdir(checkpointsDir, { recursive: true })
const gitPath = path.join(checkpointsDir, ".git")
return gitPath
}
public static async doesShadowGitExist(
taskId: string,
provider?: ClineProvider,
): Promise<boolean> {
public static async doesShadowGitExist(taskId: string, provider?: ClineProvider): Promise<boolean> {
const globalStoragePath = provider?.context.globalStorageUri.fsPath
if (!globalStoragePath) {
return false
}
const gitPath = path.join(
globalStoragePath,
"tasks",
taskId,
"checkpoints",
".git",
)
const gitPath = path.join(globalStoragePath, "tasks", taskId, "checkpoints", ".git")
return await fileExistsAtPath(gitPath)
}
@@ -118,10 +94,7 @@ class CheckpointTracker {
// Make sure it's the same cwd as the configured worktree
const worktree = await this.getShadowGitConfigWorkTree()
if (worktree !== this.cwd) {
throw new Error(
"Checkpoints can only be used in the original workspace: " +
worktree,
)
throw new Error("Checkpoints can only be used in the original workspace: " + worktree)
}
return gitPath
@@ -250,8 +223,7 @@ class CheckpointTracker {
const gitPath = await this.getShadowGitPath()
const git = simpleGit(path.dirname(gitPath))
const worktree = await git.getConfig("core.worktree")
this.lastRetrievedShadowGitConfigWorkTree =
worktree.value || undefined
this.lastRetrievedShadowGitConfigWorkTree = worktree.value || undefined
return this.lastRetrievedShadowGitConfigWorkTree
} catch (error) {
console.error("Failed to get shadow git config worktree:", error)
@@ -323,11 +295,7 @@ class CheckpointTracker {
// If lhsHash is missing, use the initial commit of the repo
let baseHash = lhsHash
if (!baseHash) {
const rootCommit = await git.raw([
"rev-list",
"--max-parents=0",
"HEAD",
])
const rootCommit = await git.raw(["rev-list", "--max-parents=0", "HEAD"])
baseHash = rootCommit.trim()
}
@@ -336,14 +304,11 @@ class CheckpointTracker {
await git.add(".")
await this.renameNestedGitRepos(false)
const diffSummary = rhsHash
? await git.diffSummary([`${baseHash}..${rhsHash}`])
: await git.diffSummary([baseHash])
const diffSummary = rhsHash ? await git.diffSummary([`${baseHash}..${rhsHash}`]) : await git.diffSummary([baseHash])
// For each changed file, gather before/after content
const result = []
const cwdPath =
(await this.getShadowGitConfigWorkTree()) || this.cwd || ""
const cwdPath = (await this.getShadowGitConfigWorkTree()) || this.cwd || ""
for (const file of diffSummary.files) {
const filePath = file.file
@@ -387,16 +352,13 @@ class CheckpointTracker {
// Since we use git to track checkpoints, we need to temporarily disable nested git repos to work around git's requirement of using submodules for nested repos.
async renameNestedGitRepos(disable: boolean) {
// Find all .git directories that are not at the root level
const gitPaths = await globby(
"**/.git" + (disable ? "" : GIT_DISABLED_SUFFIX),
{
cwd: this.cwd,
onlyDirectories: true,
ignore: [".git"], // Ignore root level .git
dot: true,
markDirectories: false,
},
)
const gitPaths = await globby("**/.git" + (disable ? "" : GIT_DISABLED_SUFFIX), {
cwd: this.cwd,
onlyDirectories: true,
ignore: [".git"], // Ignore root level .git
dot: true,
markDirectories: false,
})
// For each nested .git directory, rename it based on operation
for (const gitPath of gitPaths) {
@@ -405,21 +367,14 @@ class CheckpointTracker {
if (disable) {
newPath = fullPath + GIT_DISABLED_SUFFIX
} else {
newPath = fullPath.endsWith(GIT_DISABLED_SUFFIX)
? fullPath.slice(0, -GIT_DISABLED_SUFFIX.length)
: fullPath
newPath = fullPath.endsWith(GIT_DISABLED_SUFFIX) ? fullPath.slice(0, -GIT_DISABLED_SUFFIX.length) : fullPath
}
try {
await fs.rename(fullPath, newPath)
console.log(
`CheckpointTracker ${disable ? "disabled" : "enabled"} nested git repo ${gitPath}`,
)
console.log(`CheckpointTracker ${disable ? "disabled" : "enabled"} nested git repo ${gitPath}`)
} catch (error) {
console.error(
`CheckpointTracker failed to ${disable ? "disable" : "enable"} nested git repo ${gitPath}:`,
error,
)
console.error(`CheckpointTracker failed to ${disable ? "disable" : "enable"} nested git repo ${gitPath}:`, error)
}
}
}
+2 -7
View File
@@ -11,10 +11,7 @@ export function getNewDiagnostics(
for (const [uri, newDiags] of newDiagnostics) {
const oldDiags = oldMap.get(uri) || []
const newProblemsForUri = newDiags.filter(
(newDiag) =>
!oldDiags.some((oldDiag) => deepEqual(oldDiag, newDiag)),
)
const newProblemsForUri = newDiags.filter((newDiag) => !oldDiags.some((oldDiag) => deepEqual(oldDiag, newDiag)))
if (newProblemsForUri.length > 0) {
newProblems.push([uri, newProblemsForUri])
@@ -80,9 +77,7 @@ export function diagnosticsToProblemsString(
): string {
let result = ""
for (const [uri, fileDiagnostics] of diagnostics) {
const problems = fileDiagnostics.filter((d) =>
severities.includes(d.severity),
)
const problems = fileDiagnostics.filter((d) => severities.includes(d.severity))
if (problems.length > 0) {
result += `\n\n${path.relative(cwd, uri.fsPath).toPosix()}`
for (const diagnostic of problems) {
@@ -1,12 +1,10 @@
import * as vscode from "vscode"
const fadedOverlayDecorationType = vscode.window.createTextEditorDecorationType(
{
backgroundColor: "rgba(255, 255, 0, 0.1)",
opacity: "0.4",
isWholeLine: true,
},
)
const fadedOverlayDecorationType = vscode.window.createTextEditorDecorationType({
backgroundColor: "rgba(255, 255, 0, 0.1)",
opacity: "0.4",
isWholeLine: true,
})
const activeLineDecorationType = vscode.window.createTextEditorDecorationType({
backgroundColor: "rgba(255, 255, 0, 0.3)",
@@ -44,20 +42,10 @@ export class DecorationController {
const lastRange = this.ranges[this.ranges.length - 1]
if (lastRange && lastRange.end.line === startIndex - 1) {
this.ranges[this.ranges.length - 1] = lastRange.with(
undefined,
lastRange.end.translate(numLines),
)
this.ranges[this.ranges.length - 1] = lastRange.with(undefined, lastRange.end.translate(numLines))
} else {
const endLine = startIndex + numLines - 1
this.ranges.push(
new vscode.Range(
startIndex,
0,
endLine,
Number.MAX_SAFE_INTEGER,
),
)
this.ranges.push(new vscode.Range(startIndex, 0, endLine, Number.MAX_SAFE_INTEGER))
}
this.editor.setDecorations(this.getDecoration(), this.ranges)
@@ -75,13 +63,7 @@ export class DecorationController {
// Add a new range for all lines after the current line
if (line < totalLines - 1) {
this.ranges.push(
new vscode.Range(
new vscode.Position(line + 1, 0),
new vscode.Position(
totalLines - 1,
Number.MAX_SAFE_INTEGER,
),
),
new vscode.Range(new vscode.Position(line + 1, 0), new vscode.Position(totalLines - 1, Number.MAX_SAFE_INTEGER)),
)
}
+31 -105
View File
@@ -33,9 +33,7 @@ export class DiffViewProvider {
this.isEditing = true
// if the file is already open, ensure it's not dirty before getting its contents
if (fileExists) {
const existingDocument = vscode.workspace.textDocuments.find(
(doc) => arePathsEqual(doc.uri.fsPath, absolutePath),
)
const existingDocument = vscode.workspace.textDocuments.find((doc) => arePathsEqual(doc.uri.fsPath, absolutePath))
if (existingDocument && existingDocument.isDirty) {
await existingDocument.save()
}
@@ -61,11 +59,7 @@ export class DiffViewProvider {
const tabs = vscode.window.tabGroups.all
.map((tg) => tg.tabs)
.flat()
.filter(
(tab) =>
tab.input instanceof vscode.TabInputText &&
arePathsEqual(tab.input.uri.fsPath, absolutePath),
)
.filter((tab) => tab.input instanceof vscode.TabInputText && arePathsEqual(tab.input.uri.fsPath, absolutePath))
for (const tab of tabs) {
if (!tab.isDirty) {
await vscode.window.tabGroups.close(tab)
@@ -73,29 +67,16 @@ export class DiffViewProvider {
this.documentWasOpen = true
}
this.activeDiffEditor = await this.openDiffEditor()
this.fadedOverlayController = new DecorationController(
"fadedOverlay",
this.activeDiffEditor,
)
this.activeLineController = new DecorationController(
"activeLine",
this.activeDiffEditor,
)
this.fadedOverlayController = new DecorationController("fadedOverlay", this.activeDiffEditor)
this.activeLineController = new DecorationController("activeLine", this.activeDiffEditor)
// Apply faded overlay to all lines initially
this.fadedOverlayController.addLines(
0,
this.activeDiffEditor.document.lineCount,
)
this.fadedOverlayController.addLines(0, this.activeDiffEditor.document.lineCount)
this.scrollEditorToLine(0) // will this crash for new files?
this.streamedLines = []
}
async update(accumulatedContent: string, isFinal: boolean) {
if (
!this.relPath ||
!this.activeLineController ||
!this.fadedOverlayController
) {
if (!this.relPath || !this.activeLineController || !this.fadedOverlayController) {
throw new Error("Required values not set")
}
this.newContent = accumulatedContent
@@ -113,10 +94,7 @@ export class DiffViewProvider {
// Place cursor at the beginning of the diff editor to keep it out of the way of the stream animation
const beginningOfDocument = new vscode.Position(0, 0)
diffEditor.selection = new vscode.Selection(
beginningOfDocument,
beginningOfDocument,
)
diffEditor.selection = new vscode.Selection(beginningOfDocument, beginningOfDocument)
for (let i = 0; i < diffLines.length; i++) {
const currentLine = this.streamedLines.length + i
@@ -124,16 +102,12 @@ export class DiffViewProvider {
// This is necessary (as compared to inserting one line at a time) to handle cases where html tags on previous lines are auto closed for example
const edit = new vscode.WorkspaceEdit()
const rangeToReplace = new vscode.Range(0, 0, currentLine + 1, 0)
const contentToReplace =
accumulatedLines.slice(0, currentLine + 1).join("\n") + "\n"
const contentToReplace = accumulatedLines.slice(0, currentLine + 1).join("\n") + "\n"
edit.replace(document.uri, rangeToReplace, contentToReplace)
await vscode.workspace.applyEdit(edit)
// Update decorations
this.activeLineController.setActiveLine(currentLine)
this.fadedOverlayController.updateOverlayAfterLine(
currentLine,
document.lineCount,
)
this.fadedOverlayController.updateOverlayAfterLine(currentLine, document.lineCount)
// Scroll to the current line
this.scrollEditorToLine(currentLine)
}
@@ -143,15 +117,7 @@ export class DiffViewProvider {
// Handle any remaining lines if the new content is shorter than the original
if (this.streamedLines.length < document.lineCount) {
const edit = new vscode.WorkspaceEdit()
edit.delete(
document.uri,
new vscode.Range(
this.streamedLines.length,
0,
document.lineCount,
0,
),
)
edit.delete(document.uri, new vscode.Range(this.streamedLines.length, 0, document.lineCount, 0))
await vscode.workspace.applyEdit(edit)
}
// Add empty last line if original content had one
@@ -227,31 +193,19 @@ export class DiffViewProvider {
this.cwd,
) // will be empty string if no errors
const newProblemsMessage =
newProblems.length > 0
? `\n\nNew problems detected after saving the file:\n${newProblems}`
: ""
newProblems.length > 0 ? `\n\nNew problems detected after saving the file:\n${newProblems}` : ""
// If the edited content has different EOL characters, we don't want to show a diff with all the EOL differences.
const newContentEOL = this.newContent.includes("\r\n") ? "\r\n" : "\n"
const normalizedPreSaveContent =
preSaveContent.replace(/\r\n|\n/g, newContentEOL).trimEnd() +
newContentEOL // trimEnd to fix issue where editor adds in extra new line automatically
const normalizedPostSaveContent =
postSaveContent.replace(/\r\n|\n/g, newContentEOL).trimEnd() +
newContentEOL // this is the final content we return to the model to use as the new baseline for future edits
const normalizedPreSaveContent = preSaveContent.replace(/\r\n|\n/g, newContentEOL).trimEnd() + newContentEOL // trimEnd to fix issue where editor adds in extra new line automatically
const normalizedPostSaveContent = postSaveContent.replace(/\r\n|\n/g, newContentEOL).trimEnd() + newContentEOL // this is the final content we return to the model to use as the new baseline for future edits
// just in case the new content has a mix of varying EOL characters
const normalizedNewContent =
this.newContent.replace(/\r\n|\n/g, newContentEOL).trimEnd() +
newContentEOL
const normalizedNewContent = this.newContent.replace(/\r\n|\n/g, newContentEOL).trimEnd() + newContentEOL
let userEdits: string | undefined
if (normalizedPreSaveContent !== normalizedNewContent) {
// user made changes before approving edit. let the model know about user made changes (not including post-save auto-formatting changes)
userEdits = formatResponse.createPrettyPatch(
this.relPath.toPosix(),
normalizedNewContent,
normalizedPreSaveContent,
)
userEdits = formatResponse.createPrettyPatch(this.relPath.toPosix(), normalizedNewContent, normalizedPreSaveContent)
// return { newProblemsMessage, userEdits, finalContent: normalizedPostSaveContent }
} else {
// no changes to cline's edits
@@ -292,9 +246,7 @@ export class DiffViewProvider {
// Remove only the directories we created, in reverse order
for (let i = this.createdDirs.length - 1; i >= 0; i--) {
await fs.rmdir(this.createdDirs[i])
console.log(
`Directory ${this.createdDirs[i]} has been deleted.`,
)
console.log(`Directory ${this.createdDirs[i]} has been deleted.`)
}
console.log(`File ${absolutePath} has been deleted.`)
} else {
@@ -304,24 +256,15 @@ export class DiffViewProvider {
updatedDocument.positionAt(0),
updatedDocument.positionAt(updatedDocument.getText().length),
)
edit.replace(
updatedDocument.uri,
fullRange,
this.originalContent ?? "",
)
edit.replace(updatedDocument.uri, fullRange, this.originalContent ?? "")
// Apply the edit and save, since contents shouldnt have changed this wont show in local history unless of course the user made changes and saved during the edit
await vscode.workspace.applyEdit(edit)
await updatedDocument.save()
console.log(
`File ${absolutePath} has been reverted to its original content.`,
)
console.log(`File ${absolutePath} has been reverted to its original content.`)
if (this.documentWasOpen) {
await vscode.window.showTextDocument(
vscode.Uri.file(absolutePath),
{
preview: false,
},
)
await vscode.window.showTextDocument(vscode.Uri.file(absolutePath), {
preview: false,
})
}
await this.closeAllDiffViews()
}
@@ -333,11 +276,7 @@ export class DiffViewProvider {
private async closeAllDiffViews() {
const tabs = vscode.window.tabGroups.all
.flatMap((tg) => tg.tabs)
.filter(
(tab) =>
tab.input instanceof vscode.TabInputTextDiff &&
tab.input?.original?.scheme === DIFF_VIEW_URI_SCHEME,
)
.filter((tab) => tab.input instanceof vscode.TabInputTextDiff && tab.input?.original?.scheme === DIFF_VIEW_URI_SCHEME)
for (const tab of tabs) {
// trying to close dirty views results in save popup
if (!tab.isDirty) {
@@ -361,32 +300,23 @@ export class DiffViewProvider {
arePathsEqual(tab.input.modified.fsPath, uri.fsPath),
)
if (diffTab && diffTab.input instanceof vscode.TabInputTextDiff) {
const editor = await vscode.window.showTextDocument(
diffTab.input.modified,
)
const editor = await vscode.window.showTextDocument(diffTab.input.modified)
return editor
}
// Open new diff editor
return new Promise<vscode.TextEditor>((resolve, reject) => {
const fileName = path.basename(uri.fsPath)
const fileExists = this.editType === "modify"
const disposable = vscode.window.onDidChangeActiveTextEditor(
(editor) => {
if (
editor &&
arePathsEqual(editor.document.uri.fsPath, uri.fsPath)
) {
disposable.dispose()
resolve(editor)
}
},
)
const disposable = vscode.window.onDidChangeActiveTextEditor((editor) => {
if (editor && arePathsEqual(editor.document.uri.fsPath, uri.fsPath)) {
disposable.dispose()
resolve(editor)
}
})
vscode.commands.executeCommand(
"vscode.diff",
vscode.Uri.parse(`${DIFF_VIEW_URI_SCHEME}:${fileName}`).with({
query: Buffer.from(this.originalContent ?? "").toString(
"base64",
),
query: Buffer.from(this.originalContent ?? "").toString("base64"),
}),
uri,
`${fileName}: ${fileExists ? "Original ↔ Cline's Changes" : "New File"} (Editable)`,
@@ -394,11 +324,7 @@ export class DiffViewProvider {
// This may happen on very slow machines ie project idx
setTimeout(() => {
disposable.dispose()
reject(
new Error(
"Failed to open diff editor, please try again...",
),
)
reject(new Error("Failed to open diff editor, please try again..."))
}, 10_000)
})
}
+3 -17
View File
@@ -6,21 +6,10 @@ import * as vscode from "vscode"
* @param newFileContent The new content of the file to check.
* @returns True if a potential omission is detected, false otherwise.
*/
function detectCodeOmission(
originalFileContent: string,
newFileContent: string,
): boolean {
function detectCodeOmission(originalFileContent: string, newFileContent: string): boolean {
const originalLines = originalFileContent.split("\n")
const newLines = newFileContent.split("\n")
const omissionKeywords = [
"remain",
"remains",
"unchanged",
"rest",
"previous",
"existing",
"...",
]
const omissionKeywords = ["remain", "remains", "unchanged", "rest", "previous", "existing", "..."]
const commentPatterns = [
/^\s*\/\//, // Single-line comment for most languages
@@ -49,10 +38,7 @@ function detectCodeOmission(
* @param originalFileContent The original content of the file.
* @param newFileContent The new content of the file to check.
*/
export function showOmissionWarning(
originalFileContent: string,
newFileContent: string,
): void {
export function showOmissionWarning(originalFileContent: string, newFileContent: string): void {
if (detectCodeOmission(originalFileContent, newFileContent)) {
vscode.window
.showWarningMessage(
+9 -32
View File
@@ -3,10 +3,7 @@ import os from "os"
import * as path from "path"
import * as vscode from "vscode"
export async function downloadTask(
dateTs: number,
conversationHistory: Anthropic.MessageParam[],
) {
export async function downloadTask(dateTs: number, conversationHistory: Anthropic.MessageParam[]) {
// File name
const date = new Date(dateTs)
const month = date.toLocaleString("en-US", { month: "short" }).toLowerCase()
@@ -23,12 +20,9 @@ export async function downloadTask(
// Generate markdown
const markdownContent = conversationHistory
.map((message) => {
const role =
message.role === "user" ? "**User:**" : "**Assistant:**"
const role = message.role === "user" ? "**User:**" : "**Assistant:**"
const content = Array.isArray(message.content)
? message.content
.map((block) => formatContentBlockToMarkdown(block))
.join("\n")
? message.content.map((block) => formatContentBlockToMarkdown(block)).join("\n")
: message.content
return `${role}\n\n${content}\n\n`
})
@@ -37,27 +31,18 @@ export async function downloadTask(
// Prompt user for save location
const saveUri = await vscode.window.showSaveDialog({
filters: { Markdown: ["md"] },
defaultUri: vscode.Uri.file(
path.join(os.homedir(), "Downloads", fileName),
),
defaultUri: vscode.Uri.file(path.join(os.homedir(), "Downloads", fileName)),
})
if (saveUri) {
// Write content to the selected location
await vscode.workspace.fs.writeFile(
saveUri,
Buffer.from(markdownContent),
)
await vscode.workspace.fs.writeFile(saveUri, Buffer.from(markdownContent))
vscode.window.showTextDocument(saveUri, { preview: true })
}
}
export function formatContentBlockToMarkdown(
block:
| Anthropic.TextBlockParam
| Anthropic.ImageBlockParam
| Anthropic.ToolUseBlockParam
| Anthropic.ToolResultBlockParam,
block: Anthropic.TextBlockParam | Anthropic.ImageBlockParam | Anthropic.ToolUseBlockParam | Anthropic.ToolResultBlockParam,
// messages: Anthropic.MessageParam[]
): string {
switch (block.type) {
@@ -69,10 +54,7 @@ export function formatContentBlockToMarkdown(
let input: string
if (typeof block.input === "object" && block.input !== null) {
input = Object.entries(block.input)
.map(
([key, value]) =>
`${key.charAt(0).toUpperCase() + key.slice(1)}: ${value}`,
)
.map(([key, value]) => `${key.charAt(0).toUpperCase() + key.slice(1)}: ${value}`)
.join("\n")
} else {
input = String(block.input)
@@ -86,9 +68,7 @@ export function formatContentBlockToMarkdown(
return `[${toolName}${block.is_error ? " (Error)" : ""}]\n${block.content}`
} else if (Array.isArray(block.content)) {
return `[${toolName}${block.is_error ? " (Error)" : ""}]\n${block.content
.map((contentBlock) =>
formatContentBlockToMarkdown(contentBlock),
)
.map((contentBlock) => formatContentBlockToMarkdown(contentBlock))
.join("\n")}`
} else {
return `[${toolName}${block.is_error ? " (Error)" : ""}]`
@@ -98,10 +78,7 @@ export function formatContentBlockToMarkdown(
}
}
export function findToolName(
toolCallId: string,
messages: Anthropic.MessageParam[],
): string {
export function findToolName(toolCallId: string, messages: Anthropic.MessageParam[]): string {
for (const message of messages) {
if (Array.isArray(message.content)) {
for (const block of message.content) {
+2 -7
View File
@@ -24,9 +24,7 @@ export async function extractTextFromFile(filePath: string): Promise<string> {
if (!isBinary) {
return await fs.readFile(filePath, "utf8")
} else {
throw new Error(
`Cannot read text for file type: ${fileExtension}`,
)
throw new Error(`Cannot read text for file type: ${fileExtension}`)
}
}
}
@@ -48,10 +46,7 @@ async function extractTextFromIPYNB(filePath: string): Promise<string> {
let extractedText = ""
for (const cell of notebook.cells) {
if (
(cell.cell_type === "markdown" || cell.cell_type === "code") &&
cell.source
) {
if ((cell.cell_type === "markdown" || cell.cell_type === "code") && cell.source) {
extractedText += cell.source.join("\n") + "\n"
}
}
+7 -25
View File
@@ -11,19 +11,10 @@ export async function openImage(dataUri: string) {
}
const [, format, base64Data] = matches
const imageBuffer = Buffer.from(base64Data, "base64")
const tempFilePath = path.join(
os.tmpdir(),
`temp_image_${Date.now()}.${format}`,
)
const tempFilePath = path.join(os.tmpdir(), `temp_image_${Date.now()}.${format}`)
try {
await vscode.workspace.fs.writeFile(
vscode.Uri.file(tempFilePath),
imageBuffer,
)
await vscode.commands.executeCommand(
"vscode.open",
vscode.Uri.file(tempFilePath),
)
await vscode.workspace.fs.writeFile(vscode.Uri.file(tempFilePath), imageBuffer)
await vscode.commands.executeCommand("vscode.open", vscode.Uri.file(tempFilePath))
} catch (error) {
vscode.window.showErrorMessage(`Error opening image: ${error}`)
}
@@ -37,21 +28,12 @@ export async function openFile(absolutePath: string) {
try {
for (const group of vscode.window.tabGroups.all) {
const existingTab = group.tabs.find(
(tab) =>
tab.input instanceof vscode.TabInputText &&
arePathsEqual(tab.input.uri.fsPath, uri.fsPath),
(tab) => tab.input instanceof vscode.TabInputText && arePathsEqual(tab.input.uri.fsPath, uri.fsPath),
)
if (existingTab) {
const activeColumn =
vscode.window.activeTextEditor?.viewColumn
const tabColumn = vscode.window.tabGroups.all.find(
(group) => group.tabs.includes(existingTab),
)?.viewColumn
if (
activeColumn &&
activeColumn !== tabColumn &&
!existingTab.isDirty
) {
const activeColumn = vscode.window.activeTextEditor?.viewColumn
const tabColumn = vscode.window.tabGroups.all.find((group) => group.tabs.includes(existingTab))?.viewColumn
if (activeColumn && activeColumn !== tabColumn && !existingTab.isDirty) {
await vscode.window.tabGroups.close(existingTab)
}
break
+4 -12
View File
@@ -7,9 +7,7 @@ interface NotificationOptions {
message: string
}
async function showMacOSNotification(
options: NotificationOptions,
): Promise<void> {
async function showMacOSNotification(options: NotificationOptions): Promise<void> {
const { title, subtitle = "", message } = options
const script = `display notification "${message}" with title "${title}" subtitle "${subtitle}" sound name "Tink"`
@@ -21,9 +19,7 @@ async function showMacOSNotification(
}
}
async function showWindowsNotification(
options: NotificationOptions,
): Promise<void> {
async function showWindowsNotification(options: NotificationOptions): Promise<void> {
const { subtitle, message } = options
const script = `
@@ -54,9 +50,7 @@ async function showWindowsNotification(
}
}
async function showLinuxNotification(
options: NotificationOptions,
): Promise<void> {
async function showLinuxNotification(options: NotificationOptions): Promise<void> {
const { title = "", subtitle = "", message } = options
// Combine subtitle and message if subtitle exists
@@ -69,9 +63,7 @@ async function showLinuxNotification(
}
}
export async function showSystemNotification(
options: NotificationOptions,
): Promise<void> {
export async function showSystemNotification(options: NotificationOptions): Promise<void> {
try {
const { title = "Cline", message } = options
+17 -41
View File
@@ -1,11 +1,7 @@
import pWaitFor from "p-wait-for"
import * as vscode from "vscode"
import { arePathsEqual } from "../../utils/path"
import {
mergePromise,
TerminalProcess,
TerminalProcessResultPromise,
} from "./TerminalProcess"
import { mergePromise, TerminalProcess, TerminalProcessResultPromise } from "./TerminalProcess"
import { TerminalInfo, TerminalRegistry } from "./TerminalRegistry"
/*
@@ -101,9 +97,7 @@ export class TerminalManager {
constructor() {
let disposable: vscode.Disposable | undefined
try {
disposable = (
vscode.window as vscode.Window
).onDidStartTerminalShellExecution?.(async (e) => {
disposable = (vscode.window as vscode.Window).onDidStartTerminalShellExecution?.(async (e) => {
// Creating a read stream here results in a more consistent output. This is most obvious when running the `date` command.
e?.execution?.read()
})
@@ -115,10 +109,7 @@ export class TerminalManager {
}
}
runCommand(
terminalInfo: TerminalInfo,
command: string,
): TerminalProcessResultPromise {
runCommand(terminalInfo: TerminalInfo, command: string): TerminalProcessResultPromise {
terminalInfo.busy = true
terminalInfo.lastCommand = command
const process = new TerminalProcess()
@@ -130,9 +121,7 @@ export class TerminalManager {
// if shell integration is not available, remove terminal so it does not get reused as it may be running a long-running process
process.once("no_shell_integration", () => {
console.log(
`no_shell_integration received for terminal ${terminalInfo.id}`,
)
console.log(`no_shell_integration received for terminal ${terminalInfo.id}`)
// Remove the terminal so we can't reuse it (in case it's running a long-running process)
TerminalRegistry.removeTerminal(terminalInfo.id)
this.terminalIds.delete(terminalInfo.id)
@@ -155,15 +144,9 @@ export class TerminalManager {
process.run(terminalInfo.terminal, command)
} else {
// docs recommend waiting 3s for shell integration to activate
pWaitFor(
() => terminalInfo.terminal.shellIntegration !== undefined,
{ timeout: 4000 },
).finally(() => {
pWaitFor(() => terminalInfo.terminal.shellIntegration !== undefined, { timeout: 4000 }).finally(() => {
const existingProcess = this.processes.get(terminalInfo.id)
if (
existingProcess &&
existingProcess.waitForShellIntegration
) {
if (existingProcess && existingProcess.waitForShellIntegration) {
existingProcess.waitForShellIntegration = false
existingProcess.run(terminalInfo.terminal, command)
}
@@ -175,21 +158,16 @@ export class TerminalManager {
async getOrCreateTerminal(cwd: string): Promise<TerminalInfo> {
// Find available terminal from our pool first (created for this task)
const availableTerminal = TerminalRegistry.getAllTerminals().find(
(t) => {
if (t.busy) {
return false
}
const terminalCwd = t.terminal.shellIntegration?.cwd // one of cline's commands could have changed the cwd of the terminal
if (!terminalCwd) {
return false
}
return arePathsEqual(
vscode.Uri.file(cwd).fsPath,
terminalCwd.fsPath,
)
},
)
const availableTerminal = TerminalRegistry.getAllTerminals().find((t) => {
if (t.busy) {
return false
}
const terminalCwd = t.terminal.shellIntegration?.cwd // one of cline's commands could have changed the cwd of the terminal
if (!terminalCwd) {
return false
}
return arePathsEqual(vscode.Uri.file(cwd).fsPath, terminalCwd.fsPath)
})
if (availableTerminal) {
this.terminalIds.add(availableTerminal.id)
return availableTerminal
@@ -203,9 +181,7 @@ export class TerminalManager {
getTerminals(busy: boolean): { id: number; lastCommand: string }[] {
return Array.from(this.terminalIds)
.map((id) => TerminalRegistry.getTerminal(id))
.filter(
(t): t is TerminalInfo => t !== undefined && t.busy === busy,
)
.filter((t): t is TerminalInfo => t !== undefined && t.busy === busy)
.map((t) => ({ id: t.id, lastCommand: t.lastCommand }))
}
+10 -43
View File
@@ -27,10 +27,7 @@ export class TerminalProcess extends EventEmitter<TerminalProcessEvents> {
// super()
async run(terminal: vscode.Terminal, command: string) {
if (
terminal.shellIntegration &&
terminal.shellIntegration.executeCommand
) {
if (terminal.shellIntegration && terminal.shellIntegration.executeCommand) {
const execution = terminal.shellIntegration.executeCommand(command)
const stream = execution.read()
// todo: need to handle errors
@@ -63,9 +60,7 @@ export class TerminalProcess extends EventEmitter<TerminalProcessEvents> {
// Once we've retrieved any potential output between sequences, we can remove everything up to end of the last sequence
// https://code.visualstudio.com/docs/terminal/shell-integration#_vs-code-custom-sequences-osc-633-st
const vscodeSequenceRegex = /\x1b\]633;.[^\x07]*\x07/g
const lastMatch = [
...data.matchAll(vscodeSequenceRegex),
].pop()
const lastMatch = [...data.matchAll(vscodeSequenceRegex)].pop()
if (lastMatch && lastMatch.index !== undefined) {
data = data.slice(lastMatch.index + lastMatch[0].length)
}
@@ -82,11 +77,7 @@ export class TerminalProcess extends EventEmitter<TerminalProcessEvents> {
lines[0] = lines[0].replace(/[^\x20-\x7E]/g, "")
}
// Check if first two characters are the same, if so remove the first character
if (
lines.length > 0 &&
lines[0].length >= 2 &&
lines[0][0] === lines[0][1]
) {
if (lines.length > 0 && lines[0].length >= 2 && lines[0][0] === lines[0][1]) {
lines[0] = lines[0].slice(1)
}
// Remove everything up to the first alphanumeric character for first two lines
@@ -129,14 +120,7 @@ export class TerminalProcess extends EventEmitter<TerminalProcessEvents> {
clearTimeout(this.hotTimer)
}
// these markers indicate the command is some kind of local dev server recompiling the app, which we want to wait for output of before sending request to cline
const compilingMarkers = [
"compiling",
"building",
"bundling",
"transpiling",
"generating",
"starting",
]
const compilingMarkers = ["compiling", "building", "bundling", "transpiling", "generating", "starting"]
const markerNullifiers = [
"compiled",
"success",
@@ -152,19 +136,13 @@ export class TerminalProcess extends EventEmitter<TerminalProcessEvents> {
"fail",
]
const isCompiling =
compilingMarkers.some((marker) =>
data.toLowerCase().includes(marker.toLowerCase()),
) &&
!markerNullifiers.some((nullifier) =>
data.toLowerCase().includes(nullifier.toLowerCase()),
)
compilingMarkers.some((marker) => data.toLowerCase().includes(marker.toLowerCase())) &&
!markerNullifiers.some((nullifier) => data.toLowerCase().includes(nullifier.toLowerCase()))
this.hotTimer = setTimeout(
() => {
this.isHot = false
},
isCompiling
? PROCESS_HOT_TIMEOUT_COMPILING
: PROCESS_HOT_TIMEOUT_NORMAL,
isCompiling ? PROCESS_HOT_TIMEOUT_COMPILING : PROCESS_HOT_TIMEOUT_NORMAL,
)
// For non-immediately returning commands we want to show loading spinner right away but this wouldnt happen until it emits a line break, so as soon as we get any output we emit "" to let webview know to show spinner
@@ -176,8 +154,7 @@ export class TerminalProcess extends EventEmitter<TerminalProcessEvents> {
this.fullOutput += data
if (this.isListening) {
this.emitIfEol(data)
this.lastRetrievedIndex =
this.fullOutput.length - this.buffer.length
this.lastRetrievedIndex = this.fullOutput.length - this.buffer.length
}
}
@@ -260,20 +237,10 @@ export class TerminalProcess extends EventEmitter<TerminalProcessEvents> {
export type TerminalProcessResultPromise = TerminalProcess & Promise<void>
// Similar to execa's ResultPromise, this lets us create a mixin of both a TerminalProcess and a Promise: https://github.com/sindresorhus/execa/blob/main/lib/methods/promise.js
export function mergePromise(
process: TerminalProcess,
promise: Promise<void>,
): TerminalProcessResultPromise {
export function mergePromise(process: TerminalProcess, promise: Promise<void>): TerminalProcessResultPromise {
const nativePromisePrototype = (async () => {})().constructor.prototype
const descriptors = ["then", "catch", "finally"].map(
(property) =>
[
property,
Reflect.getOwnPropertyDescriptor(
nativePromisePrototype,
property,
),
] as const,
(property) => [property, Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property)] as const,
)
for (const [property, descriptor] of descriptors) {
if (descriptor) {
@@ -50,9 +50,7 @@ export class TerminalRegistry {
}
static getAllTerminals(): TerminalInfo[] {
this.terminals = this.terminals.filter(
(t) => !this.isTerminalClosed(t.terminal),
)
this.terminals = this.terminals.filter((t) => !this.isTerminalClosed(t.terminal))
return this.terminals
}
@@ -154,10 +154,7 @@
}
},
{
"scope": [
"keyword.operator.or.regexp",
"keyword.control.anchor.regexp"
],
"scope": ["keyword.operator.or.regexp", "keyword.control.anchor.regexp"],
"settings": {
"foreground": "#DCDCAA"
}
@@ -345,10 +345,7 @@
}
},
{
"scope": [
"punctuation.section.embedded.begin.php",
"punctuation.section.embedded.end.php"
],
"scope": ["punctuation.section.embedded.begin.php", "punctuation.section.embedded.end.php"],
"settings": {
"foreground": "#569cd6"
}
@@ -367,11 +364,7 @@
},
{
"name": "coloring of the Java import and package identifiers",
"scope": [
"storage.modifier.import.java",
"variable.language.wildcard.java",
"storage.modifier.package.java"
],
"scope": ["storage.modifier.import.java", "variable.language.wildcard.java", "storage.modifier.package.java"],
"settings": {
"foreground": "#d4d4d4"
}
@@ -57,12 +57,7 @@
}
},
{
"scope": [
"constant.numeric",
"constant.other.color.rgb-value",
"constant.other.rgb-value",
"support.constant.color"
],
"scope": ["constant.numeric", "constant.other.color.rgb-value", "constant.other.rgb-value", "support.constant.color"],
"settings": {
"foreground": "#b5cea8"
}
@@ -320,11 +315,7 @@
},
{
"name": "coloring of the Java import and package identifiers",
"scope": [
"storage.modifier.import.java",
"variable.language.wildcard.java",
"storage.modifier.package.java"
],
"scope": ["storage.modifier.import.java", "variable.language.wildcard.java", "storage.modifier.package.java"],
"settings": {
"foreground": "#d4d4d4"
}
@@ -410,11 +401,7 @@
},
{
"name": "Variable and parameter name",
"scope": [
"variable",
"meta.definition.variable.name",
"support.variable"
],
"scope": ["variable", "meta.definition.variable.name", "support.variable"],
"settings": {
"foreground": "#9CDCFE"
}
@@ -3,11 +3,7 @@
"name": "Light High Contrast",
"tokenColors": [
{
"scope": [
"meta.embedded",
"source.groovy.embedded",
"variable.legacy.builtin.python"
],
"scope": ["meta.embedded", "source.groovy.embedded", "variable.legacy.builtin.python"],
"settings": {
"foreground": "#292929"
}
@@ -150,10 +146,7 @@
}
},
{
"scope": [
"punctuation.definition.quote.begin.markdown",
"punctuation.definition.list.begin.markdown"
],
"scope": ["punctuation.definition.quote.begin.markdown", "punctuation.definition.list.begin.markdown"],
"settings": {
"foreground": "#0451A5"
}
@@ -335,10 +328,7 @@
}
},
{
"scope": [
"punctuation.section.embedded.begin.php",
"punctuation.section.embedded.end.php"
],
"scope": ["punctuation.section.embedded.begin.php", "punctuation.section.embedded.end.php"],
"settings": {
"foreground": "#0F4A85"
}
@@ -356,11 +346,7 @@
}
},
{
"scope": [
"storage.modifier.import.java",
"variable.language.wildcard.java",
"storage.modifier.package.java"
],
"scope": ["storage.modifier.import.java", "variable.language.wildcard.java", "storage.modifier.package.java"],
"settings": {
"foreground": "#000000"
}
@@ -519,10 +505,7 @@
}
},
{
"scope": [
"keyword.operator.or.regexp",
"keyword.control.anchor.regexp"
],
"scope": ["keyword.operator.or.regexp", "keyword.control.anchor.regexp"],
"settings": {
"foreground": "#EE0000"
}
@@ -160,10 +160,7 @@
}
},
{
"scope": [
"keyword.operator.or.regexp",
"keyword.control.anchor.regexp"
],
"scope": ["keyword.operator.or.regexp", "keyword.control.anchor.regexp"],
"settings": {
"foreground": "#EE0000"
}
@@ -185,10 +185,7 @@
}
},
{
"scope": [
"punctuation.definition.quote.begin.markdown",
"punctuation.definition.list.begin.markdown"
],
"scope": ["punctuation.definition.quote.begin.markdown", "punctuation.definition.list.begin.markdown"],
"settings": {
"foreground": "#0451a5"
}
@@ -373,10 +370,7 @@
}
},
{
"scope": [
"punctuation.section.embedded.begin.php",
"punctuation.section.embedded.end.php"
],
"scope": ["punctuation.section.embedded.begin.php", "punctuation.section.embedded.end.php"],
"settings": {
"foreground": "#800000"
}
@@ -395,11 +389,7 @@
},
{
"name": "coloring of the Java import and package identifiers",
"scope": [
"storage.modifier.import.java",
"variable.language.wildcard.java",
"storage.modifier.package.java"
],
"scope": ["storage.modifier.import.java", "variable.language.wildcard.java", "storage.modifier.package.java"],
"settings": {
"foreground": "#000000"
}
+9 -45
View File
@@ -32,10 +32,7 @@ function parseThemeString(themeString: string | undefined): any {
export async function getTheme() {
let currentTheme = undefined
const colorTheme =
vscode.workspace
.getConfiguration("workbench")
.get<string>("colorTheme") || "Default Dark Modern"
const colorTheme = vscode.workspace.getConfiguration("workbench").get<string>("colorTheme") || "Default Dark Modern"
try {
for (let i = vscode.extensions.all.length - 1; i >= 0; i--) {
@@ -46,10 +43,7 @@ export async function getTheme() {
if (extension.packageJSON?.contributes?.themes?.length > 0) {
for (const theme of extension.packageJSON.contributes.themes) {
if (theme.label === colorTheme) {
const themePath = path.join(
extension.extensionPath,
theme.path,
)
const themePath = path.join(extension.extensionPath, theme.path)
currentTheme = await fs.readFile(themePath, "utf-8")
break
}
@@ -60,14 +54,7 @@ export async function getTheme() {
if (currentTheme === undefined && defaultThemes[colorTheme]) {
const filename = `${defaultThemes[colorTheme]}.json`
currentTheme = await fs.readFile(
path.join(
getExtensionUri().fsPath,
"src",
"integrations",
"theme",
"default-themes",
filename,
),
path.join(getExtensionUri().fsPath, "src", "integrations", "theme", "default-themes", filename),
"utf-8",
)
}
@@ -77,14 +64,7 @@ export async function getTheme() {
if (parsed.include) {
const includeThemeString = await fs.readFile(
path.join(
getExtensionUri().fsPath,
"src",
"integrations",
"theme",
"default-themes",
parsed.include,
),
path.join(getExtensionUri().fsPath, "src", "integrations", "theme", "default-themes", parsed.include),
"utf-8",
)
const includeTheme = parseThemeString(includeThemeString)
@@ -94,11 +74,7 @@ export async function getTheme() {
const converted = convertTheme(parsed)
converted.base = (
["vs", "hc-black"].includes(converted.base)
? converted.base
: colorTheme.includes("Light")
? "vs"
: "vs-dark"
["vs", "hc-black"].includes(converted.base) ? converted.base : colorTheme.includes("Light") ? "vs" : "vs-dark"
) as any
return converted
@@ -134,11 +110,7 @@ export function mergeJson(
// Merge keys are used to determine whether an item form the second object should override one from the first
const keptFromFirst: any[] = []
firstValue.forEach((item: any) => {
if (
!secondValue.some((item2: any) =>
mergeKeys[key](item, item2),
)
) {
if (!secondValue.some((item2: any) => mergeKeys[key](item, item2))) {
keptFromFirst.push(item)
}
})
@@ -146,16 +118,9 @@ export function mergeJson(
} else {
copyOfFirst[key] = [...firstValue, ...secondValue]
}
} else if (
typeof secondValue === "object" &&
typeof firstValue === "object"
) {
} else if (typeof secondValue === "object" && typeof firstValue === "object") {
// Object
copyOfFirst[key] = mergeJson(
firstValue,
secondValue,
mergeBehavior,
)
copyOfFirst[key] = mergeJson(firstValue, secondValue, mergeBehavior)
} else {
// Other (boolean, number, string)
copyOfFirst[key] = secondValue
@@ -172,6 +137,5 @@ export function mergeJson(
}
function getExtensionUri(): vscode.Uri {
return vscode.extensions.getExtension("saoudrizwan.claude-dev")!
.extensionUri
return vscode.extensions.getExtension("saoudrizwan.claude-dev")!.extensionUri
}
+9 -29
View File
@@ -3,9 +3,7 @@ import * as path from "path"
import { listFiles } from "../../services/glob/list-files"
import { ClineProvider } from "../../core/webview/ClineProvider"
const cwd = vscode.workspace.workspaceFolders
?.map((folder) => folder.uri.fsPath)
.at(0)
const cwd = vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0)
// Note: this is not a drop-in replacement for listFiles at the start of tasks, since that will be done for Desktops when there is no workspace selected
class WorkspaceTracker {
@@ -24,28 +22,20 @@ class WorkspaceTracker {
return
}
const [files, _] = await listFiles(cwd, true, 1_000)
files.forEach((file) =>
this.filePaths.add(this.normalizeFilePath(file)),
)
files.forEach((file) => this.filePaths.add(this.normalizeFilePath(file)))
this.workspaceDidUpdate()
}
private registerListeners() {
// Listen for file creation
// .bind(this) ensures the callback refers to class instance when using this, not necessary when using arrow function
this.disposables.push(
vscode.workspace.onDidCreateFiles(this.onFilesCreated.bind(this)),
)
this.disposables.push(vscode.workspace.onDidCreateFiles(this.onFilesCreated.bind(this)))
// Listen for file deletion
this.disposables.push(
vscode.workspace.onDidDeleteFiles(this.onFilesDeleted.bind(this)),
)
this.disposables.push(vscode.workspace.onDidDeleteFiles(this.onFilesDeleted.bind(this)))
// Listen for file renaming
this.disposables.push(
vscode.workspace.onDidRenameFiles(this.onFilesRenamed.bind(this)),
)
this.disposables.push(vscode.workspace.onDidRenameFiles(this.onFilesRenamed.bind(this)))
/*
An event that is emitted when a workspace folder is added or removed.
@@ -105,23 +95,16 @@ class WorkspaceTracker {
}
private normalizeFilePath(filePath: string): string {
const resolvedPath = cwd
? path.resolve(cwd, filePath)
: path.resolve(filePath)
const resolvedPath = cwd ? path.resolve(cwd, filePath) : path.resolve(filePath)
return filePath.endsWith("/") ? resolvedPath + "/" : resolvedPath
}
private async addFilePath(filePath: string): Promise<string> {
const normalizedPath = this.normalizeFilePath(filePath)
try {
const stat = await vscode.workspace.fs.stat(
vscode.Uri.file(normalizedPath),
)
const stat = await vscode.workspace.fs.stat(vscode.Uri.file(normalizedPath))
const isDirectory = (stat.type & vscode.FileType.Directory) !== 0
const pathWithSlash =
isDirectory && !normalizedPath.endsWith("/")
? normalizedPath + "/"
: normalizedPath
const pathWithSlash = isDirectory && !normalizedPath.endsWith("/") ? normalizedPath + "/" : normalizedPath
this.filePaths.add(pathWithSlash)
return pathWithSlash
} catch {
@@ -133,10 +116,7 @@ class WorkspaceTracker {
private async removeFilePath(filePath: string): Promise<boolean> {
const normalizedPath = this.normalizeFilePath(filePath)
return (
this.filePaths.delete(normalizedPath) ||
this.filePaths.delete(normalizedPath + "/")
)
return this.filePaths.delete(normalizedPath) || this.filePaths.delete(normalizedPath + "/")
}
public dispose() {
+1 -3
View File
@@ -33,9 +33,7 @@ export async function getPythonEnvPath(): Promise<string | undefined> {
return undefined
}
// Get the active python environment path for the current workspace
const pythonEnv = await pythonApi?.environments?.getActiveEnvironmentPath(
workspaceFolder.uri,
)
const pythonEnv = await pythonApi?.environments?.getActiveEnvironmentPath(workspaceFolder.uri)
if (pythonEnv && pythonEnv.path) {
return pythonEnv.path
} else {