Feat: Reduce diff edit errors when restoring tasks w/o checkpoints (#4232)
* Added file context warnings to reduce diff edit errors when resuming a task after it has been restored * changeset * Prompt tweak
This commit is contained in:
1 parent
54a7fed77b
commit
e8e8eac820
5 files changed
+203
-15
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
Added file context warnings to reduce diff edit errors when resuming a task after it has been restored
|
||||
@@ -1,7 +1,10 @@
|
||||
import * as path from "path"
|
||||
import * as vscode from "vscode"
|
||||
import { getTaskMetadata, saveTaskMetadata } from "@core/storage/disk"
|
||||
import { getWorkspaceState, updateWorkspaceState } from "@core/storage/state"
|
||||
import { getGlobalState } from "@core/storage/state"
|
||||
import type { FileMetadataEntry } from "./ContextTrackerTypes"
|
||||
import type { ClineMessage } from "@shared/ExtensionMessage"
|
||||
|
||||
// This class is responsible for tracking file operations that may result in stale context.
|
||||
// If a user modifies a file outside of Cline, the context may become stale and need to be updated.
|
||||
@@ -11,10 +14,12 @@ import type { FileMetadataEntry } from "./ContextTrackerTypes"
|
||||
// a diff edit because the file was modified since Cline last read it.
|
||||
|
||||
// FileContextTracker
|
||||
//
|
||||
// This class is responsible for tracking file operations.
|
||||
// If the full contents of a file are pass to Cline via a tool, mention, or edit, the file is marked as active.
|
||||
// If a file is modified outside of Cline, we detect and track this change to prevent stale context.
|
||||
/**
|
||||
This class is responsible for tracking file operations.
|
||||
If the full contents of a file are passed to Cline via a tool, mention, or edit, the file is marked as active.
|
||||
If a file is modified outside of Cline, we detect and track this change to prevent stale context.
|
||||
This is used when restoring a task (non-git "checkpoint" restore), and mid-task.
|
||||
*/
|
||||
export class FileContextTracker {
|
||||
private context: vscode.ExtensionContext
|
||||
readonly taskId: string
|
||||
@@ -29,7 +34,9 @@ export class FileContextTracker {
|
||||
this.taskId = taskId
|
||||
}
|
||||
|
||||
// Gets the current working directory or returns undefined if it cannot be determined
|
||||
/**
|
||||
* Gets the current working directory or returns undefined if it cannot be determined
|
||||
*/
|
||||
private getCwd(): string | undefined {
|
||||
const cwd = vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0)
|
||||
if (!cwd) {
|
||||
@@ -38,7 +45,9 @@ export class FileContextTracker {
|
||||
return cwd
|
||||
}
|
||||
|
||||
// File watchers are set up for each file that is tracked in the task metadata.
|
||||
/**
|
||||
* File watchers are set up for each file that is tracked in the task metadata.
|
||||
*/
|
||||
async setupFileWatcher(filePath: string) {
|
||||
// Only setup watcher if it doesn't already exist for this file
|
||||
if (this.fileWatchers.has(filePath)) {
|
||||
@@ -70,8 +79,10 @@ export class FileContextTracker {
|
||||
this.fileWatchers.set(filePath, watcher)
|
||||
}
|
||||
|
||||
// Tracks a file operation in metadata and sets up a watcher for the file
|
||||
// This is the main entry point for FileContextTracker and is called when a file is passed to Cline via a tool, mention, or edit.
|
||||
/**
|
||||
* Tracks a file operation in metadata and sets up a watcher for the file
|
||||
* This is the main entry point for FileContextTracker and is called when a file is passed to Cline via a tool, mention, or edit.
|
||||
*/
|
||||
async trackFileContext(filePath: string, operation: "read_tool" | "user_edited" | "cline_edited" | "file_mentioned") {
|
||||
try {
|
||||
const cwd = this.getCwd()
|
||||
@@ -89,9 +100,11 @@ export class FileContextTracker {
|
||||
}
|
||||
}
|
||||
|
||||
// Adds a file to the metadata tracker
|
||||
// This handles the business logic of determining if the file is new, stale, or active.
|
||||
// It also updates the metadata with the latest read/edit dates.
|
||||
/**
|
||||
* Adds a file to the metadata tracker
|
||||
* This handles the business logic of determining if the file is new, stale, or active.
|
||||
* It also updates the metadata with the latest read/edit dates.
|
||||
*/
|
||||
async addFileToFileContextTracker(
|
||||
context: vscode.ExtensionContext,
|
||||
taskId: string,
|
||||
@@ -154,23 +167,149 @@ export class FileContextTracker {
|
||||
}
|
||||
}
|
||||
|
||||
// Returns (and then clears) the set of recently modified files
|
||||
/**
|
||||
* Returns (and then clears) the set of recently modified files
|
||||
*/
|
||||
getAndClearRecentlyModifiedFiles(): string[] {
|
||||
const files = Array.from(this.recentlyModifiedFiles)
|
||||
this.recentlyModifiedFiles.clear()
|
||||
return files
|
||||
}
|
||||
|
||||
// Marks a file as edited by Cline to prevent false positives in file watchers
|
||||
/**
|
||||
* Marks a file as edited by Cline to prevent false positives in file watchers
|
||||
*/
|
||||
markFileAsEditedByCline(filePath: string): void {
|
||||
this.recentlyEditedByCline.add(filePath)
|
||||
}
|
||||
|
||||
// Disposes all file watchers
|
||||
/**
|
||||
* Disposes all file watchers
|
||||
*/
|
||||
dispose(): void {
|
||||
for (const watcher of this.fileWatchers.values()) {
|
||||
watcher.dispose()
|
||||
}
|
||||
this.fileWatchers.clear()
|
||||
}
|
||||
|
||||
/**
|
||||
* Detects files that were edited by Cline or users after a specific message timestamp
|
||||
* This is used when restoring checkpoints to warn about potential file content mismatches
|
||||
*/
|
||||
async detectFilesEditedAfterMessage(messageTs: number, deletedMessages: ClineMessage[]): Promise<string[]> {
|
||||
const editedFiles: string[] = []
|
||||
|
||||
try {
|
||||
// Check task metadata for files that were edited by Cline or users after the message timestamp
|
||||
const taskMetadata = await getTaskMetadata(this.context, this.taskId)
|
||||
|
||||
if (taskMetadata?.files_in_context) {
|
||||
for (const fileEntry of taskMetadata.files_in_context) {
|
||||
const clineEditedAfter = fileEntry.cline_edit_date && fileEntry.cline_edit_date > messageTs
|
||||
const userEditedAfter = fileEntry.user_edit_date && fileEntry.user_edit_date > messageTs
|
||||
|
||||
if (clineEditedAfter || userEditedAfter) {
|
||||
editedFiles.push(fileEntry.path)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error checking file context metadata:", error)
|
||||
}
|
||||
|
||||
// Also check deleted task messages for file operations
|
||||
for (const message of deletedMessages) {
|
||||
if (message.say === "tool" && message.text) {
|
||||
try {
|
||||
const toolData = JSON.parse(message.text)
|
||||
if ((toolData.tool === "editedExistingFile" || toolData.tool === "newFileCreated") && toolData.path) {
|
||||
if (!editedFiles.includes(toolData.path)) {
|
||||
editedFiles.push(toolData.path)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error checking task messages:", error)
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...new Set(editedFiles)]
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores pending file context warning in workspace state so it persists across task reinitialization
|
||||
*/
|
||||
async storePendingFileContextWarning(files: string[]): Promise<void> {
|
||||
try {
|
||||
const key = `pendingFileContextWarning_${this.taskId}`
|
||||
await updateWorkspaceState(this.context, key, files)
|
||||
} catch (error) {
|
||||
console.error("Error storing pending file context warning:", error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves pending file context warning from workspace state (without clearing it)
|
||||
*/
|
||||
async retrievePendingFileContextWarning(): Promise<string[] | undefined> {
|
||||
try {
|
||||
const key = `pendingFileContextWarning_${this.taskId}`
|
||||
const files = (await getWorkspaceState(this.context, key)) as string[]
|
||||
return files
|
||||
} catch (error) {
|
||||
console.error("Error retrieving pending file context warning:", error)
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves and clears pending file context warning from workspace state
|
||||
*/
|
||||
async retrieveAndClearPendingFileContextWarning(): Promise<string[] | undefined> {
|
||||
try {
|
||||
const files = await this.retrievePendingFileContextWarning()
|
||||
if (files) {
|
||||
await updateWorkspaceState(this.context, `pendingFileContextWarning_${this.taskId}`, undefined)
|
||||
return files
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error retrieving pending file context warning:", error)
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Static method to clean up orphaned pending file context warnings at startup
|
||||
* This removes warnings for tasks that may no longer exist
|
||||
*/
|
||||
static async cleanupOrphanedWarnings(context: vscode.ExtensionContext): Promise<void> {
|
||||
const startTime = Date.now()
|
||||
try {
|
||||
const taskHistory = ((await getGlobalState(context, "taskHistory")) as Array<{ id: string }>) || []
|
||||
const existingTaskIds = new Set(taskHistory.map((task) => task.id))
|
||||
const allStateKeys = context.workspaceState.keys()
|
||||
const pendingWarningKeys = allStateKeys.filter((key) => key.startsWith("pendingFileContextWarning_"))
|
||||
|
||||
const orphanedPendingContextTasks: string[] = []
|
||||
for (const key of pendingWarningKeys) {
|
||||
const taskId = key.replace("pendingFileContextWarning_", "")
|
||||
if (!existingTaskIds.has(taskId)) {
|
||||
orphanedPendingContextTasks.push(key)
|
||||
}
|
||||
}
|
||||
|
||||
if (orphanedPendingContextTasks.length > 0) {
|
||||
for (const key of orphanedPendingContextTasks) {
|
||||
await updateWorkspaceState(context, key, undefined)
|
||||
}
|
||||
}
|
||||
|
||||
const duration = Date.now() - startTime
|
||||
console.log(
|
||||
`FileContextTracker: Processed ${existingTaskIds.size} tasks, found ${pendingWarningKeys.length} pending warnings, ${orphanedPendingContextTasks.length} orphaned, deleted ${orphanedPendingContextTasks.length}, took ${duration}ms`,
|
||||
)
|
||||
} catch (error) {
|
||||
console.error("Error cleaning up orphaned file context warnings:", error)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -149,13 +149,14 @@ Otherwise, if you have not completed the task and do not need additional informa
|
||||
cwd: string,
|
||||
wasRecent: boolean | 0 | undefined,
|
||||
responseText?: string,
|
||||
hasPendingFileContextWarnings?: boolean,
|
||||
): [string, string] => {
|
||||
const taskResumptionMessage = `[TASK RESUMPTION] ${
|
||||
mode === "plan"
|
||||
? `This task was interrupted ${agoText}. The conversation may have been incomplete. Be aware that the project state may have changed since then. The current working directory is now '${cwd.toPosix()}'.\n\nNote: If you previously attempted a tool use that the user did not provide a result for, you should assume the tool use was not successful. However you are in PLAN MODE, so rather than continuing the task, you must respond to the user's message.`
|
||||
: `This task was interrupted ${agoText}. It may or may not be complete, so please reassess the task context. Be aware that the project state may have changed since then. The current working directory is now '${cwd.toPosix()}'. If the task has not been completed, retry the last step before interruption and proceed with completing the task.\n\nNote: If you previously attempted a tool use that the user did not provide a result for, you should assume the tool use was not successful and assess whether you should retry. If the last tool was a browser_action, the browser has been closed and you must launch a new browser if needed.`
|
||||
}${
|
||||
wasRecent
|
||||
wasRecent && !hasPendingFileContextWarnings
|
||||
? "\n\nIMPORTANT: If the last tool use was a replace_in_file or write_to_file that was interrupted, the file was reverted back to its original state before the interrupted edit, and you do NOT need to re-read the file as you already have its up-to-date contents."
|
||||
: ""
|
||||
}`
|
||||
@@ -240,6 +241,19 @@ Otherwise, if you have not completed the task and do not need additional informa
|
||||
|
||||
cursorRulesLocalDirectoryInstructions: (cwd: string, content: string) =>
|
||||
`# .cursor/rules\n\nThe following is provided by a root-level .cursor/rules directory where the user has specified instructions for this working directory (${cwd.toPosix()})\n\n${content}`,
|
||||
|
||||
fileContextWarning: (editedFiles: string[]): string => {
|
||||
const fileCount = editedFiles.length
|
||||
const fileVerb = fileCount === 1 ? "file has" : "files have"
|
||||
const fileDemonstrativePronoun = fileCount === 1 ? "this file" : "these files"
|
||||
const filePersonalPronoun = fileCount === 1 ? "it" : "they"
|
||||
|
||||
return (
|
||||
`<explicit_instructions>\nCRITICAL FILE STATE ALERT: ${fileCount} ${fileVerb} been externally modified since your last interaction. Your cached understanding of ${fileDemonstrativePronoun} is now stale and unreliable. Before making ANY modifications to ${fileDemonstrativePronoun}, you must execute read_file to obtain the current state, as ${filePersonalPronoun} may contain completely different content than what you expect:\n` +
|
||||
`${editedFiles.map((file) => ` ${path.resolve(file).toPosix()}`).join("\n")}\n` +
|
||||
`Failure to re-read before editing will result in replace_in_file edit errors, requiring subsequent attempts and wasting tokens. You DO NOT need to re-read these files after subsequent edits, unless instructed to do so.\n</explicit_instructions>`
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
// to avoid circular dependency
|
||||
|
||||
@@ -454,6 +454,18 @@ export class Task {
|
||||
const deletedMessages = this.clineMessages.slice(messageIndex + 1)
|
||||
const deletedApiReqsMetrics = getApiMetrics(combineApiRequests(combineCommandSequences(deletedMessages)))
|
||||
|
||||
// Detect files edited after this message timestamp for file context warning
|
||||
// Only needed for task-only restores when a user edits a message or restores the task context, but not the files.
|
||||
if (restoreType === "task") {
|
||||
const filesEditedAfterMessage = await this.fileContextTracker.detectFilesEditedAfterMessage(
|
||||
messageTs,
|
||||
deletedMessages,
|
||||
)
|
||||
if (filesEditedAfterMessage.length > 0) {
|
||||
await this.fileContextTracker.storePendingFileContextWarning(filesEditedAfterMessage)
|
||||
}
|
||||
}
|
||||
|
||||
const newClineMessages = this.clineMessages.slice(0, messageIndex + 1)
|
||||
await this.overwriteClineMessages(newClineMessages) // calls saveClineMessages which saves historyItem
|
||||
|
||||
@@ -1131,12 +1143,17 @@ export class Task {
|
||||
|
||||
const wasRecent = lastClineMessage?.ts && Date.now() - lastClineMessage.ts < 30_000
|
||||
|
||||
// Check if there are pending file context warnings before calling taskResumption
|
||||
const pendingContextWarning = await this.fileContextTracker.retrieveAndClearPendingFileContextWarning()
|
||||
const hasPendingFileContextWarnings = pendingContextWarning && pendingContextWarning.length > 0
|
||||
|
||||
const [taskResumptionMessage, userResponseMessage] = formatResponse.taskResumption(
|
||||
this.chatSettings?.mode === "plan" ? "plan" : "act",
|
||||
agoText,
|
||||
cwd,
|
||||
wasRecent,
|
||||
responseText,
|
||||
hasPendingFileContextWarnings,
|
||||
)
|
||||
|
||||
if (taskResumptionMessage !== "") {
|
||||
@@ -1167,6 +1184,15 @@ export class Task {
|
||||
}
|
||||
}
|
||||
|
||||
// Inject file context warning if there were pending warnings from message editing
|
||||
if (pendingContextWarning && pendingContextWarning.length > 0) {
|
||||
const fileContextWarning = formatResponse.fileContextWarning(pendingContextWarning)
|
||||
newUserContent.push({
|
||||
type: "text",
|
||||
text: fileContextWarning,
|
||||
})
|
||||
}
|
||||
|
||||
await this.overwriteApiConversationHistory(modifiedApiConversationHistory)
|
||||
await this.initiateTaskLoop(newUserContent)
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ import { sendAccountButtonClickedEvent } from "./core/controller/ui/subscribeToA
|
||||
import { migratePlanActGlobalToWorkspaceStorage, migrateCustomInstructionsToGlobalRules } from "./core/storage/state"
|
||||
|
||||
import { sendFocusChatInputEvent } from "./core/controller/ui/subscribeToFocusChatInput"
|
||||
import { FileContextTracker } from "./core/context/context-tracking/FileContextTracker"
|
||||
/*
|
||||
Built using https://github.com/microsoft/vscode-webview-ui-toolkit
|
||||
|
||||
@@ -52,6 +53,9 @@ export async function activate(context: vscode.ExtensionContext) {
|
||||
// Migrate custom instructions to global Cline rules (one-time cleanup)
|
||||
await migrateCustomInstructionsToGlobalRules(context)
|
||||
|
||||
// Clean up orphaned file context warnings (startup cleanup)
|
||||
await FileContextTracker.cleanupOrphanedWarnings(context)
|
||||
|
||||
// Version checking for autoupdate notification
|
||||
const currentVersion = context.extension.packageJSON.version
|
||||
const previousVersion = context.globalState.get<string>("clineVersion")
|
||||
|
||||
Reference in new issue
Block a user