Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions src/core/task-persistence/TaskHistoryStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -345,8 +345,9 @@ export class TaskHistoryStore {
let dirEntries: string[]
try {
dirEntries = await fs.readdir(tasksDir)
} catch {
return // tasks dir doesn't exist yet
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return
throw error
}

// Filter out hidden and reserved names
Expand Down Expand Up @@ -1315,7 +1316,7 @@ export class TaskHistoryStore {
* Get the tasks base directory path, resolving custom storage paths.
*/
private async getTasksDir(): Promise<string> {
const basePath = await getStorageBasePath(this.globalStoragePath)
const basePath = await getStorageBasePath(this.globalStoragePath, true)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All tests still pass if I remove this true, or the one in getTaskDirectoryPath. Could a test with the real storage helper and an unusable custom path make sure that nothing goes to the default root?

return path.join(basePath, "tasks")
}

Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

33 changes: 33 additions & 0 deletions src/core/task-persistence/__tests__/configuredStorage.spec.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 19 additions & 0 deletions src/core/task/Task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1637,6 +1637,16 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
return saved
}

private readonly unsavedHistory = new Set<"chat" | "API">()

/** Show the first failure for each history until a subsequent write succeeds. */
private reportHistorySaveFailure(history: "chat" | "API", error: unknown): void {
if (this.unsavedHistory.has(history)) return
this.unsavedHistory.add(history)
const detail = error instanceof Error ? error.message : String(error)
void vscode.window?.showErrorMessage?.(`Zoo could not save this task's ${history} history. ${detail}`)
}

/** Persists the current API conversation history to disk, returning false on I/O errors. */
private async saveApiConversationHistory(merge = true): Promise<boolean> {
try {
Expand All @@ -1646,9 +1656,11 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
globalStoragePath: this.globalStoragePath,
merge,
})
this.unsavedHistory.delete("API")
return true
} catch (error) {
console.error("Failed to save API conversation history:", error)
this.reportHistorySaveFailure("API", error)
return false
}
}
Expand Down Expand Up @@ -1853,8 +1865,10 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
})
} catch (error) {
console.error("Failed to save Roo messages:", error)
this.reportHistorySaveFailure("chat", error)
return false
}
this.unsavedHistory.delete("chat")

try {
if (this._taskApiConfigName === undefined) {
Expand Down Expand Up @@ -3121,6 +3135,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
await this.providerRef.deref()?.postStateToWebviewWithoutTaskHistory()

await this.say("text", task, images)
if (this.unsavedHistory.has("chat")) throw new Error("The initial task prompt could not be saved")

// Check for too many MCP tools and warn the user
const { enabledToolCount, enabledServerCount } = await this.getEnabledMcpToolsCount()
Expand Down Expand Up @@ -6445,6 +6460,10 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
return cleanConversationHistory
}
public async checkpointRestore(options: CheckpointRestoreOptions) {
if (options.mode === "restore") {
// A rewind must be able to persist its histories before changing the workspace.
await getTaskDirectoryPath(this.globalStoragePath, this.taskId, { requireWritable: true })
}
return checkpointRestore(this, options)
}

Expand Down
44 changes: 44 additions & 0 deletions src/core/task/__tests__/Task.spec.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 17 additions & 12 deletions src/core/tools/ExecuteCommandTool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -451,19 +451,24 @@ export async function executeCommandInTerminal(

// Create OutputInterceptor if we have storage available
if (globalStoragePath) {
const taskDir = await getTaskDirectoryPath(globalStoragePath, task.taskId)
const storageDir = path.join(taskDir, "command-output")
const providerState = await provider?.getState()
const terminalOutputPreviewSize =
providerState?.terminalOutputPreviewSize ?? DEFAULT_TERMINAL_OUTPUT_PREVIEW_SIZE

interceptor = new OutputInterceptor({
executionId,
taskId: task.taskId,
command,
storageDir,
previewSize: terminalOutputPreviewSize,
const taskDir = await getTaskDirectoryPath(globalStoragePath, task.taskId).catch((error: unknown) => {
console.warn("Could not open command artifact storage. The command will still run.", error)
return undefined
})
if (taskDir) {
const storageDir = path.join(taskDir, "command-output")
const providerState = await provider?.getState()
const terminalOutputPreviewSize =
providerState?.terminalOutputPreviewSize ?? DEFAULT_TERMINAL_OUTPUT_PREVIEW_SIZE

interceptor = new OutputInterceptor({
executionId,
taskId: task.taskId,
command,
storageDir,
previewSize: terminalOutputPreviewSize,
})
}
}

let accumulatedOutput = ""
Expand Down
30 changes: 30 additions & 0 deletions src/core/tools/__tests__/executeCommand.spec.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

36 changes: 19 additions & 17 deletions src/core/webview/ClineProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -656,6 +656,9 @@ export class ClineProvider
elapsedMs: Date.now() - startedAt,
})
this.log(`[initializeTaskHistoryStore] Error: ${error instanceof Error ? error.message : String(error)}`)
void vscode.window.showWarningMessage(
`Zoo could not load conversation history: ${error instanceof Error ? error.message : String(error)}. Check the configured storage path and restart VS Code after it is available.`,
)
}
}

Expand Down Expand Up @@ -2841,10 +2844,14 @@ export class ClineProvider
taskId: id,
})
try {
if (id !== this.getCurrentTask()?.taskId) {
// Non-current task.
const current = this.getCurrentTask()
if (id !== current?.taskId) {
const { historyItem } = await this.getTaskWithId(id)
await this.createTaskWithHistoryItem(historyItem) // Clears existing task.
await this.createTaskWithHistoryItem(historyItem)
} else if (current.abort || current.abandoned) {
// A failed cancellation lookup leaves the stopped task visible.
// A later history lookup can replace it once storage is available.
await this.restartTaskIfCurrent(current)
}

await this.postMessageToWebview({ type: "action", action: "chatButtonClicked" })
Expand Down Expand Up @@ -4516,20 +4523,14 @@ export class ClineProvider
}

private async cancelTaskInternal(task: Task): Promise<void> {
let historyItem: HistoryItem | undefined
try {
const history = await this.getTaskWithId(task.taskId)
historyItem = history.historyItem
} catch (error) {
// During task startup there is a short window where currentTask exists
// but task history has not been persisted yet. Cancelling should still
// abort safely; we just skip post-cancel rehydration in that case.
if (error instanceof Error && error.message === "Task not found") {
this.log(`[cancelTask] task history missing for ${task.taskId}; skipping rehydrate`)
} else {
throw error
}
}
// Storage may be missing at startup or inaccessible. The history lookup
// is only needed for rehydration and must never delay aborting the request.
const historyRead = this.getTaskWithId(task.taskId)
.then(({ historyItem }) => historyItem)
.catch(() => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this read fails, cancelTask now succeeds and leaves the aborted task current. Can the checkpoint restore handlers then reset the workspace on that task while the history rewind is not saved?

this.log(`[cancelTask] task history unavailable for ${task.taskId}; skipping rehydrate`)
return undefined
Comment thread
cartridgebasic marked this conversation as resolved.
Resolved
})

// Preserve parent and root task information for history item.
let rootTask = task.rootTask
Expand Down Expand Up @@ -4573,6 +4574,7 @@ export class ClineProvider
// Wait for abortTask to fully settle (including its final saveClineMessages write)
// before we persist "interrupted", so our write is always the last one.
await abortPromise.catch(() => {})
let historyItem = await historyRead

// Defensive safeguard: if current instance already changed, skip rehydrate
const current = this.getCurrentTask()
Expand Down
Loading
Loading