diff --git a/src/core/config/__tests__/importExport.spec.ts b/src/core/config/__tests__/importExport.spec.ts index 6c66655325..b595bb1b12 100644 --- a/src/core/config/__tests__/importExport.spec.ts +++ b/src/core/config/__tests__/importExport.spec.ts @@ -51,25 +51,21 @@ vi.mock("vscode", () => ({ }, })) +// Shared instances so the default import (`import fs from "fs/promises"`) and the +// named imports used by `utils/export` resolve to the same mocks. +const fsMocks = vi.hoisted(() => { + const readFile = vi.fn() + const mkdir = vi.fn() + const writeFile = vi.fn() + const access = vi.fn() + const stat = vi.fn() + const constants = { F_OK: 0, R_OK: 4, W_OK: 2, X_OK: 1 } + return { readFile, mkdir, writeFile, access, stat, constants } +}) + vi.mock("fs/promises", () => ({ - default: { - readFile: vi.fn(), - mkdir: vi.fn(), - writeFile: vi.fn(), - access: vi.fn(), - constants: { - F_OK: 0, - R_OK: 4, - }, - }, - readFile: vi.fn(), - mkdir: vi.fn(), - writeFile: vi.fn(), - access: vi.fn(), - constants: { - F_OK: 0, - R_OK: 4, - }, + ...fsMocks, + default: fsMocks, })) vi.mock("os", () => ({ @@ -79,6 +75,13 @@ vi.mock("os", () => ({ homedir: vi.fn(() => "/mock/home"), })) +// Echo the key with params serialized so tests can assert the message arguments +// without loading a real i18n catalogue (same approach as +// webviewMessageHandler.openFile.spec.ts). +vi.mock("../../../i18n", () => ({ + t: vi.fn((key: string, params?: Record) => (params ? `${key}:${JSON.stringify(params)}` : key)), +})) + vi.mock("../../../utils/safeWriteJson") // Mock buildApiHandler to avoid issues with provider instantiation in tests @@ -133,6 +136,10 @@ describe("importExport", () => { listConfig: vi.fn(), } as unknown as ReturnType> + // A remembered export location is usable unless a test says otherwise. + fsMocks.stat.mockResolvedValue({ isDirectory: () => true }) + fsMocks.access.mockResolvedValue(undefined) + mockContextProxy = { setValues: vi.fn(), setValue: vi.fn(), @@ -274,9 +281,155 @@ describe("importExport", () => { expect(mockContextProxy.setValues).not.toHaveBeenCalled() }) - it("should import settings successfully from a valid file", async () => { + it("should default the import dialog to a remembered export directory that is still writable", async () => { + const remembered = path.join("/usb", "zoo-code-settings.json") + mockContextProxy.getValue.mockImplementation((key: string) => + key === "lastSettingsExportPath" ? remembered : undefined, + ) + ;(vscode.window.showOpenDialog as Mock).mockResolvedValue(undefined) + + await importSettings({ + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + }) + + // Assert the dialog argument, not just that a URI was built: the remembered + // location is only fixed if the dialog is actually opened there. + expect(vscode.window.showOpenDialog).not.toHaveBeenCalledWith( + expect.objectContaining({ + defaultUri: expect.objectContaining({ + fsPath: path.join("/mock/home", "Downloads", "zoo-code-settings.json"), + }), + }), + ) + expect(vscode.window.showOpenDialog).toHaveBeenCalledWith( + expect.objectContaining({ + defaultUri: expect.objectContaining({ fsPath: path.join("/usb", "zoo-code-settings.json") }), + }), + ) + }) + + it("should default the import dialog to a remembered directory that is readable but read-only", async () => { + const remembered = path.join("/usb", "zoo-code-settings.json") + mockContextProxy.getValue.mockImplementation((key: string) => + key === "lastSettingsExportPath" ? remembered : undefined, + ) + // A read-only volume: write access fails, read access succeeds. An open + // dialog only reads, so this folder must stay the default. + fsMocks.access.mockImplementation((_dir: string, mode: number) => + (mode & fsMocks.constants.W_OK) === fsMocks.constants.W_OK + ? Promise.reject(Object.assign(new Error("EACCES"), { code: "EACCES" })) + : Promise.resolve(), + ) + ;(vscode.window.showOpenDialog as Mock).mockResolvedValue(undefined) + + await importSettings({ + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + }) + + expect(fs.access).toHaveBeenCalledWith( + path.dirname(remembered), + fsMocks.constants.R_OK | fsMocks.constants.X_OK, + ) + expect(vscode.window.showOpenDialog).toHaveBeenCalledWith( + expect.objectContaining({ + defaultUri: expect.objectContaining({ fsPath: path.join("/usb", "zoo-code-settings.json") }), + }), + ) + }) + + it("should not default the import dialog to a remembered directory that no longer exists", async () => { + const staleRemembered = path.join("Z:\\gone", "zoo-code-settings.json") + mockContextProxy.getValue.mockImplementation((key: string) => + key === "lastSettingsExportPath" ? staleRemembered : undefined, + ) + fsMocks.stat.mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" })) + ;(vscode.window.showOpenDialog as Mock).mockResolvedValue(undefined) + + await importSettings({ + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + }) + + expect(vscode.window.showOpenDialog).not.toHaveBeenCalledWith( + expect.objectContaining({ + defaultUri: expect.objectContaining({ + fsPath: path.join(path.dirname(staleRemembered), "zoo-code-settings.json"), + }), + }), + ) + expect(vscode.window.showOpenDialog).toHaveBeenCalledWith( + expect.objectContaining({ + defaultUri: expect.objectContaining({ + fsPath: path.join("/mock/home", "Downloads", "zoo-code-settings.json"), + }), + }), + ) + }) + + it("should not import the save locations of the machine that produced the file", async () => { ;(vscode.window.showOpenDialog as Mock).mockResolvedValue([{ fsPath: "/mock/path/settings.json" }]) + // A settings file carries the dialog memory of the machine that exported it. + // Importing those absolute paths would make this machine's dialogs probe, + // and default to, folders nobody picked here. + ;(fs.readFile as Mock).mockResolvedValue( + JSON.stringify({ + providerProfiles: { + currentApiConfigName: "test", + apiConfigs: { test: { apiProvider: providerIdentifiers.openai, id: "test-id" } }, + }, + globalSettings: { + mode: "code", + lastSettingsExportPath: path.join("Z:\\other-machine", "Downloads", "zoo-code-settings.json"), + lastTaskExportPath: path.join("Z:\\other-machine", "Downloads", "task.md"), + lastModeExportPath: path.join("Z:\\other-machine", "modes"), + lastImageSavePath: path.join("Z:\\other-machine", "Pictures"), + }, + }), + ) + mockProviderSettingsManager.export.mockResolvedValue({ + currentApiConfigName: "default", + apiConfigs: { default: { apiProvider: providerIdentifiers.anthropic, id: "default-id" } }, + }) + mockProviderSettingsManager.listConfig.mockResolvedValue([ + { name: "test", id: "test-id", apiProvider: providerIdentifiers.openai }, + ]) + mockContextProxy.export.mockResolvedValue({ mode: "code" }) + + const result = await importSettings({ + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + customModesManager: mockCustomModesManager, + }) + + expect(result.success).toBe(true) + expect(result.globalSettings).toEqual(expect.objectContaining({ mode: "code" })) + expect(result.globalSettings).not.toHaveProperty("lastSettingsExportPath") + expect(result.globalSettings).not.toHaveProperty("lastTaskExportPath") + expect(result.globalSettings).not.toHaveProperty("lastModeExportPath") + expect(result.globalSettings).not.toHaveProperty("lastImageSavePath") + // What matters is what reaches storage: setValues installs the imported object, + // so the foreign dialog memory has to be gone from the value the extension will + // actually use, not only from the summary returned to the caller. + expect(mockContextProxy.setValues).toHaveBeenCalledTimes(1) + const installedGlobalSettings = mockContextProxy.setValues.mock.calls[0][0] + expect(installedGlobalSettings).toEqual(expect.objectContaining({ mode: "code" })) + expect(installedGlobalSettings).not.toHaveProperty("lastSettingsExportPath") + expect(installedGlobalSettings).not.toHaveProperty("lastTaskExportPath") + expect(installedGlobalSettings).not.toHaveProperty("lastModeExportPath") + expect(installedGlobalSettings).not.toHaveProperty("lastImageSavePath") + // Dropped silently: every export contains these keys, so warning on each + // import would report nothing the user can act on. The whole warning list is + // the assertion here — this import has nothing to report. + expect(result.warnings).toBeUndefined() + }) + + it("should import settings successfully from a valid file", async () => { const mockFileContent = JSON.stringify({ providerProfiles: { currentApiConfigName: "test", @@ -1679,9 +1832,15 @@ describe("importExport", () => { expect(mockContextProxy.export).toHaveBeenCalled() expect(fs.mkdir).toHaveBeenCalledWith("/mock/path", { recursive: true }) expect(safeWriteJson).toHaveBeenCalled() // safeWriteJson is called, but it will throw - // The error is caught and the function exits silently. - // Optionally, ensure no error message was shown if that's part of "silent" - // expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + // The failure must reach the user: a silent export is how a settings file + // ends up in a folder the user never selected. + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + expect.stringContaining("errors.settings_export_failed"), + ) + // The reason matters too: the message must say why the location failed. + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(expect.stringContaining("Safe write error")) + // A location that never received the file must not steer the next dialog. + expect(mockContextProxy.setValue).not.toHaveBeenCalledWith("lastSettingsExportPath", expect.anything()) }) it("should handle errors during directory creation", async () => { @@ -1708,6 +1867,281 @@ describe("importExport", () => { expect(mockContextProxy.export).toHaveBeenCalled() expect(fs.mkdir).toHaveBeenCalled() expect(safeWriteJson).not.toHaveBeenCalled() // Should not be called since mkdir failed. + // A failed export is reported, and it must not steer the next dialog. + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + expect.stringContaining("errors.settings_export_failed"), + ) + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + expect.stringContaining("Directory creation error"), + ) + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled() + expect(mockContextProxy.setValue).not.toHaveBeenCalledWith("lastSettingsExportPath", expect.anything()) + }) + + it("should report a failed provider profile export instead of exporting half a settings file", async () => { + ;(vscode.window.showSaveDialog as Mock).mockResolvedValue({ + fsPath: "/mock/path/zoo-code-settings.json", + }) + mockProviderSettingsManager.export.mockRejectedValue(new Error("Provider export error")) + mockContextProxy.export.mockResolvedValue({ mode: "code" }) + + await exportSettings({ + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + }) + + expect(fs.mkdir).not.toHaveBeenCalled() + expect(safeWriteJson).not.toHaveBeenCalled() + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + expect.stringContaining("errors.settings_export_failed"), + ) + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + expect.stringContaining("Provider export error"), + ) + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled() + expect(mockContextProxy.setValue).not.toHaveBeenCalledWith("lastSettingsExportPath", expect.anything()) + }) + + it("should report a failed global settings export instead of exporting half a settings file", async () => { + ;(vscode.window.showSaveDialog as Mock).mockResolvedValue({ + fsPath: "/mock/path/zoo-code-settings.json", + }) + mockProviderSettingsManager.export.mockResolvedValue({ + currentApiConfigName: "test", + apiConfigs: { test: { apiProvider: providerIdentifiers.openai, id: "test-id" } }, + migrations: { rateLimitSecondsMigrated: false }, + }) + mockContextProxy.export.mockRejectedValue(new Error("Global settings export error")) + + await exportSettings({ + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + }) + + expect(fs.mkdir).not.toHaveBeenCalled() + expect(safeWriteJson).not.toHaveBeenCalled() + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + expect.stringContaining("errors.settings_export_failed"), + ) + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + expect.stringContaining("Global settings export error"), + ) + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled() + expect(mockContextProxy.setValue).not.toHaveBeenCalledWith("lastSettingsExportPath", expect.anything()) + }) + + it("writes nothing when no provider profile is configured", async () => { + ;(vscode.window.showSaveDialog as Mock).mockResolvedValue({ + fsPath: "/mock/path/zoo-code-settings.json", + }) + // `ProviderSettingsManager.export()` is typed as returning parsed profiles or + // throwing, so the profile-less branch in `exportSettings` is defensive rather + // than reachable. The mock is loosened the way this file already loosens the + // dialog mocks so the defensive branch is the one under test. + ;(mockProviderSettingsManager.export as Mock).mockResolvedValue(undefined) + mockContextProxy.export.mockResolvedValue({ mode: "code" }) + + await exportSettings({ + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + }) + + // Deliberate behaviour, pinned rather than changed: `importSettings` cannot + // consume a file with no provider profiles, so a profile-less export writes + // nothing at all. The guard sits after both collect calls, so it must not + // reach the disk, the toasts, or the remembered location. + expect(mockContextProxy.export).toHaveBeenCalled() + expect(fs.mkdir).not.toHaveBeenCalled() + expect(safeWriteJson).not.toHaveBeenCalled() + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled() + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + expect(mockContextProxy.setValue).not.toHaveBeenCalledWith("lastSettingsExportPath", expect.anything()) + }) + + it("should persist and report the location that received the exported file", async () => { + ;(fs.mkdir as Mock).mockResolvedValue(undefined) + ;(vscode.window.showSaveDialog as Mock).mockResolvedValue({ + fsPath: "/usb/zoo-code-settings.json", + }) + mockProviderSettingsManager.export.mockResolvedValue({ + currentApiConfigName: "test", + apiConfigs: { test: { apiProvider: providerIdentifiers.openai, id: "test-id" } }, + migrations: { rateLimitSecondsMigrated: false }, + }) + mockContextProxy.export.mockResolvedValue({ mode: "code" }) + + await exportSettings({ + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + }) + + expect(safeWriteJson).toHaveBeenCalledWith("/usb/zoo-code-settings.json", expect.anything()) + expect(mockContextProxy.setValue).toHaveBeenCalledWith( + "lastSettingsExportPath", + "/usb/zoo-code-settings.json", + ) + // The location is remembered before the toast is shown: + // showInformationMessage only resolves once the notification is dismissed, + // so a later export has to see this folder straight away. + expect(mockContextProxy.setValue.mock.invocationCallOrder[0]).toBeLessThan( + (vscode.window.showInformationMessage as Mock).mock.invocationCallOrder[0], + ) + // The toast must name the file that actually received the export, and name it + // under the parameter the catalogue interpolates: the mocked t echoes the params + // as JSON, so matching the whole rendered message catches a renamed `path` param + // that a substring match on the path would let through. + expect(vscode.window.showInformationMessage).toHaveBeenCalledWith( + `common:info.settings_exported:{"path":"/usb/zoo-code-settings.json"}`, + ) + }) + + it("should report a partial export when the location cannot be remembered", async () => { + ;(fs.mkdir as Mock).mockResolvedValue(undefined) + ;(vscode.window.showSaveDialog as Mock).mockResolvedValue({ + fsPath: "/usb/zoo-code-settings.json", + }) + mockProviderSettingsManager.export.mockResolvedValue({ + currentApiConfigName: "test", + apiConfigs: { test: { apiProvider: providerIdentifiers.openai, id: "test-id" } }, + migrations: { rateLimitSecondsMigrated: false }, + }) + mockContextProxy.export.mockResolvedValue({ mode: "code" }) + // The file is on disk; only the remembered location fails. That must not + // swallow the report the user just earned. + const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + mockContextProxy.setValue.mockRejectedValueOnce(new Error("storage unavailable")) + + await exportSettings({ + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + }) + + expect(safeWriteJson).toHaveBeenCalledWith("/usb/zoo-code-settings.json", expect.anything()) + // The file is on disk, but the next export will not know this folder. Say both + // halves instead of posting the plain success toast. + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith( + expect.stringContaining("warnings.settings_export_location_not_remembered"), + ) + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith( + expect.stringContaining("/usb/zoo-code-settings.json"), + ) + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith( + expect.stringContaining("storage unavailable"), + ) + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled() + // The stack still belongs in the extension host logs. + expect(consoleErrorSpy).toHaveBeenCalledWith("Failed to remember the export location:", expect.any(Error)) + consoleErrorSpy.mockRestore() + }) + + it("should not default the dialog to a remembered directory that no longer exists", async () => { + const staleRemembered = path.join("Z:\\gone", "zoo-code-settings.json") + mockContextProxy.getValue.mockImplementation((key: string) => + key === "lastSettingsExportPath" ? staleRemembered : undefined, + ) + fsMocks.stat.mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" })) + ;(vscode.window.showSaveDialog as Mock).mockResolvedValue(undefined) + + await exportSettings({ + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + }) + + // Falling through to the documented fallback beats handing a dead path to + // the platform dialog, which silently lands the file in a default folder. + expect(vscode.window.showSaveDialog).not.toHaveBeenCalledWith( + expect.objectContaining({ + defaultUri: expect.objectContaining({ + fsPath: path.join(path.dirname(staleRemembered), "zoo-code-settings.json"), + }), + }), + ) + expect(vscode.window.showSaveDialog).toHaveBeenCalledWith( + expect.objectContaining({ + defaultUri: expect.objectContaining({ + fsPath: path.join("/mock/home", "Downloads", "zoo-code-settings.json"), + }), + }), + ) + }) + + it("should not default the dialog to a remembered path that is now a file", async () => { + const remembered = path.join("/usb", "zoo-code-settings.json") + mockContextProxy.getValue.mockImplementation((key: string) => + key === "lastSettingsExportPath" ? remembered : undefined, + ) + fsMocks.stat.mockResolvedValueOnce({ isDirectory: () => false }) + ;(vscode.window.showSaveDialog as Mock).mockResolvedValue(undefined) + + await exportSettings({ + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + }) + + expect(vscode.window.showSaveDialog).not.toHaveBeenCalledWith( + expect.objectContaining({ + defaultUri: expect.objectContaining({ fsPath: path.join("/usb", "zoo-code-settings.json") }), + }), + ) + expect(vscode.window.showSaveDialog).toHaveBeenCalledWith( + expect.objectContaining({ + defaultUri: expect.objectContaining({ + fsPath: path.join("/mock/home", "Downloads", "zoo-code-settings.json"), + }), + }), + ) + }) + + it("should not default the dialog to a remembered directory that is not writable", async () => { + const remembered = path.join("/usb", "zoo-code-settings.json") + mockContextProxy.getValue.mockImplementation((key: string) => + key === "lastSettingsExportPath" ? remembered : undefined, + ) + fsMocks.access.mockRejectedValueOnce(Object.assign(new Error("EACCES"), { code: "EACCES" })) + ;(vscode.window.showSaveDialog as Mock).mockResolvedValue(undefined) + + await exportSettings({ + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + }) + + // W_OK (plus traversal) is the property that matters for an export target. + expect(fs.access).toHaveBeenCalledWith( + path.dirname(remembered), + fsMocks.constants.W_OK | fsMocks.constants.X_OK, + ) + expect(vscode.window.showSaveDialog).not.toHaveBeenCalledWith( + expect.objectContaining({ + defaultUri: expect.objectContaining({ fsPath: path.join("/usb", "zoo-code-settings.json") }), + }), + ) + expect(vscode.window.showSaveDialog).toHaveBeenCalledWith( + expect.objectContaining({ + defaultUri: expect.objectContaining({ + fsPath: path.join("/mock/home", "Downloads", "zoo-code-settings.json"), + }), + }), + ) + }) + + it("should default the dialog to a remembered directory that is still writable", async () => { + const remembered = path.join("/usb", "zoo-code-settings.json") + mockContextProxy.getValue.mockImplementation((key: string) => + key === "lastSettingsExportPath" ? remembered : undefined, + ) + ;(vscode.window.showSaveDialog as Mock).mockResolvedValue(undefined) + + await exportSettings({ + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + }) + + expect(vscode.window.showSaveDialog).toHaveBeenCalledWith( + expect.objectContaining({ + defaultUri: expect.objectContaining({ fsPath: path.join("/usb", "zoo-code-settings.json") }), + }), + ) }) it("should use the correct default save location", async () => { diff --git a/src/core/config/importExport.ts b/src/core/config/importExport.ts index 9882039ad3..8fa2f650ac 100644 --- a/src/core/config/importExport.ts +++ b/src/core/config/importExport.ts @@ -78,6 +78,23 @@ function formatZodIssues(error: ZodError): string { return error.issues.map((issue) => `[${issue.path.join(".") || "value"}]: ${issue.message}`).join(", ") } +/** + * Save and open dialogs remember an absolute directory per machine, so these + * settings are host-local state rather than configuration. An exported settings + * file must not be able to install another machine's folder layout into this + * one: the dialogs would then probe, and default to, a path nobody picked on + * this machine. They are dropped on import and re-established by the next dialog + * choice. + */ +const hostLocalPathKeyNames = [ + "lastSettingsExportPath", + "lastTaskExportPath", + "lastModeExportPath", + "lastImageSavePath", +] as const satisfies readonly (keyof GlobalSettings)[] + +const hostLocalPathKeys: ReadonlySet = new Set(hostLocalPathKeyNames) + function sanitizeGlobalSettings(rawGlobalSettings: unknown): { sanitizedGlobalSettings: GlobalSettings warnings: string[] @@ -105,6 +122,12 @@ function sanitizeGlobalSettings(rawGlobalSettings: unknown): { continue } + if (hostLocalPathKeys.has(key)) { + // Deliberately silent: every settings export contains these keys, so warning + // on each import would report nothing the user can act on. + continue + } + let valueToValidate = rawValue if (key === "imageGenerationProvider" && rawValue === retiredProviderIdentifiers.roo) { @@ -270,10 +293,13 @@ export async function importSettingsFromPath( * @returns Promise resolving to import result */ export const importSettings = async ({ providerSettingsManager, contextProxy, customModesManager }: ImportOptions) => { - // Use the last export path as a sensible default, falling back to Downloads - const defaultUri = resolveDefaultSaveUri(contextProxy, "lastSettingsExportPath", "zoo-code-settings.json", { + // Use the last export path as a sensible default, falling back to Downloads. + // An open dialog only reads from that folder, so requiring write access here + // would drop a read-only folder that does hold the settings file. + const defaultUri = await resolveDefaultSaveUri(contextProxy, "lastSettingsExportPath", "zoo-code-settings.json", { useWorkspace: false, fallbackDir: path.join(os.homedir(), "Downloads"), + accessMode: fs.constants.R_OK, }) const uris = await vscode.window.showOpenDialog({ @@ -327,8 +353,6 @@ export const exportSettings = async ({ providerSettingsManager, contextProxy }: return } - await saveLastExportPath(contextProxy, "lastSettingsExportPath", uri) - try { const providerProfiles = await providerSettingsManager.export() const globalSettings = await contextProxy.export() @@ -348,9 +372,35 @@ export const exportSettings = async ({ providerSettingsManager, contextProxy }: await fs.mkdir(dirname, { recursive: true }) await safeWriteJson(uri.fsPath, { providerProfiles, globalSettings }) } catch (e) { + const message = e instanceof Error ? e.message : String(e) console.error("Failed to export settings:", e) - // Don't re-throw - the UI will handle showing error messages + // A silent export failure is how a user ends up with a settings file in a + // folder they never picked: nothing on disk reported that the chosen + // location was unwritable. + await vscode.window.showErrorMessage(t("common:errors.settings_export_failed", { error: message })) + return + } + + // Remember only a location that actually received the file, so a failed export + // cannot steer the next dialog either. It runs before the confirmation because + // `showInformationMessage` only resolves once the notification is dismissed, and + // it is guarded because failing to remember a location is not a failed export: + // the export is still reported, just as the partial result it is, and the + // rejection must not escape into the unawaited message handler. + try { + await saveLastExportPath(contextProxy, "lastSettingsExportPath", uri) + } catch (e) { + const reason = e instanceof Error ? e.message : String(e) + console.error("Failed to remember the export location:", e) + // The file was written: report that part plainly, and report the part that + // did not happen instead of pretending the export was complete. + await vscode.window.showWarningMessage( + t("common:warnings.settings_export_location_not_remembered", { path: uri.fsPath, error: reason }), + ) + return } + + await vscode.window.showInformationMessage(t("common:info.settings_exported", { path: uri.fsPath })) } /** diff --git a/src/i18n/__tests__/locale-bundles.spec.ts b/src/i18n/__tests__/locale-bundles.spec.ts index cb455e2d65..0adfdaa7f3 100644 --- a/src/i18n/__tests__/locale-bundles.spec.ts +++ b/src/i18n/__tests__/locale-bundles.spec.ts @@ -26,7 +26,10 @@ import vi from "../locales/vi/common.json" import zhCn from "../locales/zh-CN/common.json" import zhTw from "../locales/zh-TW/common.json" -const bundles: Record }> = { +const bundles: Record< + string, + { errors: Record; info: Record; warnings: Record } +> = { ca, de, en, @@ -58,3 +61,20 @@ describe("common locale bundles", () => { } }) }) + +// Keys the settings-export unit adds to the common namespace: exportSettings +// now names the location that received the file, and names the failure +// instead of swallowing it. +describe("settings export locale bundles", () => { + it.each(Object.keys(bundles))("%s defines every settings export message", (locale) => { + expect(bundles[locale].info.settings_exported).toEqual(expect.any(String)) + expect(bundles[locale].info.settings_exported).toContain("{{path}}") + expect(bundles[locale].errors.settings_export_failed).toEqual(expect.any(String)) + expect(bundles[locale].errors.settings_export_failed).toContain("{{error}}") + // A written file whose location could not be remembered is a partial export: + // every locale has to be able to say both halves. + expect(bundles[locale].warnings.settings_export_location_not_remembered).toEqual(expect.any(String)) + expect(bundles[locale].warnings.settings_export_location_not_remembered).toContain("{{path}}") + expect(bundles[locale].warnings.settings_export_location_not_remembered).toContain("{{error}}") + }) +}) diff --git a/src/i18n/locales/ca/common.json b/src/i18n/locales/ca/common.json index d414d697f2..ee47926780 100644 --- a/src/i18n/locales/ca/common.json +++ b/src/i18n/locales/ca/common.json @@ -51,6 +51,7 @@ "cannot_access_path": "No es pot accedir a la ruta {{path}}: {{error}}", "path_outside_workspace": "La ruta és fora de l'espai de treball", "settings_import_failed": "Ha fallat la importació de la configuració: {{error}}.", + "settings_export_failed": "No s'ha pogut exportar la configuració: {{error}}", "mistake_limit_guidance": "Això pot indicar un error en el procés de pensament del model o la incapacitat d'utilitzar una eina correctament, que es pot mitigar amb orientació de l'usuari (p. ex. \"Prova de dividir la tasca en passos més petits\").", "violated_organization_allowlist": "Ha fallat l'execució de la tasca: el perfil actual no és compatible amb la configuració de la teva organització", "condense_failed": "Ha fallat la condensació del context", @@ -127,6 +128,7 @@ "warnings": { "no_terminal_content": "No s'ha seleccionat contingut de terminal", "auto_import_failed": "Ha fallat la importació automàtica de la configuració de ZooCode: {{error}}", + "settings_export_location_not_remembered": "Configuració exportada a {{path}}, però no s'ha pogut recordar la ubicació per a la propera exportació: {{error}}", "rooHistoryImport": { "nothingFound": "No s'ha trobat historial de tasques de Roo Code per importar de {{domain}}.", "alreadyImported_one": "Tot l'historial de tasca de Roo Code ({{count}}) ja s'ha importat a Zoo Code.", @@ -138,6 +140,7 @@ "custom_storage_path_set": "Ruta d'emmagatzematge personalitzada establerta: {{path}}", "default_storage_path": "S'ha reprès l'ús de la ruta d'emmagatzematge predeterminada", "settings_imported": "Configuració importada correctament.", + "settings_exported": "Configuració exportada a {{path}}.", "auto_import_success": "Configuració de ZooCode importada automàticament des de {{filename}}", "image_copied_to_clipboard": "URI de dades de la imatge copiada al portapapers", "image_saved": "Imatge desada a {{path}}", diff --git a/src/i18n/locales/de/common.json b/src/i18n/locales/de/common.json index 8361221019..5d1878c968 100644 --- a/src/i18n/locales/de/common.json +++ b/src/i18n/locales/de/common.json @@ -47,6 +47,7 @@ "cannot_access_path": "Zugriff auf Pfad {{path}} nicht möglich: {{error}}", "path_outside_workspace": "Pfad liegt außerhalb des Arbeitsbereichs", "settings_import_failed": "Fehler beim Importieren der Einstellungen: {{error}}.", + "settings_export_failed": "Fehler beim Exportieren der Einstellungen: {{error}}", "mistake_limit_guidance": "Dies kann auf einen Fehler im Denkprozess des Modells oder die Unfähigkeit hinweisen, ein Tool richtig zu verwenden, was durch Benutzerführung behoben werden kann (z.B. \"Versuche, die Aufgabe in kleinere Schritte zu unterteilen\").", "violated_organization_allowlist": "Aufgabe konnte nicht ausgeführt werden: Das aktuelle Profil ist nicht kompatibel mit den Einstellungen deiner Organisation", "condense_failed": "Fehler beim Verdichten des Kontexts", @@ -123,6 +124,7 @@ "warnings": { "no_terminal_content": "Kein Terminal-Inhalt ausgewählt", "auto_import_failed": "Fehler beim automatischen Import der ZooCode-Einstellungen: {{error}}", + "settings_export_location_not_remembered": "Einstellungen wurden nach {{path}} exportiert, aber der Speicherort konnte für den nächsten Export nicht gemerkt werden: {{error}}", "rooHistoryImport": { "nothingFound": "Es wurde kein Roo Code-Aufgabenverlauf zum Importieren von {{domain}} gefunden.", "alreadyImported_one": "Der {{count}} Roo Code-Aufgabenverlauf wurde bereits in Zoo Code importiert.", @@ -134,6 +136,7 @@ "custom_storage_path_set": "Benutzerdefinierter Speicherpfad festgelegt: {{path}}", "default_storage_path": "Auf Standardspeicherpfad zurückgesetzt", "settings_imported": "Einstellungen erfolgreich importiert.", + "settings_exported": "Einstellungen wurden nach {{path}} exportiert.", "auto_import_success": "ZooCode-Einstellungen automatisch importiert aus {{filename}}", "image_copied_to_clipboard": "Bild-Daten-URI in die Zwischenablage kopiert", "image_saved": "Bild gespeichert unter {{path}}", diff --git a/src/i18n/locales/en/common.json b/src/i18n/locales/en/common.json index 21cb77dd5f..edc1f27d4a 100644 --- a/src/i18n/locales/en/common.json +++ b/src/i18n/locales/en/common.json @@ -47,6 +47,7 @@ "cannot_access_path": "Cannot access path {{path}}: {{error}}", "path_outside_workspace": "Path is outside the workspace", "settings_import_failed": "Settings import failed: {{error}}.", + "settings_export_failed": "Failed to export settings: {{error}}", "mistake_limit_guidance": "This may indicate a failure in the model's thought process or inability to use a tool properly, which can be mitigated with some user guidance (e.g. \"Try breaking down the task into smaller steps\").", "violated_organization_allowlist": "Failed to run task: the current profile isn't compatible with your organization settings", "condense_failed": "Failed to condense context", @@ -123,6 +124,7 @@ "warnings": { "no_terminal_content": "No terminal content selected", "auto_import_failed": "Failed to auto-import ZooCode settings: {{error}}", + "settings_export_location_not_remembered": "Settings exported to {{path}}, but the location could not be remembered for the next export: {{error}}", "rooHistoryImport": { "nothingFound": "No Roo Code task history was found to import from {{domain}}.", "alreadyImported_one": "All {{count}} Roo Code task history has already been imported into Zoo Code.", @@ -134,6 +136,7 @@ "custom_storage_path_set": "Custom storage path set: {{path}}", "default_storage_path": "Reverted to using default storage path", "settings_imported": "Settings imported successfully.", + "settings_exported": "Settings exported to {{path}}.", "auto_import_success": "ZooCode settings automatically imported from {{filename}}", "image_copied_to_clipboard": "Image data URI copied to clipboard", "image_saved": "Image saved to {{path}}", diff --git a/src/i18n/locales/es/common.json b/src/i18n/locales/es/common.json index 5b959f6e2f..dc61ecf314 100644 --- a/src/i18n/locales/es/common.json +++ b/src/i18n/locales/es/common.json @@ -47,6 +47,7 @@ "cannot_access_path": "No se puede acceder a la ruta {{path}}: {{error}}", "path_outside_workspace": "La ruta está fuera del espacio de trabajo", "settings_import_failed": "Error al importar la configuración: {{error}}.", + "settings_export_failed": "No se pudo exportar la configuración: {{error}}", "mistake_limit_guidance": "Esto puede indicar un fallo en el proceso de pensamiento del modelo o la incapacidad de usar una herramienta correctamente, lo cual puede mitigarse con orientación del usuario (ej. \"Intenta dividir la tarea en pasos más pequeños\").", "violated_organization_allowlist": "Error al ejecutar la tarea: el perfil actual no es compatible con la configuración de tu organización", "condense_failed": "Error al condensar el contexto", @@ -123,6 +124,7 @@ "warnings": { "no_terminal_content": "No hay contenido de terminal seleccionado", "auto_import_failed": "Error al importar automáticamente la configuración de ZooCode: {{error}}", + "settings_export_location_not_remembered": "Configuración exportada a {{path}}, pero la ubicación no se pudo recordar para la próxima exportación: {{error}}", "rooHistoryImport": { "nothingFound": "No se encontró historial de tareas de Roo Code para importar desde {{domain}}.", "alreadyImported_one": "El historial de {{count}} tarea de Roo Code ya ha sido importado en Zoo Code.", @@ -134,6 +136,7 @@ "custom_storage_path_set": "Ruta de almacenamiento personalizada establecida: {{path}}", "default_storage_path": "Se ha vuelto a usar la ruta de almacenamiento predeterminada", "settings_imported": "Configuración importada correctamente.", + "settings_exported": "Configuración exportada a {{path}}.", "auto_import_success": "Configuración de ZooCode importada automáticamente desde {{filename}}", "image_copied_to_clipboard": "URI de datos de imagen copiada al portapapeles", "image_saved": "Imagen guardada en {{path}}", diff --git a/src/i18n/locales/fr/common.json b/src/i18n/locales/fr/common.json index 03e911de49..01d871bf87 100644 --- a/src/i18n/locales/fr/common.json +++ b/src/i18n/locales/fr/common.json @@ -47,6 +47,7 @@ "cannot_access_path": "Impossible d'accéder au chemin {{path}} : {{error}}", "path_outside_workspace": "Le chemin est à l'extérieur de l'espace de travail", "settings_import_failed": "Échec de l'importation des paramètres : {{error}}", + "settings_export_failed": "Échec de l'exportation des paramètres : {{error}}", "mistake_limit_guidance": "Cela peut indiquer un échec dans le processus de réflexion du modèle ou une incapacité à utiliser un outil correctement, ce qui peut être atténué avec des conseils de l'utilisateur (par ex. \"Essaie de diviser la tâche en étapes plus petites\").", "violated_organization_allowlist": "Échec de l'exécution de la tâche : le profil actuel n'est pas compatible avec les paramètres de votre organisation", "condense_failed": "Échec de la condensation du contexte", @@ -123,6 +124,7 @@ "warnings": { "no_terminal_content": "Aucun contenu de terminal sélectionné", "auto_import_failed": "Échec de l'importation automatique des paramètres ZooCode : {{error}}", + "settings_export_location_not_remembered": "Paramètres exportés vers {{path}}, mais l'emplacement n'a pas pu être mémorisé pour le prochain export : {{error}}", "rooHistoryImport": { "nothingFound": "Aucun historique de tâches Roo Code trouvé à importer depuis {{domain}}.", "alreadyImported_one": "L'historique de {{count}} tâche Roo Code a déjà été importé dans Zoo Code.", @@ -134,6 +136,7 @@ "custom_storage_path_set": "Chemin de stockage personnalisé défini : {{path}}", "default_storage_path": "Retour au chemin de stockage par défaut", "settings_imported": "Paramètres importés avec succès.", + "settings_exported": "Paramètres exportés vers {{path}}.", "auto_import_success": "Paramètres ZooCode importés automatiquement depuis {{filename}}", "image_copied_to_clipboard": "URI de données d'image copiée dans le presse-papiers", "image_saved": "Image enregistrée dans {{path}}", diff --git a/src/i18n/locales/hi/common.json b/src/i18n/locales/hi/common.json index 36479f1060..38c8938587 100644 --- a/src/i18n/locales/hi/common.json +++ b/src/i18n/locales/hi/common.json @@ -47,6 +47,7 @@ "cannot_access_path": "पाथ {{path}} तक पहुंच नहीं पा रहे हैं: {{error}}", "path_outside_workspace": "पथ वर्कस्पेस से बाहर है", "settings_import_failed": "सेटिंग्स इम्पोर्ट करने में विफल: {{error}}।", + "settings_export_failed": "सेटिंग्स निर्यात करने में विफल: {{error}}", "mistake_limit_guidance": "यह मॉडल की सोच प्रक्रिया में विफलता या किसी टूल का सही उपयोग न कर पाने का संकेत हो सकता है, जिसे उपयोगकर्ता के मार्गदर्शन से ठीक किया जा सकता है (जैसे \"कार्य को छोटे चरणों में बांटने की कोशिश करें\")।", "violated_organization_allowlist": "कार्य चलाने में विफल: वर्तमान प्रोफ़ाइल आपके संगठन की सेटिंग्स के साथ संगत नहीं है", "condense_failed": "संदर्भ को संक्षिप्त करने में विफल", @@ -123,6 +124,7 @@ "warnings": { "no_terminal_content": "कोई टर्मिनल सामग्री चयनित नहीं", "auto_import_failed": "ZooCode सेटिंग्स का स्वचालित आयात विफल: {{error}}", + "settings_export_location_not_remembered": "सेटिंग्स {{path}} में निर्यात की गईं, लेकिन अगले निर्यात के लिए स्थान याद नहीं रखा जा सका: {{error}}", "rooHistoryImport": { "nothingFound": "{{domain}} से आयात करने के लिए कोई Roo Code कार्य इतिहास नहीं मिला।", "alreadyImported_one": "सभी {{count}} Roo Code कार्य इतिहास पहले से ही Zoo Code में आयात किया जा चुका है।", @@ -134,6 +136,7 @@ "custom_storage_path_set": "कस्टम स्टोरेज पाथ सेट किया गया: {{path}}", "default_storage_path": "डिफ़ॉल्ट स्टोरेज पाथ का उपयोग पुनः शुरू किया गया", "settings_imported": "सेटिंग्स सफलतापूर्वक इम्पोर्ट की गईं।", + "settings_exported": "सेटिंग्स {{path}} में निर्यात की गईं।", "auto_import_success": "ZooCode सेटिंग्स {{filename}} से स्वचालित रूप से आयात की गईं", "image_copied_to_clipboard": "छवि डेटा URI क्लिपबोर्ड में कॉपी की गई", "image_saved": "छवि {{path}} में सहेजी गई", diff --git a/src/i18n/locales/id/common.json b/src/i18n/locales/id/common.json index d047cf3cbf..6771e019ab 100644 --- a/src/i18n/locales/id/common.json +++ b/src/i18n/locales/id/common.json @@ -47,6 +47,7 @@ "cannot_access_path": "Tidak dapat mengakses path {{path}}: {{error}}", "path_outside_workspace": "Path berada di luar workspace", "settings_import_failed": "Impor pengaturan gagal: {{error}}.", + "settings_export_failed": "Gagal mengekspor pengaturan: {{error}}", "mistake_limit_guidance": "Ini mungkin menunjukkan kegagalan dalam proses pemikiran model atau ketidakmampuan untuk menggunakan tool dengan benar, yang dapat diatasi dengan beberapa panduan pengguna (misalnya \"Coba bagi tugas menjadi langkah-langkah yang lebih kecil\").", "violated_organization_allowlist": "Gagal menjalankan tugas: profil saat ini tidak kompatibel dengan pengaturan organisasi kamu", "condense_failed": "Gagal mengompres konteks", @@ -123,6 +124,7 @@ "warnings": { "no_terminal_content": "Tidak ada konten terminal yang dipilih", "auto_import_failed": "Gagal mengimpor pengaturan ZooCode secara otomatis: {{error}}", + "settings_export_location_not_remembered": "Pengaturan diekspor ke {{path}}, tetapi lokasi tidak dapat diingat untuk ekspor berikutnya: {{error}}", "rooHistoryImport": { "nothingFound": "Tidak ada riwayat tugas Roo Code yang ditemukan untuk diimpor dari {{domain}}.", "alreadyImported_one": "Semua {{count}} riwayat tugas Roo Code sudah diimpor ke Zoo Code.", @@ -134,6 +136,7 @@ "custom_storage_path_set": "Path penyimpanan kustom diatur: {{path}}", "default_storage_path": "Kembali menggunakan path penyimpanan default", "settings_imported": "Pengaturan berhasil diimpor.", + "settings_exported": "Pengaturan diekspor ke {{path}}.", "auto_import_success": "Pengaturan ZooCode berhasil diimpor secara otomatis dari {{filename}}", "image_copied_to_clipboard": "Data URI gambar disalin ke clipboard", "image_saved": "Gambar disimpan ke {{path}}", diff --git a/src/i18n/locales/it/common.json b/src/i18n/locales/it/common.json index ecdf443a3d..99e3aeebaf 100644 --- a/src/i18n/locales/it/common.json +++ b/src/i18n/locales/it/common.json @@ -47,6 +47,7 @@ "cannot_access_path": "Impossibile accedere al percorso {{path}}: {{error}}", "path_outside_workspace": "Il percorso è fuori dall'area di lavoro", "settings_import_failed": "Importazione delle impostazioni fallita: {{error}}.", + "settings_export_failed": "Esportazione delle impostazioni non riuscita: {{error}}", "mistake_limit_guidance": "Questo può indicare un fallimento nel processo di pensiero del modello o l'incapacità di utilizzare correttamente uno strumento, che può essere mitigato con la guida dell'utente (ad es. \"Prova a suddividere l'attività in passaggi più piccoli\").", "violated_organization_allowlist": "Impossibile eseguire l'attività: il profilo corrente non è compatibile con le impostazioni della tua organizzazione", "condense_failed": "Impossibile condensare il contesto", @@ -123,6 +124,7 @@ "warnings": { "no_terminal_content": "Nessun contenuto del terminale selezionato", "auto_import_failed": "Importazione automatica delle impostazioni ZooCode fallita: {{error}}", + "settings_export_location_not_remembered": "Impostazioni esportate in {{path}}, ma la posizione non è stata memorizzata per l'esportazione successiva: {{error}}", "rooHistoryImport": { "nothingFound": "Nessuna cronologia di attività Roo Code trovata da importare da {{domain}}.", "alreadyImported_one": "La cronologia di {{count}} attività Roo Code è già stata importata in Zoo Code.", @@ -134,6 +136,7 @@ "custom_storage_path_set": "Percorso di archiviazione personalizzato impostato: {{path}}", "default_storage_path": "Tornato al percorso di archiviazione predefinito", "settings_imported": "Impostazioni importate con successo.", + "settings_exported": "Impostazioni esportate in {{path}}.", "auto_import_success": "Impostazioni ZooCode importate automaticamente da {{filename}}", "image_copied_to_clipboard": "URI dati dell'immagine copiato negli appunti", "image_saved": "Immagine salvata in {{path}}", diff --git a/src/i18n/locales/ja/common.json b/src/i18n/locales/ja/common.json index 2220a608d6..dc612a8a9a 100644 --- a/src/i18n/locales/ja/common.json +++ b/src/i18n/locales/ja/common.json @@ -47,6 +47,7 @@ "cannot_access_path": "パス {{path}} にアクセスできません:{{error}}", "path_outside_workspace": "パスはワークスペースの外にあります", "settings_import_failed": "設定のインポートに失敗しました:{{error}}", + "settings_export_failed": "設定のエクスポートに失敗しました: {{error}}", "mistake_limit_guidance": "これは、モデルの思考プロセスの失敗やツールを適切に使用できないことを示している可能性があり、ユーザーのガイダンスによって軽減できます(例:「タスクをより小さなステップに分割してみてください」)。", "violated_organization_allowlist": "タスクの実行に失敗しました: 現在のプロファイルは組織の設定と互換性がありません", "condense_failed": "コンテキストの圧縮に失敗しました", @@ -123,6 +124,7 @@ "warnings": { "no_terminal_content": "選択されたターミナルコンテンツがありません", "auto_import_failed": "ZooCode設定の自動インポートに失敗しました:{{error}}", + "settings_export_location_not_remembered": "設定を {{path}} にエクスポートしましたが、次のエクスポート用の保存場所を記憶できませんでした:{{error}}", "rooHistoryImport": { "nothingFound": "{{domain}}からインポートするRoo Codeのタスク履歴が見つかりませんでした。", "alreadyImported_one": "{{count}}件のRoo Codeタスク履歴はすでにZoo Codeにインポート済みです。", @@ -134,6 +136,7 @@ "custom_storage_path_set": "カスタムストレージパスが設定されました:{{path}}", "default_storage_path": "デフォルトのストレージパスに戻りました", "settings_imported": "設定が正常にインポートされました。", + "settings_exported": "設定を {{path}} にエクスポートしました。", "auto_import_success": "ZooCode設定が{{filename}}から自動インポートされました", "image_copied_to_clipboard": "画像データURIがクリップボードにコピーされました", "image_saved": "画像を{{path}}に保存しました", diff --git a/src/i18n/locales/ko/common.json b/src/i18n/locales/ko/common.json index b462dc8056..3bf22bdbad 100644 --- a/src/i18n/locales/ko/common.json +++ b/src/i18n/locales/ko/common.json @@ -47,6 +47,7 @@ "cannot_access_path": "경로 {{path}}에 접근할 수 없습니다: {{error}}", "path_outside_workspace": "경로가 작업 영역 밖에 있습니다", "settings_import_failed": "설정 가져오기 실패: {{error}}.", + "settings_export_failed": "설정 내보내기 실패: {{error}}", "mistake_limit_guidance": "이는 모델의 사고 과정 실패나 도구를 제대로 사용하지 못하는 것을 나타낼 수 있으며, 사용자 가이드를 통해 완화할 수 있습니다 (예: \"작업을 더 작은 단계로 나누어 시도해보세요\").", "violated_organization_allowlist": "작업 실행 실패: 현재 프로필이 조직 설정과 호환되지 않습니다", "condense_failed": "컨텍스트 압축에 실패했습니다", @@ -123,6 +124,7 @@ "warnings": { "no_terminal_content": "선택된 터미널 내용이 없습니다", "auto_import_failed": "ZooCode 설정 자동 가져오기 실패: {{error}}", + "settings_export_location_not_remembered": "설정을 {{path}}(으)로 내보냈습니다만 다음 내보내기할 위치를 기억하지 못했습니다: {{error}}", "rooHistoryImport": { "nothingFound": "{{domain}}에서 가져올 Roo Code 작업 기록을 찾을 수 없습니다.", "alreadyImported_one": "{{count}}개의 Roo Code 작업 기록이 이미 Zoo Code로 가져와졌습니다.", @@ -134,6 +136,7 @@ "custom_storage_path_set": "사용자 지정 저장 경로 설정됨: {{path}}", "default_storage_path": "기본 저장 경로로 되돌아갔습니다", "settings_imported": "설정이 성공적으로 가져와졌습니다.", + "settings_exported": "설정을 {{path}}(으)로 내보냈습니다.", "auto_import_success": "{{filename}}에서 ZooCode 설정을 자동으로 가져왔습니다", "image_copied_to_clipboard": "이미지 데이터 URI가 클립보드에 복사되었습니다", "image_saved": "이미지가 {{path}}에 저장되었습니다", diff --git a/src/i18n/locales/nl/common.json b/src/i18n/locales/nl/common.json index 01523541d9..4aad7790b6 100644 --- a/src/i18n/locales/nl/common.json +++ b/src/i18n/locales/nl/common.json @@ -47,6 +47,7 @@ "cannot_access_path": "Kan pad {{path}} niet openen: {{error}}", "path_outside_workspace": "Pad is buiten de werkomgeving", "settings_import_failed": "Importeren van instellingen mislukt: {{error}}.", + "settings_export_failed": "Instellingen exporteren mislukt: {{error}}", "mistake_limit_guidance": "Dit kan duiden op een fout in het denkproces van het model of het onvermogen om een tool correct te gebruiken, wat kan worden verminderd met gebruikersbegeleiding (bijv. \"Probeer de taak op te delen in kleinere stappen\").", "violated_organization_allowlist": "Taak uitvoeren mislukt: het huidige profiel is niet compatibel met de instellingen van uw organisatie", "condense_failed": "Comprimeren van context mislukt", @@ -123,6 +124,7 @@ "warnings": { "no_terminal_content": "Geen terminalinhoud geselecteerd", "auto_import_failed": "Automatisch importeren van ZooCode-instellingen mislukt: {{error}}", + "settings_export_location_not_remembered": "Instellingen geëxporteerd naar {{path}}, maar de locatie kon niet worden onthouden voor de volgende export: {{error}}", "rooHistoryImport": { "nothingFound": "Geen Roo Code-taakgeschiedenis gevonden om te importeren van {{domain}}.", "alreadyImported_one": "De {{count}} Roo Code-taakgeschiedenis is al geïmporteerd in Zoo Code.", @@ -134,6 +136,7 @@ "custom_storage_path_set": "Aangepast opslagpad ingesteld: {{path}}", "default_storage_path": "Terug naar standaard opslagpad", "settings_imported": "Instellingen succesvol geïmporteerd.", + "settings_exported": "Instellingen geëxporteerd naar {{path}}.", "auto_import_success": "ZooCode-instellingen automatisch geïmporteerd van {{filename}}", "image_copied_to_clipboard": "Afbeelding data-URI gekopieerd naar klembord", "image_saved": "Afbeelding opgeslagen naar {{path}}", diff --git a/src/i18n/locales/pl/common.json b/src/i18n/locales/pl/common.json index d2b6412257..e70eeff192 100644 --- a/src/i18n/locales/pl/common.json +++ b/src/i18n/locales/pl/common.json @@ -47,6 +47,7 @@ "cannot_access_path": "Nie można uzyskać dostępu do ścieżki {{path}}: {{error}}", "path_outside_workspace": "Ścieżka znajduje się poza obszarem roboczym", "settings_import_failed": "Nie udało się zaimportować ustawień: {{error}}.", + "settings_export_failed": "Nie udało się wyeksportować ustawień: {{error}}", "mistake_limit_guidance": "To może wskazywać na błąd w procesie myślowym modelu lub niezdolność do prawidłowego użycia narzędzia, co można złagodzić poprzez wskazówki użytkownika (np. \"Spróbuj podzielić zadanie na mniejsze kroki\").", "violated_organization_allowlist": "Nie udało się uruchomić zadania: bieżący profil nie jest kompatybilny z ustawieniami Twojej organizacji", "condense_failed": "Nie udało się skondensować kontekstu", @@ -123,6 +124,7 @@ "warnings": { "no_terminal_content": "Nie wybrano zawartości terminala", "auto_import_failed": "Nie udało się automatycznie zaimportować ustawień ZooCode: {{error}}", + "settings_export_location_not_remembered": "Ustawienia wyeksportowane do {{path}}, ale nie udało się zapamiętać lokalizacji do następnego eksportu: {{error}}", "rooHistoryImport": { "nothingFound": "Nie znaleziono historii zadań Roo Code do zaimportowania z {{domain}}.", "alreadyImported_one": "Cała {{count}} historia zadań Roo Code została już zaimportowana do Zoo Code.", @@ -134,6 +136,7 @@ "custom_storage_path_set": "Ustawiono niestandardową ścieżkę przechowywania: {{path}}", "default_storage_path": "Wznowiono używanie domyślnej ścieżki przechowywania", "settings_imported": "Ustawienia zaimportowane pomyślnie.", + "settings_exported": "Ustawienia wyeksportowane do {{path}}.", "auto_import_success": "Ustawienia ZooCode zostały automatycznie zaimportowane z {{filename}}", "image_copied_to_clipboard": "URI danych obrazu skopiowane do schowka", "image_saved": "Obraz zapisany w {{path}}", diff --git a/src/i18n/locales/pt-BR/common.json b/src/i18n/locales/pt-BR/common.json index 02e65d5ab9..164733d987 100644 --- a/src/i18n/locales/pt-BR/common.json +++ b/src/i18n/locales/pt-BR/common.json @@ -51,6 +51,7 @@ "cannot_access_path": "Não é possível acessar o caminho {{path}}: {{error}}", "path_outside_workspace": "O caminho está fora do espaço de trabalho", "settings_import_failed": "Falha ao importar configurações: {{error}}", + "settings_export_failed": "Falha ao exportar configurações: {{error}}", "mistake_limit_guidance": "Isso pode indicar uma falha no processo de pensamento do modelo ou incapacidade de usar uma ferramenta adequadamente, o que pode ser mitigado com orientação do usuário (ex. \"Tente dividir a tarefa em etapas menores\").", "violated_organization_allowlist": "Falha ao executar a tarefa: o perfil atual não é compatível com as configurações da sua organização", "condense_failed": "Falha ao condensar o contexto", @@ -127,6 +128,7 @@ "warnings": { "no_terminal_content": "Nenhum conteúdo do terminal selecionado", "auto_import_failed": "Falha ao importar automaticamente as configurações do ZooCode: {{error}}", + "settings_export_location_not_remembered": "Configurações exportadas para {{path}}, mas o local não pôde ser lembrado para a próxima exportação: {{error}}", "rooHistoryImport": { "nothingFound": "Nenhum histórico de tarefas do Roo Code encontrado para importar de {{domain}}.", "alreadyImported_one": "O histórico de {{count}} tarefa do Roo Code já foi importado para o Zoo Code.", @@ -138,6 +140,7 @@ "custom_storage_path_set": "Caminho de armazenamento personalizado definido: {{path}}", "default_storage_path": "Retornado ao caminho de armazenamento padrão", "settings_imported": "Configurações importadas com sucesso.", + "settings_exported": "Configurações exportadas para {{path}}.", "auto_import_success": "Configurações do ZooCode importadas automaticamente de {{filename}}", "image_copied_to_clipboard": "URI de dados da imagem copiada para a área de transferência", "image_saved": "Imagem salva em {{path}}", diff --git a/src/i18n/locales/ru/common.json b/src/i18n/locales/ru/common.json index 64e60ab2ff..46a74af83e 100644 --- a/src/i18n/locales/ru/common.json +++ b/src/i18n/locales/ru/common.json @@ -47,6 +47,7 @@ "cannot_access_path": "Невозможно получить доступ к пути {{path}}: {{error}}", "path_outside_workspace": "Путь находится вне рабочего пространства", "settings_import_failed": "Не удалось импортировать настройки: {{error}}.", + "settings_export_failed": "Не удалось экспортировать настройки: {{error}}", "mistake_limit_guidance": "Это может указывать на сбой в процессе мышления модели или неспособность правильно использовать инструмент, что можно смягчить с помощью руководства пользователя (например, \"Попробуйте разбить задачу на более мелкие шаги\").", "violated_organization_allowlist": "Не удалось выполнить задачу: текущий профиль несовместим с настройками вашей организации", "condense_failed": "Не удалось сжать контекст", @@ -123,6 +124,7 @@ "warnings": { "no_terminal_content": "Не выбрано содержимое терминала", "auto_import_failed": "Не удалось автоматически импортировать настройки ZooCode: {{error}}", + "settings_export_location_not_remembered": "Настройки экспортированы в {{path}}, но расположение не удалось запомнить для следующего экспорта: {{error}}", "rooHistoryImport": { "nothingFound": "История задач Roo Code для импорта из {{domain}} не найдена.", "alreadyImported_one": "{{count}} история задач Roo Code уже импортирована в Zoo Code.", @@ -134,6 +136,7 @@ "custom_storage_path_set": "Установлен пользовательский путь хранения: {{path}}", "default_storage_path": "Возвращено использование пути хранения по умолчанию", "settings_imported": "Настройки успешно импортированы.", + "settings_exported": "Настройки экспортированы в {{path}}.", "auto_import_success": "Настройки ZooCode автоматически импортированы из {{filename}}", "image_copied_to_clipboard": "URI данных изображения скопирован в буфер обмена", "image_saved": "Изображение сохранено в {{path}}", diff --git a/src/i18n/locales/tr/common.json b/src/i18n/locales/tr/common.json index 992e03a419..9548d9fb9d 100644 --- a/src/i18n/locales/tr/common.json +++ b/src/i18n/locales/tr/common.json @@ -47,6 +47,7 @@ "cannot_access_path": "{{path}} yoluna erişilemiyor: {{error}}", "path_outside_workspace": "Yol çalışma alanının dışında", "settings_import_failed": "Ayarlar içe aktarılamadı: {{error}}.", + "settings_export_failed": "Ayarlar dışa aktarılamadı: {{error}}", "mistake_limit_guidance": "Bu, modelin düşünce sürecindeki bir başarısızlığı veya bir aracı düzgün kullanamama durumunu gösterebilir, bu da kullanıcı rehberliği ile hafifletilebilir (örn. \"Görevi daha küçük adımlara bölmeyi deneyin\").", "violated_organization_allowlist": "Görev yürütülemedi: Geçerli profil kuruluşunuzun ayarlarıyla uyumlu değil", "condense_failed": "Bağlam sıkıştırılamadı", @@ -123,6 +124,7 @@ "warnings": { "no_terminal_content": "Seçili terminal içeriği yok", "auto_import_failed": "ZooCode ayarları otomatik olarak içe aktarılamadı: {{error}}", + "settings_export_location_not_remembered": "Ayarlar {{path}} konumuna dışa aktarıldı, ancak sonraki dışa aktarma için konum hatırlanamadı: {{error}}", "rooHistoryImport": { "nothingFound": "{{domain}} kaynağından içe aktarılacak Roo Code görev geçmişi bulunamadı.", "alreadyImported_one": "{{count}} Roo Code görev geçmişinin tamamı zaten Zoo Code'a aktarılmış.", @@ -134,6 +136,7 @@ "custom_storage_path_set": "Özel depolama yolu ayarlandı: {{path}}", "default_storage_path": "Varsayılan depolama yoluna geri dönüldü", "settings_imported": "Ayarlar başarıyla içe aktarıldı.", + "settings_exported": "Ayarlar {{path}} konumuna dışa aktarıldı.", "auto_import_success": "ZooCode ayarları {{filename}} dosyasından otomatik olarak içe aktarıldı", "image_copied_to_clipboard": "Resim veri URI'si panoya kopyalandı", "image_saved": "Resim {{path}} konumuna kaydedildi", diff --git a/src/i18n/locales/vi/common.json b/src/i18n/locales/vi/common.json index 94c61bdaae..5207224db4 100644 --- a/src/i18n/locales/vi/common.json +++ b/src/i18n/locales/vi/common.json @@ -47,6 +47,7 @@ "cannot_access_path": "Không thể truy cập đường dẫn {{path}}: {{error}}", "path_outside_workspace": "Đường dẫn nằm ngoài không gian làm việc", "settings_import_failed": "Nhập cài đặt thất bại: {{error}}.", + "settings_export_failed": "Không xuất được cài đặt: {{error}}", "mistake_limit_guidance": "Điều này có thể cho thấy sự thất bại trong quá trình suy nghĩ của mô hình hoặc không thể sử dụng công cụ đúng cách, có thể được giảm thiểu bằng hướng dẫn của người dùng (ví dụ: \"Hãy thử chia nhỏ nhiệm vụ thành các bước nhỏ hơn\").", "violated_organization_allowlist": "Không thể chạy tác vụ: hồ sơ hiện tại không tương thích với cài đặt của tổ chức của bạn", "condense_failed": "Không thể nén ngữ cảnh", @@ -123,6 +124,7 @@ "warnings": { "no_terminal_content": "Không có nội dung terminal được chọn", "auto_import_failed": "Không thể tự động nhập cài đặt ZooCode: {{error}}", + "settings_export_location_not_remembered": "Cài đặt đã được xuất tới {{path}}, nhưng không thể ghi nhớ vị trí cho lần xuất tiếp theo: {{error}}", "rooHistoryImport": { "nothingFound": "Không tìm thấy lịch sử nhiệm vụ Roo Code nào để nhập từ {{domain}}.", "alreadyImported_one": "{{count}} lịch sử nhiệm vụ Roo Code đã được nhập vào Zoo Code.", @@ -134,6 +136,7 @@ "custom_storage_path_set": "Đã thiết lập đường dẫn lưu trữ tùy chỉnh: {{path}}", "default_storage_path": "Đã quay lại sử dụng đường dẫn lưu trữ mặc định", "settings_imported": "Cài đặt đã được nhập thành công.", + "settings_exported": "Cài đặt đã được xuất tới {{path}}.", "auto_import_success": "Cài đặt ZooCode đã được tự động nhập từ {{filename}}", "image_copied_to_clipboard": "URI dữ liệu hình ảnh đã được sao chép vào clipboard", "image_saved": "Hình ảnh đã được lưu vào {{path}}", diff --git a/src/i18n/locales/zh-CN/common.json b/src/i18n/locales/zh-CN/common.json index 2c39a92571..3d1717f23d 100644 --- a/src/i18n/locales/zh-CN/common.json +++ b/src/i18n/locales/zh-CN/common.json @@ -52,6 +52,7 @@ "cannot_access_path": "无法访问路径 {{path}}:{{error}}", "path_outside_workspace": "路径位于工作区之外", "settings_import_failed": "设置导入失败:{{error}}。", + "settings_export_failed": "导出设置失败:{{error}}", "mistake_limit_guidance": "这可能表明模型思维过程失败或无法正确使用工具,可通过用户指导来缓解(例如\"尝试将任务分解为更小的步骤\")。", "violated_organization_allowlist": "执行任务失败:当前配置文件与您的组织设置不兼容", "condense_failed": "压缩上下文失败", @@ -128,6 +129,7 @@ "warnings": { "no_terminal_content": "没有选择终端内容", "auto_import_failed": "自动导入 ZooCode 设置失败:{{error}}", + "settings_export_location_not_remembered": "设置已导出到 {{path}},但无法记住下次导出所用的位置:{{error}}", "rooHistoryImport": { "nothingFound": "未找到可从 {{domain}} 导入的 Roo Code 任务历史记录。", "alreadyImported_one": "全部 {{count}} 条 Roo Code 任务历史记录已导入 Zoo Code。", @@ -139,6 +141,7 @@ "custom_storage_path_set": "自定义存储路径已设置:{{path}}", "default_storage_path": "已恢复使用默认存储路径", "settings_imported": "设置已成功导入。", + "settings_exported": "设置已导出到 {{path}}。", "auto_import_success": "已自动导入 ZooCode 设置:{{filename}}", "image_copied_to_clipboard": "图片数据 URI 已复制到剪贴板", "image_saved": "图片已保存到 {{path}}", diff --git a/src/i18n/locales/zh-TW/common.json b/src/i18n/locales/zh-TW/common.json index a96493284b..ea9ae9f69c 100644 --- a/src/i18n/locales/zh-TW/common.json +++ b/src/i18n/locales/zh-TW/common.json @@ -47,6 +47,7 @@ "cannot_access_path": "無法存取路徑 {{path}}:{{error}}", "path_outside_workspace": "路徑位於工作區之外", "settings_import_failed": "設定匯入失敗:{{error}}。", + "settings_export_failed": "匯出設定失敗:{{error}}", "mistake_limit_guidance": "這可能表明模型思維過程失敗或無法正確使用工具,可透過使用者指導來緩解(例如「嘗試將工作分解為更小的步驟」)。", "violated_organization_allowlist": "執行工作失敗:目前設定檔與您的組織設定不相容", "condense_failed": "壓縮上下文失敗", @@ -123,6 +124,7 @@ "warnings": { "no_terminal_content": "沒有選擇終端機內容", "auto_import_failed": "自動匯入 ZooCode 設定失敗:{{error}}", + "settings_export_location_not_remembered": "設定已匯出到 {{path}},但無法記住下次匯出所使用的位置:{{error}}", "rooHistoryImport": { "nothingFound": "未找到可從 {{domain}} 匯入的 Roo Code 工作歷史記錄。", "alreadyImported_one": "全部 {{count}} 筆 Roo Code 工作歷史記錄已匯入 Zoo Code。", @@ -134,6 +136,7 @@ "custom_storage_path_set": "自訂儲存路徑已設定:{{path}}", "default_storage_path": "已恢復使用預設儲存路徑", "settings_imported": "設定已成功匯入。", + "settings_exported": "設定已匯出到 {{path}}。", "auto_import_success": "已自動匯入 ZooCode 設定:{{filename}}", "image_copied_to_clipboard": "圖片資料 URI 已複製到剪貼簿", "image_saved": "圖片已儲存至 {{path}}", diff --git a/src/utils/__tests__/export.spec.ts b/src/utils/__tests__/export.spec.ts new file mode 100644 index 0000000000..3b84a03030 --- /dev/null +++ b/src/utils/__tests__/export.spec.ts @@ -0,0 +1,219 @@ +// npx vitest utils/__tests__/export.spec.ts + +import * as path from "path" + +import { constants } from "fs/promises" + +import type * as vscode from "vscode" + +import { resolveDefaultSaveUri, saveLastExportPath } from "../export" + +import type { ExportContext, ExportOptions } from "../export" + +const mocks = vi.hoisted(() => ({ + workspaceFolders: undefined as undefined | { uri: { fsPath: string } }[], + uriFile: vi.fn((filePath: string) => ({ fsPath: filePath })), + stat: vi.fn(), + access: vi.fn(), +})) + +vi.mock("vscode", () => ({ + Uri: { file: mocks.uriFile }, + workspace: { + get workspaceFolders() { + return mocks.workspaceFolders + }, + }, +})) + +// `utils/export` checks the target directory with the named fs/promises +// exports, so the mock has to expose them as named exports too. +vi.mock("fs/promises", () => { + const fsPromises = { stat: mocks.stat, access: mocks.access, constants: { F_OK: 0, R_OK: 4, W_OK: 2, X_OK: 1 } } + return { ...fsPromises, default: fsPromises } +}) + +// Build every expected path with `path` helpers so the assertions hold on +// both win32 and POSIX runners. +const REMEMBERED_DIR = path.join("/usb") +const REMEMBERED = path.join(REMEMBERED_DIR, "zoo-code-settings.json") +const FALLBACK = path.join("/mock/home", "Downloads") + +function makeContext(remembered?: string): ExportContext { + return { + // Key-sensitive so a resolver that reads the wrong setting key is caught. + getValue: vi.fn((key: string) => (key === "lastSettingsExportPath" ? remembered : undefined)), + setValue: vi.fn().mockResolvedValue(undefined), + } +} + +async function resolveWith(remembered: string | undefined, options: ExportOptions = {}) { + const uri = await resolveDefaultSaveUri( + makeContext(remembered), + "lastSettingsExportPath", + "zoo-code-settings.json", + options, + ) + return uri.fsPath +} + +beforeEach(() => { + vi.clearAllMocks() + mocks.workspaceFolders = undefined + mocks.stat.mockResolvedValue({ isDirectory: () => true }) + mocks.access.mockResolvedValue(undefined) +}) + +describe("resolveDefaultSaveUri", () => { + it("uses the remembered directory while it is still a writable directory", async () => { + const resolved = await resolveWith(REMEMBERED, { useWorkspace: false }) + + expect(resolved).toBe(REMEMBERED) + expect(mocks.stat).toHaveBeenCalledWith(REMEMBERED_DIR) + expect(mocks.access).toHaveBeenCalledWith(REMEMBERED_DIR, constants.W_OK | constants.X_OK) + }) + + it("prefers the remembered directory over the workspace folder while it is still usable", async () => { + // The documented priority is remembered path before workspace folder, and the + // remembered branch does not consult useWorkspace, so the order has to be proven + // with a live remembered directory and the default options. + mocks.workspaceFolders = [{ uri: { fsPath: "/workspace" } }] + + const resolved = await resolveWith(REMEMBERED, {}) + + expect(resolved).toBe(REMEMBERED) + expect(resolved).not.toBe(path.join("/workspace", "zoo-code-settings.json")) + }) + + it("checks write permission instead of existence alone", async () => { + await resolveWith(REMEMBERED, { useWorkspace: false }) + + expect(mocks.access).toHaveBeenCalledWith(REMEMBERED_DIR, constants.W_OK | constants.X_OK) + expect(mocks.access).not.toHaveBeenCalledWith(REMEMBERED_DIR, constants.R_OK | constants.X_OK) + }) + + it("falls back when the remembered directory no longer exists", async () => { + mocks.stat.mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" })) + + const resolved = await resolveWith(REMEMBERED, { useWorkspace: false, fallbackDir: FALLBACK }) + + expect(resolved).toBe(path.join(FALLBACK, "zoo-code-settings.json")) + }) + + it("falls back when the remembered path was remounted under a missing drive", async () => { + const deadUsb = path.join("Z:\\gone", "zoo-code-settings.json") + mocks.stat.mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" })) + + const resolved = await resolveWith(deadUsb, { useWorkspace: false, fallbackDir: FALLBACK }) + + expect(resolved).toBe(path.join(FALLBACK, "zoo-code-settings.json")) + expect(mocks.stat).toHaveBeenCalledWith(path.dirname(deadUsb)) + }) + + it("falls back when the remembered directory became a regular file", async () => { + mocks.stat.mockResolvedValueOnce({ isDirectory: () => false }) + + const resolved = await resolveWith(REMEMBERED, { useWorkspace: false, fallbackDir: FALLBACK }) + + expect(resolved).toBe(path.join(FALLBACK, "zoo-code-settings.json")) + }) + + it("falls back when the remembered directory is read-only", async () => { + mocks.access.mockRejectedValueOnce(Object.assign(new Error("EACCES"), { code: "EACCES" })) + + const resolved = await resolveWith(REMEMBERED, { useWorkspace: false, fallbackDir: FALLBACK }) + + expect(resolved).toBe(path.join(FALLBACK, "zoo-code-settings.json")) + }) + + it("keeps a read-only remembered directory when the caller only reads from it", async () => { + // A read-only volume: write access fails, read access succeeds. + mocks.access.mockImplementation((_dir: string, mode: number) => + (mode & constants.W_OK) === constants.W_OK + ? Promise.reject(Object.assign(new Error("EACCES"), { code: "EACCES" })) + : Promise.resolve(), + ) + + const resolved = await resolveWith(REMEMBERED, { + useWorkspace: false, + fallbackDir: FALLBACK, + accessMode: constants.R_OK, + }) + + expect(resolved).toBe(REMEMBERED) + // Traversal is part of the check even when only reading is required. + expect(mocks.access).toHaveBeenCalledWith(REMEMBERED_DIR, constants.R_OK | constants.X_OK) + }) + + it("falls back when the remembered directory cannot be read either", async () => { + mocks.access.mockRejectedValue(Object.assign(new Error("EACCES"), { code: "EACCES" })) + + const resolved = await resolveWith(REMEMBERED, { + useWorkspace: false, + fallbackDir: FALLBACK, + accessMode: constants.R_OK, + }) + + expect(resolved).toBe(path.join(FALLBACK, "zoo-code-settings.json")) + }) + + it("uses the workspace folder when the remembered path is dead", async () => { + mocks.workspaceFolders = [{ uri: { fsPath: "/workspace" } }] + mocks.stat.mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" })) + + const resolved = await resolveWith(REMEMBERED, { fallbackDir: FALLBACK }) + + expect(resolved).toBe(path.join("/workspace", "zoo-code-settings.json")) + }) + + it("uses the workspace folder when no remembered path exists", async () => { + mocks.workspaceFolders = [{ uri: { fsPath: "/workspace" } }] + + const resolved = await resolveWith(undefined, { fallbackDir: FALLBACK }) + + expect(resolved).toBe(path.join("/workspace", "zoo-code-settings.json")) + expect(mocks.stat).not.toHaveBeenCalled() + }) + + it("skips the workspace folder when useWorkspace is false", async () => { + mocks.workspaceFolders = [{ uri: { fsPath: "/workspace" } }] + + const resolved = await resolveWith(undefined, { useWorkspace: false, fallbackDir: FALLBACK }) + + expect(resolved).toBe(path.join(FALLBACK, "zoo-code-settings.json")) + }) + + it("skips an empty workspace folder list instead of indexing into it", async () => { + mocks.workspaceFolders = [] + + const resolved = await resolveWith(undefined, { fallbackDir: FALLBACK }) + + expect(resolved).toBe(path.join(FALLBACK, "zoo-code-settings.json")) + }) + + it("uses the fallback directory when nothing else is available", async () => { + const resolved = await resolveWith(undefined, { fallbackDir: FALLBACK }) + + expect(resolved).toBe(path.join(FALLBACK, "zoo-code-settings.json")) + }) + + it("falls back to the bare filename when no directory is configured", async () => { + const resolved = await resolveWith(undefined, { useWorkspace: false }) + + expect(resolved).toBe("zoo-code-settings.json") + }) +}) + +describe("saveLastExportPath", () => { + it("stores the chosen file path under the requested key", async () => { + const context = makeContext() + + // The mocked vscode module has no Uri implementation, and saveLastExportPath + // only reads `fsPath`. + const chosen = { fsPath: "/usb/zoo-code-settings.json" } as unknown as vscode.Uri + + await saveLastExportPath(context, "lastSettingsExportPath", chosen) + + expect(context.setValue).toHaveBeenCalledWith("lastSettingsExportPath", "/usb/zoo-code-settings.json") + }) +}) diff --git a/src/utils/export.ts b/src/utils/export.ts index 8bd294e000..60bb424a24 100644 --- a/src/utils/export.ts +++ b/src/utils/export.ts @@ -1,5 +1,6 @@ import * as vscode from "vscode" import * as path from "path" +import { access, constants, stat } from "fs/promises" export interface ExportContext { getValue(key: string): unknown @@ -16,44 +17,84 @@ export interface ExportOptions { * Fallback directory if no previous path or workspace is available. */ fallbackDir?: string + /** + * The permission the remembered directory must still have to be used as the dialog + * default, as an `fs/promises` access constant. A save target has to be writable + * (`constants.W_OK`); an open dialog only has to be readable (`constants.R_OK`), + * otherwise a read-only folder that actually holds the file would be skipped in + * favour of the fallback directory. + * Default: constants.W_OK + */ + accessMode?: number +} + +/** + * Whether a directory can actually receive a saved file right now. + * + * A remembered export location is frequently on a removable or network drive + * that is gone by the next export (unmounted, or remounted under a different + * drive letter). Handing such a path to `showSaveDialog` does not fail loudly: + * the platform silently falls back to its own default folder, so the file lands + * somewhere the user never selected. Validating the directory first lets the + * resolver fall through to the documented priorities instead. + */ +async function isUsableSaveDirectory(dirPath: string, accessMode: number): Promise { + try { + const stats = await stat(dirPath) + if (!stats.isDirectory()) { + return false + } + // The access bits are what matter: a readable-but-read-only volume cannot + // receive an export, while an open dialog only reads from it. X_OK is ORed in + // because R_OK/W_OK alone do not test traversal, and a directory that cannot be + // searched cannot resolve a file inside it. Node ignores X_OK on Windows. + await access(dirPath, accessMode | constants.X_OK) + return true + } catch { + return false + } } /** * Resolves the default save URI for an export operation. * Priorities: - * 1. Last used export path (if available) + * 1. Last used export path, if that directory still exists and still has the + * access the caller needs (writable for a save, readable for an open) * 2. Active workspace folder (if useWorkspace is true) * 3. Fallback directory (e.g. Downloads or Documents) * 4. Default to just the filename (user's home/cwd) */ -export function resolveDefaultSaveUri( +export async function resolveDefaultSaveUri( context: ExportContext, configKey: string, fileName: string, options: ExportOptions = {}, -): vscode.Uri { - const { useWorkspace = true, fallbackDir } = options +): Promise { + const { useWorkspace = true, fallbackDir, accessMode = constants.W_OK } = options const lastExportPath = context.getValue(configKey) as string | undefined if (lastExportPath) { - // Use the directory from the last export + // Use the directory from the last export, but only while it is still a + // directory we can actually reach with the access this operation needs. const lastDir = path.dirname(lastExportPath) - return vscode.Uri.file(path.join(lastDir, fileName)) - } else { - // Try workspace if enabled - const workspaceFolders = vscode.workspace.workspaceFolders - if (useWorkspace && workspaceFolders && workspaceFolders.length > 0) { - return vscode.Uri.file(path.join(workspaceFolders[0].uri.fsPath, fileName)) + if (await isUsableSaveDirectory(lastDir, accessMode)) { + return vscode.Uri.file(path.join(lastDir, fileName)) } + } - // Fallback - if (fallbackDir) { - return vscode.Uri.file(path.join(fallbackDir, fileName)) - } + // Try workspace if enabled + const workspaceFolders = vscode.workspace.workspaceFolders + if (useWorkspace && workspaceFolders && workspaceFolders.length > 0) { + return vscode.Uri.file(path.join(workspaceFolders[0].uri.fsPath, fileName)) + } - // Default to cwd/home - return vscode.Uri.file(fileName) + // Fallback + if (fallbackDir) { + return vscode.Uri.file(path.join(fallbackDir, fileName)) } + + // Default to cwd/home + return vscode.Uri.file(fileName) } export async function saveLastExportPath(context: ExportContext, configKey: string, uri: vscode.Uri) {