diff --git a/src/core/task-persistence/TaskHistoryStore.ts b/src/core/task-persistence/TaskHistoryStore.ts index e0bb54998c3..b3d5ad08444 100644 --- a/src/core/task-persistence/TaskHistoryStore.ts +++ b/src/core/task-persistence/TaskHistoryStore.ts @@ -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 @@ -1315,7 +1316,7 @@ export class TaskHistoryStore { * Get the tasks base directory path, resolving custom storage paths. */ private async getTasksDir(): Promise { - const basePath = await getStorageBasePath(this.globalStoragePath) + const basePath = await getStorageBasePath(this.globalStoragePath, true) return path.join(basePath, "tasks") } diff --git a/src/core/task-persistence/__tests__/TaskHistoryStore.deleteSemantics.spec.ts b/src/core/task-persistence/__tests__/TaskHistoryStore.deleteSemantics.spec.ts index 875c7dcb9a7..814579281a8 100644 --- a/src/core/task-persistence/__tests__/TaskHistoryStore.deleteSemantics.spec.ts +++ b/src/core/task-persistence/__tests__/TaskHistoryStore.deleteSemantics.spec.ts @@ -225,14 +225,27 @@ describe("TaskHistoryStore best-effort deletion semantics", () => { const store = createStore() await store.initialize() onWrite.mockClear() + vi.mocked(withFileLock).mockClear() await expect(store.delete("never-existed")).resolves.toBeUndefined() expect(store.get("never-existed")).toBeUndefined() expect(onWrite).toHaveBeenCalledTimes(1) + expect(withFileLock).not.toHaveBeenCalled() }) }) describe("deleteMany()", () => { + it("skips locking absent task directories and still writes the batch through", async () => { + const store = createStore() + await store.initialize() + onWrite.mockClear() + vi.mocked(withFileLock).mockClear() + + await expect(store.deleteMany(["never-existed"])).resolves.toBeUndefined() + expect(withFileLock).not.toHaveBeenCalled() + expect(onWrite).toHaveBeenCalledTimes(1) + }) + it("continues the batch after a failed unlink, evicts every entry, and writes through exactly once", async () => { const store = createStore() await store.initialize() diff --git a/src/core/task-persistence/__tests__/TaskHistoryStore.spec.ts b/src/core/task-persistence/__tests__/TaskHistoryStore.spec.ts index 3e277ac867e..642583374fd 100644 --- a/src/core/task-persistence/__tests__/TaskHistoryStore.spec.ts +++ b/src/core/task-persistence/__tests__/TaskHistoryStore.spec.ts @@ -53,6 +53,10 @@ describe("TaskHistoryStore", () => { }) describe("initialize()", () => { + it("reports a non-directory storage path instead of treating it as empty history", async () => { + await fs.writeFile(path.join(tmpDir, "tasks"), "blocked") + await expect(store.reconcile({ forceRefresh: true })).rejects.toMatchObject({ code: "ENOTDIR" }) + }) it("initializes from empty state (no index, no task dirs)", async () => { await store.initialize() expect(store.getAll()).toEqual([]) diff --git a/src/core/task-persistence/__tests__/configuredStorage.spec.ts b/src/core/task-persistence/__tests__/configuredStorage.spec.ts new file mode 100644 index 00000000000..f0e90a72330 --- /dev/null +++ b/src/core/task-persistence/__tests__/configuredStorage.spec.ts @@ -0,0 +1,33 @@ +import * as fs from "node:fs/promises" +import * as os from "node:os" +import * as path from "node:path" +import * as vscode from "vscode" + +import { getTaskDirectoryPath } from "../../../utils/storage" +import { makeWorkspaceConfiguration } from "../../../test-utils/vscode" +import { TaskHistoryStore } from "../TaskHistoryStore" + +it("does not open or create default history when the configured root is a file", async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "zoo-configured-storage-")) + const defaultRoot = path.join(root, "default") + const customPath = path.join(root, "unavailable") + const config = vi + .spyOn(vscode.workspace, "getConfiguration") + .mockReturnValue(makeWorkspaceConfiguration({ customStoragePath: customPath })) + const store = new TaskHistoryStore(defaultRoot) + try { + await fs.mkdir(defaultRoot) + await fs.writeFile(customPath, "This is a file, not a directory") + await expect(getTaskDirectoryPath(defaultRoot, "task")).rejects.toThrow( + "Configured Zoo storage path is unavailable", + ) + await expect(store.reconcile({ forceRefresh: true })).rejects.toThrow( + "Configured Zoo storage path is unavailable", + ) + expect(await fs.readdir(defaultRoot)).toEqual([]) + } finally { + store.dispose() + config.mockRestore() + await fs.rm(root, { recursive: true, force: true }) + } +}) diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 3b2771ddfa7..29800d95ed8 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -1637,6 +1637,16 @@ export class Task extends EventEmitter 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 { try { @@ -1646,9 +1656,11 @@ export class Task extends EventEmitter 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 } } @@ -1853,8 +1865,10 @@ export class Task extends EventEmitter 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) { @@ -3121,6 +3135,7 @@ export class Task extends EventEmitter 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() @@ -6445,6 +6460,10 @@ export class Task extends EventEmitter 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) } diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index cea34e05d1c..6ac6324d173 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -22,6 +22,7 @@ import { type TaskLike, } from "@roo-code/types" import { TelemetryService } from "@roo-code/telemetry" +import { getTaskDirectoryPath } from "../../../utils/storage" import { MODEL_FETCH_TIMEOUT_MS, Task } from "../Task" import { SYSTEM_PROMPT } from "../../prompts/system" @@ -3985,6 +3986,14 @@ describe("Cline", () => { vi.clearAllMocks() }) + beforeEach(() => { + // Mention expansion uses a saved start. The storage path is covered separately. + const save = vi + .spyOn(getTaskTestAccess(Task.prototype), "saveClineMessages") + .mockResolvedValue(true) + return () => save.mockRestore() + }) + it.each([ { label: "all generated", @@ -7789,6 +7798,41 @@ describe("Cline", () => { }) describe("startTask", () => { + it("does not start the model when it cannot persist the initial prompt", async () => { + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "new task", + startTask: false, + }) + const failure = new Error("Configured storage unavailable") + vi.mocked(getTaskDirectoryPath).mockRejectedValueOnce(failure) + const notification = vi.spyOn(vscode.window, "showErrorMessage") + const loop = vi.spyOn(getTaskTestAccess(task), "initiateTaskLoop").mockResolvedValue(undefined) + + await expect(getTaskTestAccess(task).startTask("new task")).rejects.toThrow( + "The initial task prompt could not be saved", + ) + expect(notification).toHaveBeenCalledWith( + "Zoo could not save this task's chat history. Configured storage unavailable", + ) + expect(loop).not.toHaveBeenCalled() + }) + + it("rejects checkpoint restore before rewinding when task history storage is unavailable", async () => { + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "test", + startTask: false, + }) + const failure = new Error("Configured storage unavailable") + const directory = vi.mocked(getTaskDirectoryPath).mockRejectedValueOnce(failure) + await expect(task.checkpointRestore({ ts: 1, commitHash: "a".repeat(40), mode: "restore" })).rejects.toBe( + failure, + ) + expect(directory).toHaveBeenLastCalledWith(expect.any(String), task.taskId, { requireWritable: true }) + }) it("posts a clean state immediately before adding the first task message", async () => { const task = new Task({ provider: mockProvider, diff --git a/src/core/tools/ExecuteCommandTool.ts b/src/core/tools/ExecuteCommandTool.ts index 9855e6e417e..9a46efb9012 100644 --- a/src/core/tools/ExecuteCommandTool.ts +++ b/src/core/tools/ExecuteCommandTool.ts @@ -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 = "" diff --git a/src/core/tools/__tests__/executeCommand.spec.ts b/src/core/tools/__tests__/executeCommand.spec.ts index 774601c5cab..f256fae6a43 100644 --- a/src/core/tools/__tests__/executeCommand.spec.ts +++ b/src/core/tools/__tests__/executeCommand.spec.ts @@ -10,6 +10,7 @@ import { TerminalRegistry } from "../../../integrations/terminal/TerminalRegistr import { Terminal } from "../../../integrations/terminal/Terminal" import { ExecaTerminal } from "../../../integrations/terminal/ExecaTerminal" import type { RooTerminalCallbacks } from "../../../integrations/terminal/types" +import { getTaskDirectoryPath } from "../../../utils/storage" const filesystemMocks = vitest.hoisted(() => ({ access: vitest.fn(), stat: vitest.fn(), @@ -18,6 +19,8 @@ const filesystemMocks = vitest.hoisted(() => ({ // ExecuteCommandTool uses the default import; this suite configures named imports. vitest.mock("fs/promises", () => ({ ...filesystemMocks, default: filesystemMocks })) +vi.mock("../../../utils/storage", () => ({ getTaskDirectoryPath: vi.fn() })) + // Mock TerminalRegistry to control terminal creation vitest.mock("../../../integrations/terminal/TerminalRegistry") @@ -87,6 +90,33 @@ describe("executeCommand", () => { vitest.restoreAllMocks() }) + it("runs the command when its optional artifact directory is unavailable", async () => { + const failure = new Error("Configured storage is unavailable") + vi.mocked(getTaskDirectoryPath).mockRejectedValueOnce(failure) + vi.mocked(Terminal.compressTerminalOutput).mockImplementationOnce((output) => output) + mockProvider.context = { globalStorageUri: { fsPath: "/test/storage" } } + mockTask.providerRef.deref.mockReturnValue(mockProvider) + mockTerminal.runCommand.mockImplementation((_command: string, callbacks: RooTerminalCallbacks) => { + queueMicrotask(() => { + void callbacks.onCompleted("Command output", mockProcess) + callbacks.onShellExecutionComplete({ exitCode: 0 }, mockProcess) + }) + return mockProcess + }) + + const [rejected, result] = await executeCommandInTerminal(mockTask, { + executionId: "unavailable-storage", + toolCallId: "call-1", + command: "echo test", + terminalShellIntegrationDisabled: false, + }) + + expect(getTaskDirectoryPath).toHaveBeenCalledExactlyOnceWith("/test/storage", mockTask.taskId) + expect(mockTerminal.runCommand).toHaveBeenCalledWith("echo test", expect.any(Object)) + expect(rejected).toBe(false) + expect(result).toContain("Command output") + }) + describe("Working Directory Behavior", () => { it("should use terminal.getCurrentWorkingDirectory() in the output message for completed commands", async () => { // Setup: Mock terminal to return a different current working directory diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 32714067fa2..8c15a59f8d6 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -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.`, + ) } } @@ -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" }) @@ -4516,20 +4523,14 @@ export class ClineProvider } private async cancelTaskInternal(task: Task): Promise { - 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(() => { + this.log(`[cancelTask] task history unavailable for ${task.taskId}; skipping rehydrate`) + return undefined + }) // Preserve parent and root task information for history item. let rootTask = task.rootTask @@ -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() diff --git a/src/core/webview/__tests__/ClineProvider.flicker-free-cancel.spec.ts b/src/core/webview/__tests__/ClineProvider.flicker-free-cancel.spec.ts index dde3a81b6c5..1324b97ac9a 100644 --- a/src/core/webview/__tests__/ClineProvider.flicker-free-cancel.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.flicker-free-cancel.spec.ts @@ -427,6 +427,36 @@ describe("ClineProvider flicker-free cancel", () => { await provider.dispose() }) + it("aborts immediately and reopens the task from history once storage recovers", async () => { + mockTask2.clineMessages = [] + const cancelCurrentRequest = vi.fn(() => {}) + mockTask1.cancelCurrentRequest = cancelCurrentRequest + seedRegistry(provider, mockTask1) + let rejectHistory!: (error: Error) => void + vi.spyOn(provider, "getTaskWithId").mockImplementationOnce( + () => + new Promise((_, reject) => { + rejectHistory = reject + }), + ) + const rehydrate = vi.spyOn(provider, "createTaskWithHistoryItem") + + const cancellation = provider.cancelTask() + expect(cancelCurrentRequest).toHaveBeenCalledOnce() + expect(mockTask1.abortTask).toHaveBeenCalledOnce() + expect(mockTask1.abandoned).toBe(true) + rejectHistory(new Error("Task storage inaccessible")) + + await expect(cancellation).resolves.toBeUndefined() + expect(rehydrate).not.toHaveBeenCalled() + expect(provider.getCurrentTask()).toBe(mockTask1) + + await provider.showTaskWithId(mockTask1.taskId) + + expect(provider.getCurrentTask()).toBe(mockTask2) + expect(provider["taskRegistry"].length).toBe(1) + }) + it("should not remove current task from stack when rehydrating same taskId", async () => { // Setup: Add a task to the registry first seedRegistry(provider, mockTask1) diff --git a/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts b/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts index e16badb3482..767278ee37f 100644 --- a/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts @@ -63,6 +63,17 @@ vi.mock("../../../utils/safeWriteJson", () => ({ safeWriteJson: vi.fn().mockResolvedValue(undefined), })) +// This suite mocks filesystem writes, so no file exists for proper-lockfile to +// lock. The store's own write lock is what the concurrency tests exercise. +vi.mock("../../../utils/fileLock", async () => { + const actual = await vi.importActual("../../../utils/fileLock") + return { + ...actual, + withFileLock: async (filePath: string, operation: (absoluteFilePath: string) => Promise): Promise => + operation(filePath), + } +}) + vi.mock("@modelcontextprotocol/sdk/types.js", () => ({ CallToolResultSchema: {}, ListResourcesResultSchema: {}, diff --git a/src/utils/__tests__/fileLock.spec.ts b/src/utils/__tests__/fileLock.spec.ts new file mode 100644 index 00000000000..1c990c371b7 --- /dev/null +++ b/src/utils/__tests__/fileLock.spec.ts @@ -0,0 +1,41 @@ +import * as path from "path" +import * as lockfile from "proper-lockfile" +import { acquireFileLock } from "../fileLock" + +vi.mock("proper-lockfile", () => ({ lock: vi.fn() })) + +it("queues same-process writes to one file without blocking other files", async () => { + const held = new Set() + vi.mocked(lockfile.lock).mockImplementation(async (filePath) => { + const file = path.resolve(filePath) + if (held.has(file)) throw new Error("Lock file is already being held") + held.add(file) + return async () => { + held.delete(file) + } + }) + + const firstPath = path.resolve("first-ui-messages.json") + const secondPath = path.resolve("second-ui-messages.json") + const releaseFirst = await acquireFileLock(firstPath) + const second = acquireFileLock(firstPath) + await Promise.resolve() + await Promise.resolve() + expect(lockfile.lock).toHaveBeenCalledOnce() + // Upstream startup recovery must defer immediately instead of parking on + // our same-process writer queue while holding the task-store mutex. + await expect(acquireFileLock(firstPath, { immediate: true })).rejects.toMatchObject({ code: "ELOCKED" }) + expect(lockfile.lock).toHaveBeenCalledOnce() + + const releaseOther = await acquireFileLock(secondPath) + expect(lockfile.lock).toHaveBeenCalledTimes(2) + await releaseOther() + await releaseFirst() + const releaseSecond = await second + expect(lockfile.lock).toHaveBeenCalledTimes(3) + await releaseSecond() + + const releaseAfter = await acquireFileLock(firstPath) + await releaseAfter() + expect(held.size).toBe(0) +}) diff --git a/src/utils/__tests__/fileLock.test.ts b/src/utils/__tests__/fileLock.test.ts index 92637fe7a0d..722efe5919f 100644 --- a/src/utils/__tests__/fileLock.test.ts +++ b/src/utils/__tests__/fileLock.test.ts @@ -8,16 +8,20 @@ describe("file lock protocol", () => { it("allows recovery to outwait staleness with bounded constant retries", async () => { vi.mocked(lockfile.lock).mockResolvedValue(async () => {}) - await acquireFileLock("history.json", { waitForStaleLock: true }) - expect(lockfile.lock).toHaveBeenCalledWith( - expect.any(String), - expect.objectContaining({ - stale: LOCK_STALE_MS, - update: 10000, - realpath: false, - retries: { retries: 35, factor: 1, minTimeout: 1000, maxTimeout: 1000 }, - }), - ) + const release = await acquireFileLock("history.json", { waitForStaleLock: true }) + try { + expect(lockfile.lock).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ + stale: LOCK_STALE_MS, + update: 10000, + realpath: false, + retries: { retries: 35, factor: 1, minTimeout: 1000, maxTimeout: 1000 }, + }), + ) + } finally { + await release() + } }) it("releases the lock when the operation fails", async () => { diff --git a/src/utils/__tests__/jsonFileRecovery.test.ts b/src/utils/__tests__/jsonFileRecovery.test.ts index ce33e739b42..7618eeb6552 100644 --- a/src/utils/__tests__/jsonFileRecovery.test.ts +++ b/src/utils/__tests__/jsonFileRecovery.test.ts @@ -154,6 +154,7 @@ describe("reader recovery", () => { it("does not create a missing task directory", async () => { await fs.rm(dir, { recursive: true }) + await expect(deleteJsonFile(target)).resolves.toBeUndefined() await expect(recoverMissingJsonFile(target)).resolves.toBe(false) await expect(fs.stat(dir)).rejects.toMatchObject({ code: "ENOENT" }) }) @@ -227,6 +228,7 @@ describe("reader recovery", () => { expect(tie.name).toBe("AmbiguousBackupRecencyError") expect(tie.message).not.toContain(path.sep) expect(tie.message).not.toContain(dir) + expect(tie.stack).not.toContain(dir) expect(tie.message).toContain("history_item.json") expect(tie.message).toContain("share mtime 1700000000000") expect(tie.targetPath).toBe(target) diff --git a/src/utils/__tests__/storage.spec.ts b/src/utils/__tests__/storage.spec.ts index f26b1c78f85..d7a67064d03 100644 --- a/src/utils/__tests__/storage.spec.ts +++ b/src/utils/__tests__/storage.spec.ts @@ -34,7 +34,7 @@ describe("getStorageBasePath - customStoragePath", () => { expect(fsPromises.access).toHaveBeenCalledWith(customPath, 7) // 7 = R_OK(4) | W_OK(2) | X_OK(1) }) - it("falls back to default and shows an error when custom path is not writable", async () => { + it("does not silently switch conversation storage roots when custom path is not writable", async () => { const customPath = "/test/storage/unwritable" vi.spyOn(vscode.workspace, "getConfiguration").mockReturnValue( @@ -58,13 +58,24 @@ describe("getStorageBasePath - customStoragePath", () => { return Promise.resolve() }) - const result = await getStorageBasePath(defaultPath) + await expect(getStorageBasePath(defaultPath, true)).rejects.toThrow( + "Configured Zoo storage path is unavailable", + ) + expect(showErrorSpy).not.toHaveBeenCalled() + }) + it("still reports the default-path fallback for non-history callers", async () => { + vi.spyOn(vscode.workspace, "getConfiguration").mockReturnValue( + makeWorkspaceConfiguration({ customStoragePath: "/test/optional-storage" }), + ) + const showError = vi.spyOn(vscode.window, "showErrorMessage").mockResolvedValue(undefined) + const { access } = await import("fs/promises") + const { getStorageBasePath } = await import("../storage") + vi.mocked(access).mockRejectedValueOnce(new Error("Storage unavailable")) - expect(result).toBe(defaultPath) - expect(showErrorSpy).toHaveBeenCalledTimes(1) - const firstArg = showErrorSpy.mock.calls[0][0] - expect(typeof firstArg).toBe("string") + await expect(getStorageBasePath(defaultPath)).resolves.toBe(defaultPath) + expect(showError).toHaveBeenCalledOnce() }) + it("returns the default path when customStoragePath is an empty string and does not touch fs", async () => { vi.spyOn(vscode.workspace, "getConfiguration").mockReturnValue( makeWorkspaceConfiguration({ customStoragePath: "" }), @@ -80,7 +91,7 @@ describe("getStorageBasePath - customStoragePath", () => { expect(fsPromises.access).not.toHaveBeenCalled() }) - it("falls back to default when mkdir fails and does not attempt access", async () => { + it("rejects when custom storage creation fails and does not attempt access", async () => { const customPath = "/test/storage/failmkdir" vi.spyOn(vscode.workspace, "getConfiguration").mockReturnValue( @@ -102,11 +113,11 @@ describe("getStorageBasePath - customStoragePath", () => { return undefined }) - const result = await getStorageBasePath(defaultPath) - - expect(result).toBe(defaultPath) - expect(fsPromises.access).not.toHaveBeenCalled() - expect(showErrorSpy).toHaveBeenCalledTimes(1) + await expect(getStorageBasePath(defaultPath, true)).rejects.toThrow( + "Configured Zoo storage path is unavailable", + ) + expect(vi.mocked(fsPromises.access)).not.toHaveBeenCalled() + expect(showErrorSpy).not.toHaveBeenCalled() }) it("passes the correct permission flags (R_OK | W_OK | X_OK) to fs.access", async () => { @@ -126,7 +137,7 @@ describe("getStorageBasePath - customStoragePath", () => { expect(fsPromises.access).toHaveBeenCalledWith(customPath, expectedFlags) }) - it("falls back when directory is readable but not writable (partial permissions)", async () => { + it("rejects when custom storage is readable but not writable", async () => { const customPath = "/test/storage/readonly" vi.spyOn(vscode.workspace, "getConfiguration").mockReturnValue( makeWorkspaceConfiguration({ customStoragePath: customPath }), @@ -149,9 +160,9 @@ describe("getStorageBasePath - customStoragePath", () => { return Promise.resolve() }) - const result = await getStorageBasePath(defaultPath) - - expect(result).toBe(defaultPath) - expect(showErrorSpy).toHaveBeenCalledTimes(1) + await expect(getStorageBasePath(defaultPath, true)).rejects.toThrow( + "Configured Zoo storage path is unavailable", + ) + expect(showErrorSpy).not.toHaveBeenCalled() }) }) diff --git a/src/utils/fileLock.ts b/src/utils/fileLock.ts index 49807ea154d..040940794fe 100644 --- a/src/utils/fileLock.ts +++ b/src/utils/fileLock.ts @@ -9,6 +9,9 @@ import * as lockfile from "proper-lockfile" */ export const LOCK_STALE_MS = 31_000 +// Proper-lockfile coordinates VS Code windows, while this queue prevents +// concurrent writes inside one extension host from exhausting its retry budget. +const localHolders = new Map>() const RECOVERY_RETRY_MS = 1000 const RECOVERY_GRACE_MS = 4000 @@ -28,9 +31,24 @@ export interface FileLockOptions { */ export async function acquireFileLock(filePath: string, options?: FileLockOptions): Promise<() => Promise> { const absoluteFilePath = path.resolve(filePath) + if (options?.immediate && localHolders.has(absoluteFilePath)) { + throw Object.assign(new Error(`Lock file is already being held: ${absoluteFilePath}`), { code: "ELOCKED" }) + } + const previous = localHolders.get(absoluteFilePath) ?? Promise.resolve() + let leaveQueue: () => void = () => {} + const held = new Promise((resolve) => { + leaveQueue = resolve + }) + const tail = previous.then(() => held) + localHolders.set(absoluteFilePath, tail) + await previous + const clearLocalHolder = () => { + leaveQueue() + if (localHolders.get(absoluteFilePath) === tail) localHolders.delete(absoluteFilePath) + } if (options?.waitForStaleLock) tracePersistenceEvent("json-lock-wait", { filePath: absoluteFilePath }) try { - return await lockfile.lock(absoluteFilePath, { + const release = await lockfile.lock(absoluteFilePath, { stale: LOCK_STALE_MS, update: 10000, // Update mtime every 10 seconds to prevent staleness if operation is long realpath: false, // the file may not exist yet, which is acceptable @@ -45,7 +63,7 @@ export async function acquireFileLock(filePath: string, options?: FileLockOption } : { // Configuration for retrying lock acquisition - retries: 5, // Number of retries after the initial attempt + retries: 30, // Allow large peer message writes to finish factor: 2, // Exponential backoff factor (e.g., 100ms, 200ms, 400ms, ...) minTimeout: 100, // Minimum time to wait before the first retry (in ms) maxTimeout: 1000, // Maximum time to wait for any single retry (in ms) @@ -55,7 +73,15 @@ export async function acquireFileLock(filePath: string, options?: FileLockOption throw err }, }) + return async () => { + try { + await release() + } finally { + clearLocalHolder() + } + } } catch (lockError) { + clearLocalHolder() console.error(`Failed to acquire lock for ${absoluteFilePath}:`, lockError) throw lockError } diff --git a/src/utils/jsonFileRecovery.ts b/src/utils/jsonFileRecovery.ts index 1ad95dbdd8a..5bec6776a07 100644 --- a/src/utils/jsonFileRecovery.ts +++ b/src/utils/jsonFileRecovery.ts @@ -77,6 +77,14 @@ export async function recoverMissingJsonFile( * of a stale backup after a successful deletion. Missing files are harmless. */ export async function deleteJsonFile(filePath: string): Promise { + // An absent task directory cannot contain a canonical file or backups, and + // proper-lockfile cannot create its sibling lock directory there. + try { + await fs.access(path.dirname(path.resolve(filePath))) + } catch (error: unknown) { + if (getErrorCode(error) === "ENOENT") return + throw error + } await withFileLock(filePath, async (absoluteFilePath) => { let entries: string[] try { diff --git a/src/utils/storage.ts b/src/utils/storage.ts index 0cab638d819..aebe8bc6544 100644 --- a/src/utils/storage.ts +++ b/src/utils/storage.ts @@ -11,7 +11,7 @@ import { t } from "../i18n" * If a custom path is configured, uses that path * Otherwise uses the default VSCode extension global storage path */ -export async function getStorageBasePath(defaultPath: string): Promise { +export async function getStorageBasePath(defaultPath: string, requireConfiguredPath = false): Promise { // Get user-configured custom storage path let customStoragePath = "" @@ -19,7 +19,8 @@ export async function getStorageBasePath(defaultPath: string): Promise { // This is the line causing the error in tests const config = vscode.workspace.getConfiguration(Package.name) customStoragePath = config.get("customStoragePath", "") - } catch { + } catch (error) { + if (requireConfiguredPath) throw new Error("Could not read Zoo's storage-path setting", { cause: error }) console.warn("Could not access VSCode configuration - using default path") return defaultPath } @@ -38,10 +39,16 @@ export async function getStorageBasePath(defaultPath: string): Promise { return customStoragePath } catch (error) { - // If path is unusable, report error and fall back to default path + // Never switch storage roots behind the user's back: that makes all + // conversations appear missing and may write new tasks into a second root. console.error(`Custom storage path is unusable: ${error instanceof Error ? error.message : String(error)}`) + if (requireConfiguredPath) { + throw new Error(`Configured Zoo storage path is unavailable: ${customStoragePath}`, { cause: error }) + } if (vscode.window) { - vscode.window.showErrorMessage(t("common:errors.custom_storage_path_unusable", { path: customStoragePath })) + void vscode.window.showErrorMessage( + t("common:errors.custom_storage_path_unusable", { path: customStoragePath }), + ) } return defaultPath } @@ -50,10 +57,15 @@ export async function getStorageBasePath(defaultPath: string): Promise { /** * Gets the storage directory path for a task */ -export async function getTaskDirectoryPath(globalStoragePath: string, taskId: string): Promise { - const basePath = await getStorageBasePath(globalStoragePath) +export async function getTaskDirectoryPath( + globalStoragePath: string, + taskId: string, + { requireWritable = false }: { requireWritable?: boolean } = {}, +): Promise { + const basePath = await getStorageBasePath(globalStoragePath, true) const taskDir = path.join(basePath, "tasks", taskId) await fs.mkdir(taskDir, { recursive: true }) + if (requireWritable) await fs.access(taskDir, fsConstants.R_OK | fsConstants.W_OK | fsConstants.X_OK) return taskDir }