From 05f8aa2ac82250629e7322818ad495eda2db30f7 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:40:44 +0800 Subject: [PATCH 01/17] fix(config): validate the remembered export directory before saving The save dialog default came straight from `lastSettingsExportPath` with no check that the directory still exists or is writable. When the remembered target is a removable drive that is no longer mounted, `showSaveDialog` does not fail loudly: it falls back to the platform default folder, so a settings export aimed at the USB drive lands in `~/Downloads` instead. - Reuse the remembered directory only while it is still a writable directory, otherwise fall through to the documented priorities (workspace, fallback). - Remember a location only after the file was actually written, so a failed export cannot steer the next dialog either. - Surface a failed export with an error message instead of logging to the console only, and report the location that received the file. - Await `resolveDefaultSaveUri` in `importSettings`, which is now async. Tests: new `src/utils/__tests__/export.spec.ts`; export/import flow regression tests in `importExport.spec.ts`, whose `i18n` mock now echoes the interpolation arguments (same approach as `webviewMessageHandler.openFile.spec.ts`); `locale-bundles.spec.ts` pins the two new `common.json` keys in all 18 locales. --- .../config/__tests__/importExport.spec.ts | 194 ++++++++++++++++-- src/core/config/importExport.ts | 16 +- src/i18n/__tests__/locale-bundles.spec.ts | 14 +- src/i18n/locales/ca/common.json | 2 + src/i18n/locales/de/common.json | 2 + src/i18n/locales/en/common.json | 2 + src/i18n/locales/es/common.json | 2 + src/i18n/locales/fr/common.json | 2 + src/i18n/locales/hi/common.json | 2 + src/i18n/locales/id/common.json | 2 + src/i18n/locales/it/common.json | 2 + src/i18n/locales/ja/common.json | 2 + src/i18n/locales/ko/common.json | 2 + src/i18n/locales/nl/common.json | 2 + src/i18n/locales/pl/common.json | 2 + src/i18n/locales/pt-BR/common.json | 2 + src/i18n/locales/ru/common.json | 2 + src/i18n/locales/tr/common.json | 2 + src/i18n/locales/vi/common.json | 2 + src/i18n/locales/zh-CN/common.json | 2 + src/i18n/locales/zh-TW/common.json | 2 + src/utils/__tests__/export.spec.ts | 176 ++++++++++++++++ src/utils/export.ts | 61 ++++-- 23 files changed, 455 insertions(+), 42 deletions(-) create mode 100644 src/utils/__tests__/export.spec.ts diff --git a/src/core/config/__tests__/importExport.spec.ts b/src/core/config/__tests__/importExport.spec.ts index 6c66655325..c9659ddb29 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 } + 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,6 +281,42 @@ describe("importExport", () => { expect(mockContextProxy.setValues).not.toHaveBeenCalled() }) + 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, + }) + + expect(vscode.Uri.file).toHaveBeenCalledWith(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.Uri.file).not.toHaveBeenCalledWith( + path.join(path.dirname(staleRemembered), "zoo-code-settings.json"), + ) + expect(vscode.Uri.file).toHaveBeenCalledWith(path.join("/mock/home", "Downloads", "zoo-code-settings.json")) + }) + it("should import settings successfully from a valid file", async () => { ;(vscode.window.showOpenDialog as Mock).mockResolvedValue([{ fsPath: "/mock/path/settings.json" }]) @@ -1679,9 +1722,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 () => { @@ -1710,6 +1759,109 @@ describe("importExport", () => { expect(safeWriteJson).not.toHaveBeenCalled() // Should not be called since mkdir failed. }) + 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 toast must name the file that actually received the export. + expect(vscode.window.showInformationMessage).toHaveBeenCalledWith( + expect.stringContaining("info.settings_exported"), + ) + expect(vscode.window.showInformationMessage).toHaveBeenCalledWith( + expect.stringContaining("/usb/zoo-code-settings.json"), + ) + }) + + 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.Uri.file).not.toHaveBeenCalledWith( + path.join(path.dirname(staleRemembered), "zoo-code-settings.json"), + ) + expect(vscode.Uri.file).toHaveBeenCalledWith(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.Uri.file).not.toHaveBeenCalledWith(path.join("/usb", "zoo-code-settings.json")) + expect(vscode.Uri.file).toHaveBeenCalledWith(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 is the property that matters for an export target. + expect(fs.access).toHaveBeenCalledWith(path.dirname(remembered), fsMocks.constants.W_OK) + expect(vscode.Uri.file).not.toHaveBeenCalledWith(path.join("/usb", "zoo-code-settings.json")) + expect(vscode.Uri.file).toHaveBeenCalledWith(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.Uri.file).toHaveBeenCalledWith(path.join("/usb", "zoo-code-settings.json")) + }) + it("should use the correct default save location", async () => { ;(vscode.window.showSaveDialog as Mock).mockResolvedValue(undefined) diff --git a/src/core/config/importExport.ts b/src/core/config/importExport.ts index 9882039ad3..470aeb57ac 100644 --- a/src/core/config/importExport.ts +++ b/src/core/config/importExport.ts @@ -271,7 +271,7 @@ export async function importSettingsFromPath( */ 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", { + const defaultUri = await resolveDefaultSaveUri(contextProxy, "lastSettingsExportPath", "zoo-code-settings.json", { useWorkspace: false, fallbackDir: path.join(os.homedir(), "Downloads"), }) @@ -327,8 +327,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 +346,19 @@ 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. + await saveLastExportPath(contextProxy, "lastSettingsExportPath", uri) + 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..aebd99a5d1 100644 --- a/src/i18n/__tests__/locale-bundles.spec.ts +++ b/src/i18n/__tests__/locale-bundles.spec.ts @@ -26,7 +26,7 @@ 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; info: Record }> = { ca, de, en, @@ -58,3 +58,15 @@ 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}}") + }) +}) diff --git a/src/i18n/locales/ca/common.json b/src/i18n/locales/ca/common.json index d414d697f2..ce57e2fb01 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", @@ -138,6 +139,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..5bdcab6fb8 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", @@ -134,6 +135,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..b70fda60ce 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", @@ -134,6 +135,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..836cd55069 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", @@ -134,6 +135,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..f58ae2f30d 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", @@ -134,6 +135,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..e4bfdc45a8 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": "संदर्भ को संक्षिप्त करने में विफल", @@ -134,6 +135,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..e6f3f3ded5 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", @@ -134,6 +135,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..b290c51c50 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", @@ -134,6 +135,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..f0973dd06b 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": "コンテキストの圧縮に失敗しました", @@ -134,6 +135,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..568b865a36 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": "컨텍스트 압축에 실패했습니다", @@ -134,6 +135,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..fcd0317526 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", @@ -134,6 +135,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..b022d5cb23 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", @@ -134,6 +135,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..83d9d293e6 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", @@ -138,6 +139,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..29124997f1 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": "Не удалось сжать контекст", @@ -134,6 +135,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..98d70126f9 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ı", @@ -134,6 +135,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..b0f51bb214 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", @@ -134,6 +135,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..faaeda182e 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": "压缩上下文失败", @@ -139,6 +140,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..6e14869d05 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": "壓縮上下文失敗", @@ -134,6 +135,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..e134ae7ba2 --- /dev/null +++ b/src/utils/__tests__/export.spec.ts @@ -0,0 +1,176 @@ +// 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 } 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 } } + 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 = {}) { + 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) + }) + + it("checks write permission instead of existence alone", async () => { + await resolveWith(REMEMBERED, { useWorkspace: false }) + + expect(mocks.access).toHaveBeenCalledWith(REMEMBERED_DIR, constants.W_OK) + expect(mocks.access).not.toHaveBeenCalledWith(REMEMBERED_DIR, constants.R_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("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..7c9e1865af 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 @@ -18,42 +19,70 @@ export interface ExportOptions { fallbackDir?: string } +/** + * 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): Promise { + try { + const stats = await stat(dirPath) + if (!stats.isDirectory()) { + return false + } + // W_OK is the property that matters: a readable-but-read-only volume cannot + // receive the export either. + await access(dirPath, constants.W_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 is writable * 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 { +): Promise { const { useWorkspace = true, fallbackDir } = 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 write to. 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)) { + 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) { From 4888f603af1b78971a8f196d09a30d138c63a067 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:17:16 +0800 Subject: [PATCH 02/17] fix(config): keep the export confirmation and the open-dialog default reachable Review findings on the previous commit: - `importSettings` only reads the remembered folder, so the open dialog now asks for read access (`constants.R_OK`). A read-only remembered folder that holds the settings file no longer gets dropped in favour of Downloads. - `exportSettings` confirms the written file before it remembers the location, and a failure to remember is logged instead of escaping into the unawaited message handler, where the user would never see the confirmation. - The remembered-default tests assert the dialog arguments (`defaultUri`) rather than only the URI the resolver built, and cover the read-only open case. Tests: 15 in `utils/__tests__/export.spec.ts`, 63 in `importExport.spec.ts` (1 pre-existing Windows failure, #2059); 24 hand-written mutants over the changed lines are all killed. --- .../config/__tests__/importExport.spec.ts | 135 ++++++++++++++++-- src/core/config/importExport.ts | 19 ++- src/utils/__tests__/export.spec.ts | 34 ++++- src/utils/export.ts | 26 ++-- 4 files changed, 188 insertions(+), 26 deletions(-) diff --git a/src/core/config/__tests__/importExport.spec.ts b/src/core/config/__tests__/importExport.spec.ts index c9659ddb29..bce1a0e5a4 100644 --- a/src/core/config/__tests__/importExport.spec.ts +++ b/src/core/config/__tests__/importExport.spec.ts @@ -294,7 +294,48 @@ describe("importExport", () => { customModesManager: mockCustomModesManager, }) - expect(vscode.Uri.file).toHaveBeenCalledWith(path.join("/usb", "zoo-code-settings.json")) + // 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 + ? 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) + 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 () => { @@ -311,10 +352,20 @@ describe("importExport", () => { customModesManager: mockCustomModesManager, }) - expect(vscode.Uri.file).not.toHaveBeenCalledWith( - path.join(path.dirname(staleRemembered), "zoo-code-settings.json"), + 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"), + }), + }), ) - expect(vscode.Uri.file).toHaveBeenCalledWith(path.join("/mock/home", "Downloads", "zoo-code-settings.json")) }) it("should import settings successfully from a valid file", async () => { @@ -1790,6 +1841,32 @@ describe("importExport", () => { ) }) + it("should still confirm the 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 confirmation the user just earned. + mockContextProxy.setValue.mockRejectedValueOnce(new Error("storage unavailable")) + + await exportSettings({ + providerSettingsManager: mockProviderSettingsManager, + contextProxy: mockContextProxy, + }) + + expect(safeWriteJson).toHaveBeenCalledWith("/usb/zoo-code-settings.json", expect.anything()) + expect(vscode.window.showInformationMessage).toHaveBeenCalledWith( + expect.stringContaining("info.settings_exported"), + ) + }) + 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) => @@ -1805,10 +1882,20 @@ describe("importExport", () => { // 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.Uri.file).not.toHaveBeenCalledWith( - path.join(path.dirname(staleRemembered), "zoo-code-settings.json"), + 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"), + }), + }), ) - expect(vscode.Uri.file).toHaveBeenCalledWith(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 () => { @@ -1824,8 +1911,18 @@ describe("importExport", () => { contextProxy: mockContextProxy, }) - expect(vscode.Uri.file).not.toHaveBeenCalledWith(path.join("/usb", "zoo-code-settings.json")) - expect(vscode.Uri.file).toHaveBeenCalledWith(path.join("/mock/home", "Downloads", "zoo-code-settings.json")) + 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 () => { @@ -1843,8 +1940,18 @@ describe("importExport", () => { // W_OK is the property that matters for an export target. expect(fs.access).toHaveBeenCalledWith(path.dirname(remembered), fsMocks.constants.W_OK) - expect(vscode.Uri.file).not.toHaveBeenCalledWith(path.join("/usb", "zoo-code-settings.json")) - expect(vscode.Uri.file).toHaveBeenCalledWith(path.join("/mock/home", "Downloads", "zoo-code-settings.json")) + 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 () => { @@ -1859,7 +1966,11 @@ describe("importExport", () => { contextProxy: mockContextProxy, }) - expect(vscode.Uri.file).toHaveBeenCalledWith(path.join("/usb", "zoo-code-settings.json")) + 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 470aeb57ac..28630e7f1e 100644 --- a/src/core/config/importExport.ts +++ b/src/core/config/importExport.ts @@ -270,10 +270,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 + // 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({ @@ -355,10 +358,18 @@ export const exportSettings = async ({ providerSettingsManager, contextProxy }: return } - // Remember only a location that actually received the file, so a failed - // export cannot steer the next dialog either. - await saveLastExportPath(contextProxy, "lastSettingsExportPath", uri) + // The file is on disk: confirm it before anything that can still fail. await vscode.window.showInformationMessage(t("common:info.settings_exported", { path: uri.fsPath })) + + // Remember only a location that actually received the file, so a failed export + // cannot steer the next dialog either. Failing to remember is not a failed + // export, so it must not swallow the confirmation above or escape into the + // unawaited message handler. + try { + await saveLastExportPath(contextProxy, "lastSettingsExportPath", uri) + } catch (e) { + console.error("Failed to remember the export location:", e) + } } /** diff --git a/src/utils/__tests__/export.spec.ts b/src/utils/__tests__/export.spec.ts index e134ae7ba2..35b3067a03 100644 --- a/src/utils/__tests__/export.spec.ts +++ b/src/utils/__tests__/export.spec.ts @@ -8,7 +8,7 @@ import type * as vscode from "vscode" import { resolveDefaultSaveUri, saveLastExportPath } from "../export" -import type { ExportContext } from "../export" +import type { ExportContext, ExportOptions } from "../export" const mocks = vi.hoisted(() => ({ workspaceFolders: undefined as undefined | { uri: { fsPath: string } }[], @@ -47,7 +47,7 @@ function makeContext(remembered?: string): ExportContext { } } -async function resolveWith(remembered: string | undefined, options = {}) { +async function resolveWith(remembered: string | undefined, options: ExportOptions = {}) { const uri = await resolveDefaultSaveUri( makeContext(remembered), "lastSettingsExportPath", @@ -114,6 +114,36 @@ describe("resolveDefaultSaveUri", () => { 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 + ? 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) + expect(mocks.access).toHaveBeenCalledWith(REMEMBERED_DIR, constants.R_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" })) diff --git a/src/utils/export.ts b/src/utils/export.ts index 7c9e1865af..ab4944862a 100644 --- a/src/utils/export.ts +++ b/src/utils/export.ts @@ -17,6 +17,15 @@ 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 } /** @@ -29,15 +38,15 @@ export interface ExportOptions { * somewhere the user never selected. Validating the directory first lets the * resolver fall through to the documented priorities instead. */ -async function isUsableSaveDirectory(dirPath: string): Promise { +async function isUsableSaveDirectory(dirPath: string, accessMode: number): Promise { try { const stats = await stat(dirPath) if (!stats.isDirectory()) { return false } - // W_OK is the property that matters: a readable-but-read-only volume cannot - // receive the export either. - await access(dirPath, constants.W_OK) + // The access mode is the property that matters: a readable-but-read-only volume + // cannot receive an export, while an open dialog only reads from it. + await access(dirPath, accessMode) return true } catch { return false @@ -47,7 +56,8 @@ async function isUsableSaveDirectory(dirPath: string): Promise { /** * Resolves the default save URI for an export operation. * Priorities: - * 1. Last used export path, if that directory still exists and is writable + * 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) @@ -58,14 +68,14 @@ export async function resolveDefaultSaveUri( fileName: string, options: ExportOptions = {}, ): Promise { - const { useWorkspace = true, fallbackDir } = options + 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, but only while it is still a - // directory we can actually write to. + // directory we can actually reach with the access this operation needs. const lastDir = path.dirname(lastExportPath) - if (await isUsableSaveDirectory(lastDir)) { + if (await isUsableSaveDirectory(lastDir, accessMode)) { return vscode.Uri.file(path.join(lastDir, fileName)) } } From 0ed9e0278a9b65b823f2bd22bb51c31bc848cac5 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:38:09 +0800 Subject: [PATCH 03/17] fix(config): check traversal and remember the export location before the toast Second review round on the previous commit: - `isUsableSaveDirectory` ORs `constants.X_OK` into the requested access bits. `R_OK`/`W_OK` alone do not test traversal on POSIX, and a directory that cannot be searched cannot resolve a file inside it; Node ignores `X_OK` on Windows, so the Windows result is unchanged. - `exportSettings` remembers the location before showing the confirmation: `showInformationMessage` only resolves once the notification is dismissed, so waiting for it would delay the remembered folder until the next export was already open. The guarded save still cannot swallow the confirmation. - Tests assert the combined access mode, and that `setValue` runs before `showInformationMessage`. Tests: 15 in `utils/__tests__/export.spec.ts`, 63 in `importExport.spec.ts` (1 pre-existing Windows failure, #2059); 20 hand-written mutants over the new delta are killed. --- .../config/__tests__/importExport.spec.ts | 22 ++++++++++++++----- src/core/config/importExport.ts | 11 +++++----- src/utils/__tests__/export.spec.ts | 13 ++++++----- src/utils/export.ts | 8 ++++--- 4 files changed, 35 insertions(+), 19 deletions(-) diff --git a/src/core/config/__tests__/importExport.spec.ts b/src/core/config/__tests__/importExport.spec.ts index bce1a0e5a4..becc0df6a2 100644 --- a/src/core/config/__tests__/importExport.spec.ts +++ b/src/core/config/__tests__/importExport.spec.ts @@ -59,7 +59,7 @@ const fsMocks = vi.hoisted(() => { const writeFile = vi.fn() const access = vi.fn() const stat = vi.fn() - const constants = { F_OK: 0, R_OK: 4, W_OK: 2 } + const constants = { F_OK: 0, R_OK: 4, W_OK: 2, X_OK: 1 } return { readFile, mkdir, writeFile, access, stat, constants } }) @@ -318,7 +318,7 @@ describe("importExport", () => { // 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 + (mode & fsMocks.constants.W_OK) === fsMocks.constants.W_OK ? Promise.reject(Object.assign(new Error("EACCES"), { code: "EACCES" })) : Promise.resolve(), ) @@ -330,7 +330,10 @@ describe("importExport", () => { customModesManager: mockCustomModesManager, }) - expect(fs.access).toHaveBeenCalledWith(path.dirname(remembered), fsMocks.constants.R_OK) + 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") }), @@ -1832,6 +1835,12 @@ describe("importExport", () => { "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. expect(vscode.window.showInformationMessage).toHaveBeenCalledWith( expect.stringContaining("info.settings_exported"), @@ -1938,8 +1947,11 @@ describe("importExport", () => { contextProxy: mockContextProxy, }) - // W_OK is the property that matters for an export target. - expect(fs.access).toHaveBeenCalledWith(path.dirname(remembered), fsMocks.constants.W_OK) + // 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") }), diff --git a/src/core/config/importExport.ts b/src/core/config/importExport.ts index 28630e7f1e..2e4395ac72 100644 --- a/src/core/config/importExport.ts +++ b/src/core/config/importExport.ts @@ -358,18 +358,19 @@ export const exportSettings = async ({ providerSettingsManager, contextProxy }: return } - // The file is on disk: confirm it before anything that can still fail. - await vscode.window.showInformationMessage(t("common:info.settings_exported", { path: uri.fsPath })) - // Remember only a location that actually received the file, so a failed export - // cannot steer the next dialog either. Failing to remember is not a failed - // export, so it must not swallow the confirmation above or escape into the + // 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 confirmation must still appear and the rejection must not escape into the // unawaited message handler. try { await saveLastExportPath(contextProxy, "lastSettingsExportPath", uri) } catch (e) { console.error("Failed to remember the export location:", e) } + + await vscode.window.showInformationMessage(t("common:info.settings_exported", { path: uri.fsPath })) } /** diff --git a/src/utils/__tests__/export.spec.ts b/src/utils/__tests__/export.spec.ts index 35b3067a03..97c89b2e0f 100644 --- a/src/utils/__tests__/export.spec.ts +++ b/src/utils/__tests__/export.spec.ts @@ -29,7 +29,7 @@ vi.mock("vscode", () => ({ // `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 } } + 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 } }) @@ -70,14 +70,14 @@ describe("resolveDefaultSaveUri", () => { expect(resolved).toBe(REMEMBERED) expect(mocks.stat).toHaveBeenCalledWith(REMEMBERED_DIR) - expect(mocks.access).toHaveBeenCalledWith(REMEMBERED_DIR, constants.W_OK) + expect(mocks.access).toHaveBeenCalledWith(REMEMBERED_DIR, constants.W_OK | constants.X_OK) }) it("checks write permission instead of existence alone", async () => { await resolveWith(REMEMBERED, { useWorkspace: false }) - expect(mocks.access).toHaveBeenCalledWith(REMEMBERED_DIR, constants.W_OK) - expect(mocks.access).not.toHaveBeenCalledWith(REMEMBERED_DIR, constants.R_OK) + 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 () => { @@ -117,7 +117,7 @@ describe("resolveDefaultSaveUri", () => { 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 + (mode & constants.W_OK) === constants.W_OK ? Promise.reject(Object.assign(new Error("EACCES"), { code: "EACCES" })) : Promise.resolve(), ) @@ -129,7 +129,8 @@ describe("resolveDefaultSaveUri", () => { }) expect(resolved).toBe(REMEMBERED) - expect(mocks.access).toHaveBeenCalledWith(REMEMBERED_DIR, constants.R_OK) + // 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 () => { diff --git a/src/utils/export.ts b/src/utils/export.ts index ab4944862a..60bb424a24 100644 --- a/src/utils/export.ts +++ b/src/utils/export.ts @@ -44,9 +44,11 @@ async function isUsableSaveDirectory(dirPath: string, accessMode: number): Promi if (!stats.isDirectory()) { return false } - // The access mode is the property that matters: a readable-but-read-only volume - // cannot receive an export, while an open dialog only reads from it. - await access(dirPath, accessMode) + // 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 From be8c3739b34db0f24bc107114af511a2e8a39e4f Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:03:47 +0800 Subject: [PATCH 04/17] fix(config): keep host-local save paths out of imported settings Resolves the two CodeRabbit pre-merge check errors on the export unit: - Security Boundaries: `resolveDefaultSaveUri` probes the remembered directory with `stat`/`access` before the dialog is shown, and that directory can arrive from a settings file produced by another machine. `sanitizeGlobalSettings` now drops the four host-local dialog memories (`lastSettingsExportPath`, `lastTaskExportPath`, `lastModeExportPath`, `lastImageSavePath`) on import, so a path a dialog defaults to is always one a user picked on this machine. The drop is silent: every export contains these keys, so warning on each import would report nothing actionable. - Persistence Integrity: when the file is written but the location cannot be remembered, `exportSettings` no longer posts the plain success toast. It reports the partial result (`common:warnings.settings_export_location_not_remembered`, added to all 18 locales) with both the path and the reason, and still logs the error for the extension host logs. Tests: 5 more in `importExport.spec.ts` (host-local drop, provider profile export rejection, global settings rejection, directory creation failure reporting, partial export reporting), plus `locale-bundles.spec.ts` pinning the new key. 15 in `utils/__tests__/export.spec.ts`, 66 in `importExport.spec.ts` (1 pre-existing Windows failure, #2059). 24 hand-written mutants over this delta are killed. Local `eslint --max-warnings=0` over the five touched files reports no problems. --- .../config/__tests__/importExport.spec.ts | 129 +++++++++++++++++- src/core/config/importExport.ts | 32 ++++- src/i18n/__tests__/locale-bundles.spec.ts | 10 +- src/i18n/locales/ca/common.json | 1 + src/i18n/locales/de/common.json | 1 + src/i18n/locales/en/common.json | 1 + src/i18n/locales/es/common.json | 1 + src/i18n/locales/fr/common.json | 1 + src/i18n/locales/hi/common.json | 1 + src/i18n/locales/id/common.json | 1 + src/i18n/locales/it/common.json | 1 + src/i18n/locales/ja/common.json | 1 + src/i18n/locales/ko/common.json | 1 + src/i18n/locales/nl/common.json | 1 + src/i18n/locales/pl/common.json | 1 + src/i18n/locales/pt-BR/common.json | 1 + src/i18n/locales/ru/common.json | 1 + src/i18n/locales/tr/common.json | 1 + src/i18n/locales/vi/common.json | 1 + src/i18n/locales/zh-CN/common.json | 1 + src/i18n/locales/zh-TW/common.json | 1 + 21 files changed, 181 insertions(+), 8 deletions(-) diff --git a/src/core/config/__tests__/importExport.spec.ts b/src/core/config/__tests__/importExport.spec.ts index becc0df6a2..bffe0541b4 100644 --- a/src/core/config/__tests__/importExport.spec.ts +++ b/src/core/config/__tests__/importExport.spec.ts @@ -371,9 +371,54 @@ describe("importExport", () => { ) }) - it("should import settings successfully from a valid file", async () => { + 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") + // Dropped silently: every export contains these keys, so warning on each + // import would report nothing the user can act on. + expect(result.warnings ?? []).not.toEqual(expect.arrayContaining([expect.stringContaining("last")])) + }) + + it("should import settings successfully from a valid file", async () => { const mockFileContent = JSON.stringify({ providerProfiles: { currentApiConfigName: "test", @@ -1811,6 +1856,67 @@ 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("should persist and report the location that received the exported file", async () => { @@ -1850,7 +1956,7 @@ describe("importExport", () => { ) }) - it("should still confirm the export when the location cannot be remembered", async () => { + 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", @@ -1862,7 +1968,8 @@ describe("importExport", () => { }) mockContextProxy.export.mockResolvedValue({ mode: "code" }) // The file is on disk; only the remembered location fails. That must not - // swallow the confirmation the user just earned. + // swallow the report the user just earned. + const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) mockContextProxy.setValue.mockRejectedValueOnce(new Error("storage unavailable")) await exportSettings({ @@ -1871,9 +1978,21 @@ describe("importExport", () => { }) expect(safeWriteJson).toHaveBeenCalledWith("/usb/zoo-code-settings.json", expect.anything()) - expect(vscode.window.showInformationMessage).toHaveBeenCalledWith( - expect.stringContaining("info.settings_exported"), + // 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 () => { diff --git a/src/core/config/importExport.ts b/src/core/config/importExport.ts index 2e4395ac72..ba63f84ac4 100644 --- a/src/core/config/importExport.ts +++ b/src/core/config/importExport.ts @@ -78,6 +78,21 @@ 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 hostLocalPathKeys = new Set([ + "lastSettingsExportPath", + "lastTaskExportPath", + "lastModeExportPath", + "lastImageSavePath", +]) + function sanitizeGlobalSettings(rawGlobalSettings: unknown): { sanitizedGlobalSettings: GlobalSettings warnings: string[] @@ -105,6 +120,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) { @@ -362,12 +383,19 @@ export const exportSettings = async ({ providerSettingsManager, contextProxy }: // 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 confirmation must still appear and the rejection must not escape into the - // unawaited message handler. + // 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 aebd99a5d1..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; info: Record }> = { +const bundles: Record< + string, + { errors: Record; info: Record; warnings: Record } +> = { ca, de, en, @@ -68,5 +71,10 @@ describe("settings export locale bundles", () => { 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 ce57e2fb01..ee47926780 100644 --- a/src/i18n/locales/ca/common.json +++ b/src/i18n/locales/ca/common.json @@ -128,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.", diff --git a/src/i18n/locales/de/common.json b/src/i18n/locales/de/common.json index 5bdcab6fb8..5d1878c968 100644 --- a/src/i18n/locales/de/common.json +++ b/src/i18n/locales/de/common.json @@ -124,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.", diff --git a/src/i18n/locales/en/common.json b/src/i18n/locales/en/common.json index b70fda60ce..edc1f27d4a 100644 --- a/src/i18n/locales/en/common.json +++ b/src/i18n/locales/en/common.json @@ -124,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.", diff --git a/src/i18n/locales/es/common.json b/src/i18n/locales/es/common.json index 836cd55069..dc61ecf314 100644 --- a/src/i18n/locales/es/common.json +++ b/src/i18n/locales/es/common.json @@ -124,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.", diff --git a/src/i18n/locales/fr/common.json b/src/i18n/locales/fr/common.json index f58ae2f30d..01d871bf87 100644 --- a/src/i18n/locales/fr/common.json +++ b/src/i18n/locales/fr/common.json @@ -124,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.", diff --git a/src/i18n/locales/hi/common.json b/src/i18n/locales/hi/common.json index e4bfdc45a8..38c8938587 100644 --- a/src/i18n/locales/hi/common.json +++ b/src/i18n/locales/hi/common.json @@ -124,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 में आयात किया जा चुका है।", diff --git a/src/i18n/locales/id/common.json b/src/i18n/locales/id/common.json index e6f3f3ded5..6771e019ab 100644 --- a/src/i18n/locales/id/common.json +++ b/src/i18n/locales/id/common.json @@ -124,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.", diff --git a/src/i18n/locales/it/common.json b/src/i18n/locales/it/common.json index b290c51c50..99e3aeebaf 100644 --- a/src/i18n/locales/it/common.json +++ b/src/i18n/locales/it/common.json @@ -124,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.", diff --git a/src/i18n/locales/ja/common.json b/src/i18n/locales/ja/common.json index f0973dd06b..dc612a8a9a 100644 --- a/src/i18n/locales/ja/common.json +++ b/src/i18n/locales/ja/common.json @@ -124,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にインポート済みです。", diff --git a/src/i18n/locales/ko/common.json b/src/i18n/locales/ko/common.json index 568b865a36..3bf22bdbad 100644 --- a/src/i18n/locales/ko/common.json +++ b/src/i18n/locales/ko/common.json @@ -124,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로 가져와졌습니다.", diff --git a/src/i18n/locales/nl/common.json b/src/i18n/locales/nl/common.json index fcd0317526..4aad7790b6 100644 --- a/src/i18n/locales/nl/common.json +++ b/src/i18n/locales/nl/common.json @@ -124,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.", diff --git a/src/i18n/locales/pl/common.json b/src/i18n/locales/pl/common.json index b022d5cb23..e70eeff192 100644 --- a/src/i18n/locales/pl/common.json +++ b/src/i18n/locales/pl/common.json @@ -124,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.", diff --git a/src/i18n/locales/pt-BR/common.json b/src/i18n/locales/pt-BR/common.json index 83d9d293e6..164733d987 100644 --- a/src/i18n/locales/pt-BR/common.json +++ b/src/i18n/locales/pt-BR/common.json @@ -128,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.", diff --git a/src/i18n/locales/ru/common.json b/src/i18n/locales/ru/common.json index 29124997f1..46a74af83e 100644 --- a/src/i18n/locales/ru/common.json +++ b/src/i18n/locales/ru/common.json @@ -124,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.", diff --git a/src/i18n/locales/tr/common.json b/src/i18n/locales/tr/common.json index 98d70126f9..9548d9fb9d 100644 --- a/src/i18n/locales/tr/common.json +++ b/src/i18n/locales/tr/common.json @@ -124,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ış.", diff --git a/src/i18n/locales/vi/common.json b/src/i18n/locales/vi/common.json index b0f51bb214..5207224db4 100644 --- a/src/i18n/locales/vi/common.json +++ b/src/i18n/locales/vi/common.json @@ -124,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.", diff --git a/src/i18n/locales/zh-CN/common.json b/src/i18n/locales/zh-CN/common.json index faaeda182e..3d1717f23d 100644 --- a/src/i18n/locales/zh-CN/common.json +++ b/src/i18n/locales/zh-CN/common.json @@ -129,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。", diff --git a/src/i18n/locales/zh-TW/common.json b/src/i18n/locales/zh-TW/common.json index 6e14869d05..ea9ae9f69c 100644 --- a/src/i18n/locales/zh-TW/common.json +++ b/src/i18n/locales/zh-TW/common.json @@ -124,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。", From bcd082270a962f2befca23edcaea6f1f57fe60fc Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:28:07 +0800 Subject: [PATCH 05/17] test(config): assert the silent drop really reports nothing CodeRabbit: the host-local import test only rejected warnings containing "last", which any unrelated warning would pass. The drop is documented as silent, so the test now asserts the whole warning list: `importSettings` returns no warnings at all for a settings file that carries the four dialog memories. 65 passed / 1 pre-existing failure (#2059) in `importExport.spec.ts`; `eslint --max-warnings=0` on the file exits 0. --- src/core/config/__tests__/importExport.spec.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/core/config/__tests__/importExport.spec.ts b/src/core/config/__tests__/importExport.spec.ts index bffe0541b4..b041f4ac62 100644 --- a/src/core/config/__tests__/importExport.spec.ts +++ b/src/core/config/__tests__/importExport.spec.ts @@ -414,8 +414,9 @@ describe("importExport", () => { expect(result.globalSettings).not.toHaveProperty("lastModeExportPath") expect(result.globalSettings).not.toHaveProperty("lastImageSavePath") // Dropped silently: every export contains these keys, so warning on each - // import would report nothing the user can act on. - expect(result.warnings ?? []).not.toEqual(expect.arrayContaining([expect.stringContaining("last")])) + // 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 () => { From 653661763ac2b0c921332bc23bd08cfa39b1c8c2 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:05:41 +0800 Subject: [PATCH 06/17] fix(config): roll the settings cache back when a state write is rejected Third CodeRabbit round (Persistence Integrity). `ContextProxy.updateGlobalState` wrote the key into `stateCache` before `globalState.update` settled, so a rejected write left an in-memory value that disk never received: readers, `export()`/`import()` and the next restart all report a setting that does not exist. The cache now rolls the key back to the value that is actually on disk and the rejection still reaches the caller; the success path is unchanged, and `Memento.update` is normalized first because it is only specified as a `Thenable` (removing that normalization breaks 46 tests that stub it as a plain object). This is the failure `exportSettings` can now report: it confirms the file it wrote and says the location could not be remembered. Without the rollback, the next dialog would still default to that unremembered location for the rest of the run. Tests: 2 new in `core/config/__tests__/ContextProxy.spec.ts` (38/38). Six of seven hand-written mutants over the new lines are killed (drop the rollback, roll back to undefined, do not capture the previous value, swallow the rejection, skip the cache write on success, drop the normalization); the seventh re-assigns the same value on success and is equivalent. Full unit suite before and after: 58 failed / 11996 passed before, 58 failed / 11998 passed after - the same 15 pre-existing Windows failures (#2059 among them), no new ones. `eslint --max-warnings=0` exits 0 with unchanged suppression counts for both files. --- src/core/config/ContextProxy.ts | 15 +++++++++++- .../config/__tests__/ContextProxy.spec.ts | 24 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/core/config/ContextProxy.ts b/src/core/config/ContextProxy.ts index 1250a7baca..e873dec283 100644 --- a/src/core/config/ContextProxy.ts +++ b/src/core/config/ContextProxy.ts @@ -365,8 +365,21 @@ export class ContextProxy { return this.originalContext.globalState.update(key, value) } + const previousValue = this.stateCache[key] this.stateCache[key] = value - return this.originalContext.globalState.update(key, value) + + // The cache is globalState's in-memory mirror, so a value that never reached + // disk must not stay in the mirror: readers would report a setting that the + // next restart will not reproduce. Roll the key back to what is on disk and + // let the rejection reach the caller. Memento.update is only specified as a + // Thenable, so its result is normalized before a rejection handler is hung + // off it. + const update = Promise.resolve(this.originalContext.globalState.update(key, value)) + + return update.then(undefined, (error) => { + this.stateCache[key] = previousValue + throw error + }) } private getAllGlobalState(): GlobalState { diff --git a/src/core/config/__tests__/ContextProxy.spec.ts b/src/core/config/__tests__/ContextProxy.spec.ts index b4d3b1b8aa..4d95a9d042 100644 --- a/src/core/config/__tests__/ContextProxy.spec.ts +++ b/src/core/config/__tests__/ContextProxy.spec.ts @@ -194,6 +194,30 @@ describe("ContextProxy", () => { expect(storedValue).toBe(historyItems) expect(mockGlobalState.get).toHaveBeenCalledWith("taskHistory") }) + + it("keeps the value that is actually on disk when an update is rejected", async () => { + await proxy.updateGlobalState("apiProvider", "deepseek") + mockGlobalState.update.mockRejectedValueOnce(new Error("globalState write failed")) + + await expect(proxy.updateGlobalState("apiProvider", "openai")).rejects.toThrow("globalState write failed") + + // The rejected value never reached disk, so it must not live in the cache; + // the value that is on disk must survive the failed write next to it. + expect(proxy.getGlobalState("apiProvider")).toBe("deepseek") + }) + + it("leaves a key unset when its first update is rejected", async () => { + mockGlobalState.update.mockRejectedValueOnce(new Error("globalState write failed")) + + await expect(proxy.setValue("lastSettingsExportPath", "/usb/zoo-code-settings.json")).rejects.toThrow( + "globalState write failed", + ) + + // Nothing was remembered: the export dialog default stays where the user + // last left it instead of pointing at a location that was never stored. + expect(proxy.getValue("lastSettingsExportPath")).toBeUndefined() + expect(mockGlobalState.update).toHaveBeenCalledWith("lastSettingsExportPath", "/usb/zoo-code-settings.json") + }) }) describe("getSecret", () => { From 36d0b6059e4b8a4d92007a61defbd70a52790d49 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:34:59 +0800 Subject: [PATCH 07/17] test(config): pin the profile-less export as a no-op Regression Evidence (the last CodeRabbit pre-merge check on `653661763`, warning level). `exportSettings` returns without writing when `providerSettingsManager.export()` resolves to `undefined`: `importSettings` cannot consume a file with no provider profiles, so a half-empty export would be worse than none. The behaviour stays as it is; the test pins it so the silent no-op is a decision rather than an accident - no `fs.mkdir`, no `safeWriteJson`, no toast, and no remembered location. The check asked for `contextProxy.export` to be asserted as not called, but the guard sits after both collect calls (`importExport.ts:355-364`), so the test asserts it *is* called and that the write and the reporting do not happen. Negative control: removing the guard, weakening it to a `null` check, or letting it report success each fail exactly this test (67 tests, the only other failure being the pre-existing prompt-cache TTL one, #2059). --- .../config/__tests__/importExport.spec.ts | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/core/config/__tests__/importExport.spec.ts b/src/core/config/__tests__/importExport.spec.ts index b041f4ac62..ea07c316f7 100644 --- a/src/core/config/__tests__/importExport.spec.ts +++ b/src/core/config/__tests__/importExport.spec.ts @@ -1920,6 +1920,31 @@ describe("importExport", () => { 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", + }) + mockProviderSettingsManager.export.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({ From faa9c0b790062a18f28429cca3257b727af39966 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:51:49 +0800 Subject: [PATCH 08/17] test(config): type the profile-less export mock so check-types passes `compile` was red on `36d0b6059`: `core/config/__tests__/importExport.spec.ts(1927,57): error TS2345` - `mockProviderSettingsManager` is `vi.mocked`, and `ProviderSettingsManager.export()` is typed as returning parsed profiles or throwing (`src/core/config/ProviderSettingsManager.ts:577-637`), so `mockResolvedValue(undefined)` is not assignable. The mock is loosened with a single `as Mock` assertion, the way this file already loosens the dialog mocks, with a comment saying why: the profile-less branch in `exportSettings` is defensive rather than reachable, and it is that branch under test. Locally reproduced and verified: `pnpm --dir src run check-types` gave 115 errors with the new line (114 pre-existing + this one) and 114 after, none in any file this PR touches. `importExport.spec.ts` stays 66 passed / 1 pre-existing failure (#2059); Prettier clean; `eslint --max-warnings=0` exits 0. --- src/core/config/__tests__/importExport.spec.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/core/config/__tests__/importExport.spec.ts b/src/core/config/__tests__/importExport.spec.ts index ea07c316f7..84f968e4a3 100644 --- a/src/core/config/__tests__/importExport.spec.ts +++ b/src/core/config/__tests__/importExport.spec.ts @@ -1924,7 +1924,11 @@ describe("importExport", () => { ;(vscode.window.showSaveDialog as Mock).mockResolvedValue({ fsPath: "/mock/path/zoo-code-settings.json", }) - mockProviderSettingsManager.export.mockResolvedValue(undefined) + // `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({ From 9b089a217fcbd466e7564a70c05ca5b6acd4051e Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:15:11 +0800 Subject: [PATCH 09/17] fix(config): keep the settings cache honest across batched same-key writes CodeRabbit review comment 4452829726 (Data Integrity & Integration, Minor). The rollback added in 653661763 captured `previousValue` per call, but `Memento.update` batches: two writes to the same key issued before the scheduled flush share one pending promise, so a rejected batch rejects both callers and the second one rolls the key back to the first one's unflushed value - a value storage never held. Writes are now numbered per key and the newest value that actually persisted is remembered: only the newest write may touch the cache, and it restores what is persisted. `resetAllState` clears the bookkeeping along with the cache so it cannot remember values storage dropped. Tests: 4 new in `core/config/__tests__/ContextProxy.spec.ts` (42/42) - a batched rejection restores the startup value, a superseded write that fails late leaves the newer persisted value alone, an older failure cannot roll back a write that is still in flight, and the first write of a key read from storage at startup rolls back to it. Evidence: eight hand-written mutants are killed (drop the sequence guard, stop advancing the persisted value on success, stop tracking the sequence, seed the persisted value from the incoming value, never seed it, swallow the rejection, skip the cache write, restore undefined). Full unit suite: 58 failed / 12003 passed before and after this commit, the same 15 pre-existing Windows failures, no new ones (`core/webview/__tests__/ClineProvider .spec.ts` is 2 failed / 314 passed both with and without this change). `pnpm --dir src run check-types`: 114 pre-existing errors, none in a file this PR touches. ESLint exits 0 with `no-explicit-any` counts unchanged (1 and 5). --- src/core/config/ContextProxy.ts | 41 ++++++++-- .../config/__tests__/ContextProxy.spec.ts | 75 +++++++++++++++++++ 2 files changed, 108 insertions(+), 8 deletions(-) diff --git a/src/core/config/ContextProxy.ts b/src/core/config/ContextProxy.ts index e873dec283..a7ade42810 100644 --- a/src/core/config/ContextProxy.ts +++ b/src/core/config/ContextProxy.ts @@ -43,6 +43,13 @@ export class ContextProxy { private stateCache: GlobalState private secretCache: SecretState + // `Memento.update` batches: two writes to the same key issued before the scheduled + // flush share one pending promise, so a rejected batch rejects both callers at once. + // Each write is numbered per key and the newest value that actually persisted is + // remembered, so only the newest write may roll the cache back, and it rolls back + // to something that is really on disk. + private readonly writeSequences = new Map() + private readonly persistedValues = new Map() private _isInitialized = false constructor(context: vscode.ExtensionContext) { @@ -365,21 +372,35 @@ export class ContextProxy { return this.originalContext.globalState.update(key, value) } - const previousValue = this.stateCache[key] - this.stateCache[key] = value + const sequence = (this.writeSequences.get(key) ?? 0) + 1 + this.writeSequences.set(key, sequence) + if (!this.persistedValues.has(key)) { + this.persistedValues.set(key, this.stateCache[key]) + } // The cache is globalState's in-memory mirror, so a value that never reached // disk must not stay in the mirror: readers would report a setting that the // next restart will not reproduce. Roll the key back to what is on disk and // let the rejection reach the caller. Memento.update is only specified as a - // Thenable, so its result is normalized before a rejection handler is hung - // off it. + // Thenable, so its result is normalized before handlers are hung off it. + this.stateCache[key] = value const update = Promise.resolve(this.originalContext.globalState.update(key, value)) - return update.then(undefined, (error) => { - this.stateCache[key] = previousValue - throw error - }) + return update.then( + () => { + this.persistedValues.set(key, value) + }, + (error) => { + // A batch also rejects writes that have since been superseded; only the + // newest write for the key may touch the cache, and only back to a value + // that persisted. The map spans every key, so its value is the union over + // all keys - this write's key is the one being restored. + if (this.writeSequences.get(key) === sequence) { + this.stateCache[key] = this.persistedValues.get(key) as GlobalState[K] + } + throw error + }, + ) } private getAllGlobalState(): GlobalState { @@ -603,6 +624,10 @@ export class ContextProxy { // Clear in-memory caches this.stateCache = {} this.secretCache = {} + // Nothing is persisted after a reset, so the write bookkeeping must not + // remember values that storage no longer holds. + this.writeSequences.clear() + this.persistedValues.clear() await Promise.all([ ...GLOBAL_STATE_KEYS.map((key) => this.originalContext.globalState.update(key, undefined)), diff --git a/src/core/config/__tests__/ContextProxy.spec.ts b/src/core/config/__tests__/ContextProxy.spec.ts index 4d95a9d042..1c9501eb85 100644 --- a/src/core/config/__tests__/ContextProxy.spec.ts +++ b/src/core/config/__tests__/ContextProxy.spec.ts @@ -195,6 +195,20 @@ describe("ContextProxy", () => { expect(mockGlobalState.get).toHaveBeenCalledWith("taskHistory") }) + it("restores the value read from storage at startup when the first write is rejected", async () => { + // The usual shape in the field: storage already holds a value (read into the + // cache at startup) and the session's first write of that key fails. + mockGlobalState.get.mockImplementation((key: string) => (key === "apiProvider" ? "openrouter" : undefined)) + proxy = new ContextProxy(mockContext) + await proxy.initialize() + + mockGlobalState.update.mockRejectedValueOnce(new Error("globalState write failed")) + + await expect(proxy.updateGlobalState("apiProvider", "openai")).rejects.toThrow("globalState write failed") + + expect(proxy.getGlobalState("apiProvider")).toBe("openrouter") + }) + it("keeps the value that is actually on disk when an update is rejected", async () => { await proxy.updateGlobalState("apiProvider", "deepseek") mockGlobalState.update.mockRejectedValueOnce(new Error("globalState write failed")) @@ -218,6 +232,67 @@ describe("ContextProxy", () => { expect(proxy.getValue("lastSettingsExportPath")).toBeUndefined() expect(mockGlobalState.update).toHaveBeenCalledWith("lastSettingsExportPath", "/usb/zoo-code-settings.json") }) + + it("restores the persisted value when same-key writes share a rejected batch", async () => { + await proxy.updateGlobalState("apiProvider", "deepseek") + + // Memento batches writes to one key: both calls receive the same pending + // promise, so the second call captures the first call's unflushed value as its + // "previous" one - rolling back to that would report a value that never existed + // on disk. + const sharedBatch = Promise.reject(new Error("globalState write failed")) + mockGlobalState.update.mockReturnValue(sharedBatch) + + const first = proxy.updateGlobalState("apiProvider", "openai") + const second = proxy.updateGlobalState("apiProvider", "anthropic") + + await expect(first).rejects.toThrow("globalState write failed") + await expect(second).rejects.toThrow("globalState write failed") + + // Only the newest write may touch the cache, and it rolls back to what is + // actually persisted. + expect(proxy.getGlobalState("apiProvider")).toBe("deepseek") + }) + + it("keeps a newer persisted value when an older write for the same key rejects", async () => { + let rejectFirst: (error: Error) => void = () => {} + mockGlobalState.update.mockImplementationOnce( + () => new Promise((_resolve, reject) => (rejectFirst = reject)), + ) + const first = proxy.updateGlobalState("apiProvider", "openai") + + mockGlobalState.update.mockResolvedValueOnce(undefined) + await proxy.updateGlobalState("apiProvider", "anthropic") + + rejectFirst(new Error("globalState write failed")) + await expect(first).rejects.toThrow("globalState write failed") + + // The late rejection belongs to a superseded write; the value that persisted + // after it stays in the cache. + expect(proxy.getGlobalState("apiProvider")).toBe("anthropic") + }) + + it("does not roll back a pending write when an older one for the same key fails", async () => { + let rejectFirst: (error: Error) => void = () => {} + let resolveSecond: (value: undefined) => void = () => {} + mockGlobalState.update.mockImplementationOnce( + () => new Promise((_resolve, reject) => (rejectFirst = reject)), + ) + const first = proxy.updateGlobalState("apiProvider", "openai") + + mockGlobalState.update.mockImplementationOnce(() => new Promise((resolve) => (resolveSecond = resolve))) + const second = proxy.updateGlobalState("apiProvider", "anthropic") + + // The older write fails while the newer one is still in flight, so the only + // value it could roll back to is one storage never held. + rejectFirst(new Error("globalState write failed")) + await expect(first).rejects.toThrow("globalState write failed") + + resolveSecond(undefined) + await second + + expect(proxy.getGlobalState("apiProvider")).toBe("anthropic") + }) }) describe("getSecret", () => { From 8a491fc53db6e513616ac63da80649d1f1f85f3a Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:42:21 +0800 Subject: [PATCH 10/17] test(config): read the cache while the superseded write is still in flight CodeRabbit review comment 4453429221 (Functional Correctness, Minor): the pending-write test read the cache only after the newer write settled, so an implementation that clobbered the key on the older rejection and wrote it again on success would still pass. The cache is now read between the two settlements, which is the moment the per-key sequence guard is the only thing protecting it. That gap is real: the equivalent mutant (restore unconditionally and re-write the cache in the success handler) survived the earlier version of this test and is now killed by this assertion alone. The eight mutants over the `ContextProxy` lines are still killed, `ContextProxy.spec.ts` stays 42/42, and Prettier reports the file unchanged. --- src/core/config/__tests__/ContextProxy.spec.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/core/config/__tests__/ContextProxy.spec.ts b/src/core/config/__tests__/ContextProxy.spec.ts index 1c9501eb85..03aaa4da18 100644 --- a/src/core/config/__tests__/ContextProxy.spec.ts +++ b/src/core/config/__tests__/ContextProxy.spec.ts @@ -288,6 +288,11 @@ describe("ContextProxy", () => { rejectFirst(new Error("globalState write failed")) await expect(first).rejects.toThrow("globalState write failed") + // Read the cache while the newer write is still in flight. Reading only after + // it settles would also pass an implementation that clobbered the key here and + // wrote it again on success. + expect(proxy.getGlobalState("apiProvider")).toBe("anthropic") + resolveSecond(undefined) await second From 35a8bf339b48a06472a6c006efea09b50b4af942 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 3 Nov 2026 19:10:04 +0800 Subject: [PATCH 11/17] fix(config): reconcile the settings cache when same-key writes settle out of order CodeRabbit pre-merge check "Persistence Integrity" at 8a491fc53: with the rollback added in 9b089a217, if write A starts, write B for the same key starts, B rejects first and A lands afterwards, B rolled the key back to the old value and A's success never repaired the mirror - the cache reported a value storage had overwritten. The per-key write numbering is replaced by an in-flight count. While a write is in flight the cache optimistically holds the requested value (the behaviour callers already depend on). Once the last write standing for a key settles, the cache is reconciled with storage: a landing sets it to the value that landed, a rejection falls back to the newest value that actually persisted. A settled write may not touch the cache while a newer write for the same key is still running. persistedValues stays the rollback target, so no write needs to know whether it was the newest one issued. Tests (44/44 in ContextProxy.spec.ts): - repairs the cache when an older write lands after a newer one failed: getGlobalState and getValues - the mirror export() and getState() read from - both report the landed value. - forgets what it had persisted, so a write rejected after resetAllState leaves the key unset (pre-merge check "Regression Evidence"), including that the reset wrote the key to storage. All 12 hand-written mutants over the new lines are killed: success writes the mirror unconditionally, success never writes it, failure restores unconditionally, failure never restores, persisted value not advanced on success, never seeded, seeded from the incoming value, in-flight count never decremented, last-standing predicate inverted, rejection swallowed, optimistic cache write removed, reset keeps the persisted value. Regressions: full unit suite 58 failed / 12005 passed before and after this commit (the same 15 pre-existing Windows failures). check-types: 114 pre-existing errors, none in a touched file. eslint --max-warnings=0 exits 0 and eslint-suppressions.json is untouched. --- src/core/config/ContextProxy.ts | 58 +++++++++++++------ .../config/__tests__/ContextProxy.spec.ts | 50 ++++++++++++++++ 2 files changed, 90 insertions(+), 18 deletions(-) diff --git a/src/core/config/ContextProxy.ts b/src/core/config/ContextProxy.ts index a7ade42810..b0401e1d06 100644 --- a/src/core/config/ContextProxy.ts +++ b/src/core/config/ContextProxy.ts @@ -43,12 +43,14 @@ export class ContextProxy { private stateCache: GlobalState private secretCache: SecretState - // `Memento.update` batches: two writes to the same key issued before the scheduled - // flush share one pending promise, so a rejected batch rejects both callers at once. - // Each write is numbered per key and the newest value that actually persisted is - // remembered, so only the newest write may roll the cache back, and it rolls back - // to something that is really on disk. - private readonly writeSequences = new Map() + // Writes to one key can settle out of order, and `Memento.update` batches: writes + // issued before a scheduled flush share one pending promise, so a rejected batch + // rejects every caller in that batch at once. Per key this tracks how many writes + // are still in flight and the newest value that actually persisted. While a write + // is in flight the cache optimistically holds the value that was asked for; once + // nothing is in flight the cache must equal what storage holds - which is the last + // write that landed, not necessarily the last one issued. + private readonly outstandingWrites = new Map() private readonly persistedValues = new Map() private _isInitialized = false @@ -372,30 +374,50 @@ export class ContextProxy { return this.originalContext.globalState.update(key, value) } - const sequence = (this.writeSequences.get(key) ?? 0) + 1 - this.writeSequences.set(key, sequence) + this.outstandingWrites.set(key, (this.outstandingWrites.get(key) ?? 0) + 1) if (!this.persistedValues.has(key)) { + // First write of this key in the session: what the cache holds now came from + // storage, so it is the value a rejection has to fall back to. this.persistedValues.set(key, this.stateCache[key]) } // The cache is globalState's in-memory mirror, so a value that never reached - // disk must not stay in the mirror: readers would report a setting that the - // next restart will not reproduce. Roll the key back to what is on disk and - // let the rejection reach the caller. Memento.update is only specified as a - // Thenable, so its result is normalized before handlers are hung off it. + // disk must not stay in the mirror once the write is settled: readers would + // report a setting that the next restart will not reproduce. Memento.update is + // only specified as a Thenable, so its result is normalized before handlers are + // hung off it. this.stateCache[key] = value const update = Promise.resolve(this.originalContext.globalState.update(key, value)) + // Whether this write is the last one still in flight for the key. Writes for the + // same key settle independently, so only the last one standing may decide what + // the cache holds; the others leave it to the newer write that is still running. + const isLastWriteStanding = () => { + const remaining = (this.outstandingWrites.get(key) ?? 1) - 1 + if (remaining > 0) { + this.outstandingWrites.set(key, remaining) + } else { + this.outstandingWrites.delete(key) + } + return remaining === 0 + } + return update.then( () => { this.persistedValues.set(key, value) + + // Storage holds this value now. When a newer write for the same key has + // already failed, this landing is what storage actually holds, so the + // mirror has to follow it instead of keeping the failed write's value. + if (isLastWriteStanding()) { + this.stateCache[key] = value + } }, (error) => { - // A batch also rejects writes that have since been superseded; only the - // newest write for the key may touch the cache, and only back to a value - // that persisted. The map spans every key, so its value is the union over - // all keys - this write's key is the one being restored. - if (this.writeSequences.get(key) === sequence) { + // Fall back to the newest value that actually persisted. The map spans + // every key, so its value is the union over all keys - this write's key is + // the one being restored. + if (isLastWriteStanding()) { this.stateCache[key] = this.persistedValues.get(key) as GlobalState[K] } throw error @@ -626,7 +648,7 @@ export class ContextProxy { this.secretCache = {} // Nothing is persisted after a reset, so the write bookkeeping must not // remember values that storage no longer holds. - this.writeSequences.clear() + this.outstandingWrites.clear() this.persistedValues.clear() await Promise.all([ diff --git a/src/core/config/__tests__/ContextProxy.spec.ts b/src/core/config/__tests__/ContextProxy.spec.ts index 03aaa4da18..cf067c01d9 100644 --- a/src/core/config/__tests__/ContextProxy.spec.ts +++ b/src/core/config/__tests__/ContextProxy.spec.ts @@ -298,6 +298,36 @@ describe("ContextProxy", () => { expect(proxy.getGlobalState("apiProvider")).toBe("anthropic") }) + + it("repairs the cache when an older write lands after a newer one failed", async () => { + await proxy.updateGlobalState("apiProvider", "deepseek") + + let settleFirst: (value: undefined) => void = () => {} + let failSecond: (error: Error) => void = () => {} + mockGlobalState.update.mockImplementationOnce(() => new Promise((resolve) => (settleFirst = resolve))) + const first = proxy.updateGlobalState("apiProvider", "openai") + + mockGlobalState.update.mockImplementationOnce( + () => new Promise((_resolve, reject) => (failSecond = reject)), + ) + const second = proxy.updateGlobalState("apiProvider", "anthropic") + + // The newer write fails while the older one is still in flight, so for a moment + // the cache holds only the failed write's value. + failSecond(new Error("globalState write failed")) + await expect(second).rejects.toThrow("globalState write failed") + + // The older write lands afterwards, so it is what storage holds and what the + // cache has to report once nothing is in flight. + settleFirst(undefined) + await first + + expect(proxy.getGlobalState("apiProvider")).toBe("openai") + // `getValues()` is the mirror `export()` and `getState()` read from; + // `export()` itself runs it through `globalSettingsExportSchema`, which + // deliberately leaves provider settings such as `apiProvider` out. + expect(proxy.getValues().apiProvider).toBe("openai") + }) }) describe("getSecret", () => { @@ -580,6 +610,26 @@ describe("ContextProxy", () => { // Should reinitialize caches expect(initializeSpy).toHaveBeenCalledTimes(1) }) + + it("forgets what it had persisted, so a write rejected after a reset leaves the key unset", async () => { + await proxy.updateGlobalState("lastSettingsExportPath", "/usb/zoo-code-settings.json") + expect(proxy.getGlobalState("lastSettingsExportPath")).toBe("/usb/zoo-code-settings.json") + + await proxy.resetAllState() + + // The reset wrote every key, this one included, and cleared the write bookkeeping + // with the caches, so a rejection afterwards has no pre-reset value to fall back to. + expect(mockGlobalState.update).toHaveBeenCalledWith("lastSettingsExportPath", undefined) + expect(proxy.getGlobalState("lastSettingsExportPath")).toBeUndefined() + + mockGlobalState.update.mockRejectedValueOnce(new Error("globalState write failed")) + + await expect(proxy.updateGlobalState("lastSettingsExportPath", "/c/other.json")).rejects.toThrow( + "globalState write failed", + ) + + expect(proxy.getGlobalState("lastSettingsExportPath")).toBeUndefined() + }) }) describe("invalid apiProvider migration", () => { From ec8850bc68f9708d9361e63e23074c961cb91e1c Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 3 Nov 2026 19:34:53 +0800 Subject: [PATCH 12/17] fix(config): settle same-key writes against the state they were issued against CodeRabbit review comments 4454026019 (Functional Correctness, Minor) and 4454026031 (Data Integrity & Integration, Minor) against 35a8bf339. Both held. 1. A rejection now rolls the mirror back whenever the rejecting write is the newest one issued for the key, not only when it is the last write still running. When the newer of two same-key writes fails while the older one is still in flight, readers no longer report the rejected value for the duration of the older write. The landing repair from 35a8bf339 is unchanged: a landing may only write the mirror once nothing newer is in flight, so an older write that lands after a newer one failed still corrects it. 2. resetAllState now bumps a generation counter along with clearing the maps. A write issued before the reset that settles afterwards belongs to storage state that no longer exists: its success handler used to put the pre-reset value back into persistedValues (which initialize() does not clear), and a later rejected write would restore that value into stateCache. Settlements from a stale generation are ignored while the rejection is still reported to the caller. Tests (46/46 in ContextProxy.spec.ts): the out-of-order landing test now also asserts that the mirror reports the persisted value while the older write is in flight; a pre-reset write that lands after the reset leaves the key unset and does not seed a later rollback; a rejected pre-reset write does not roll back a write issued after the reset. Mutation sweep over the new lines: 14 of 15 hand-written mutants killed (success may land after a reset, failure may roll back across a reset, any rejection rolls the mirror back, landing never repairs the mirror, persisted value not advanced / never seeded / seeded from the incoming value, in-flight count never decremented, rejection leaves the write in flight, reset keeps the generation, rejection swallowed, no optimistic cache write). One survives and is disclosed rather than papered over: leaving writeSequences un-cleared on reset is not observable because the generation guard already ignores that write - it is redundant protection, and the sweep says so. Regressions: full unit suite 58 failed / 12007 passed (was 12005 before this commit), the same 15 pre-existing Windows failures. check-types: 114 pre-existing errors, none in a touched file. eslint --max-warnings=0 exits 0; eslint-suppressions.json untouched. --- src/core/config/ContextProxy.ts | 59 +++++++++++++------ .../config/__tests__/ContextProxy.spec.ts | 55 ++++++++++++++++- 2 files changed, 94 insertions(+), 20 deletions(-) diff --git a/src/core/config/ContextProxy.ts b/src/core/config/ContextProxy.ts index b0401e1d06..66b1b7f047 100644 --- a/src/core/config/ContextProxy.ts +++ b/src/core/config/ContextProxy.ts @@ -45,13 +45,17 @@ export class ContextProxy { private secretCache: SecretState // Writes to one key can settle out of order, and `Memento.update` batches: writes // issued before a scheduled flush share one pending promise, so a rejected batch - // rejects every caller in that batch at once. Per key this tracks how many writes - // are still in flight and the newest value that actually persisted. While a write - // is in flight the cache optimistically holds the value that was asked for; once - // nothing is in flight the cache must equal what storage holds - which is the last - // write that landed, not necessarily the last one issued. + // rejects every caller in that batch at once. Per key this tracks the number given + // to each write, how many writes are still in flight, and the newest value that + // actually persisted. While a write is in flight the cache optimistically holds the + // value that was asked for; a settled write may only correct the mirror when it is + // the newest one issued (a rejection) or the last one still running (a landing). + // `resetAllState` bumps the generation so a write issued before it cannot repopulate + // this bookkeeping when it settles afterwards. + private readonly writeSequences = new Map() private readonly outstandingWrites = new Map() private readonly persistedValues = new Map() + private stateGeneration = 0 private _isInitialized = false constructor(context: vscode.ExtensionContext) { @@ -374,9 +378,12 @@ export class ContextProxy { return this.originalContext.globalState.update(key, value) } + const generation = this.stateGeneration + const sequence = (this.writeSequences.get(key) ?? 0) + 1 + this.writeSequences.set(key, sequence) this.outstandingWrites.set(key, (this.outstandingWrites.get(key) ?? 0) + 1) if (!this.persistedValues.has(key)) { - // First write of this key in the session: what the cache holds now came from + // First write of this key in the generation: what the cache holds now came from // storage, so it is the value a rejection has to fall back to. this.persistedValues.set(key, this.stateCache[key]) } @@ -389,10 +396,10 @@ export class ContextProxy { this.stateCache[key] = value const update = Promise.resolve(this.originalContext.globalState.update(key, value)) - // Whether this write is the last one still in flight for the key. Writes for the - // same key settle independently, so only the last one standing may decide what - // the cache holds; the others leave it to the newer write that is still running. - const isLastWriteStanding = () => { + // Retires this write and reports whether it was the last one still in flight for + // the key. Writes for the same key settle independently, so a landing may only + // decide what the mirror holds once nothing newer is still running. + const retireWrite = () => { const remaining = (this.outstandingWrites.get(key) ?? 1) - 1 if (remaining > 0) { this.outstandingWrites.set(key, remaining) @@ -402,22 +409,37 @@ export class ContextProxy { return remaining === 0 } + // Whether the state was reset while this write was in flight. Such a write + // belongs to storage state that no longer exists: it must not put its value + // back into the bookkeeping or the mirror. + const belongsToCurrentState = () => generation === this.stateGeneration + return update.then( () => { + if (!belongsToCurrentState()) { + return + } + this.persistedValues.set(key, value) // Storage holds this value now. When a newer write for the same key has // already failed, this landing is what storage actually holds, so the // mirror has to follow it instead of keeping the failed write's value. - if (isLastWriteStanding()) { + if (retireWrite()) { this.stateCache[key] = value } }, (error) => { - // Fall back to the newest value that actually persisted. The map spans - // every key, so its value is the union over all keys - this write's key is - // the one being restored. - if (isLastWriteStanding()) { + retireWrite() + + // The newest write for the key is the one storage would have ended up with, + // so its rejection is rolled back to the newest value that actually + // persisted, even while an older write for the same key is still running - + // otherwise readers report a value that was rejected. An older rejection + // leaves the mirror to the newer write that is still in flight. + // The map spans every key, so its value is the union over all keys - this + // write's key is the one being restored. + if (belongsToCurrentState() && this.writeSequences.get(key) === sequence) { this.stateCache[key] = this.persistedValues.get(key) as GlobalState[K] } throw error @@ -646,8 +668,11 @@ export class ContextProxy { // Clear in-memory caches this.stateCache = {} this.secretCache = {} - // Nothing is persisted after a reset, so the write bookkeeping must not - // remember values that storage no longer holds. + // Nothing is persisted after a reset, so the write bookkeeping must not remember + // values that storage no longer holds, and a write issued before the reset must + // not repopulate it when it settles afterwards. + this.stateGeneration++ + this.writeSequences.clear() this.outstandingWrites.clear() this.persistedValues.clear() diff --git a/src/core/config/__tests__/ContextProxy.spec.ts b/src/core/config/__tests__/ContextProxy.spec.ts index cf067c01d9..55dfd693c3 100644 --- a/src/core/config/__tests__/ContextProxy.spec.ts +++ b/src/core/config/__tests__/ContextProxy.spec.ts @@ -299,7 +299,7 @@ describe("ContextProxy", () => { expect(proxy.getGlobalState("apiProvider")).toBe("anthropic") }) - it("repairs the cache when an older write lands after a newer one failed", async () => { + it("drops a rejected write from the cache and repairs it when an older one lands", async () => { await proxy.updateGlobalState("apiProvider", "deepseek") let settleFirst: (value: undefined) => void = () => {} @@ -312,10 +312,12 @@ describe("ContextProxy", () => { ) const second = proxy.updateGlobalState("apiProvider", "anthropic") - // The newer write fails while the older one is still in flight, so for a moment - // the cache holds only the failed write's value. + // The newer write is the one storage would have ended up with, so its rejection + // is rolled back to the newest value that persisted even while the older write + // is still running. failSecond(new Error("globalState write failed")) await expect(second).rejects.toThrow("globalState write failed") + expect(proxy.getGlobalState("apiProvider")).toBe("deepseek") // The older write lands afterwards, so it is what storage holds and what the // cache has to report once nothing is in flight. @@ -630,6 +632,53 @@ describe("ContextProxy", () => { expect(proxy.getGlobalState("lastSettingsExportPath")).toBeUndefined() }) + + it("ignores a write issued before the reset when it lands afterwards", async () => { + let settlePending: (value: undefined) => void = () => {} + mockGlobalState.update.mockImplementationOnce(() => new Promise((resolve) => (settlePending = resolve))) + const pending = proxy.updateGlobalState("apiProvider", "openai") + + await proxy.resetAllState() + + settlePending(undefined) + await pending + + // The write belongs to storage state the reset discarded. Landing late must not + // put its value back into the cache or into the rollback record. + expect(proxy.getGlobalState("apiProvider")).toBeUndefined() + + mockGlobalState.update.mockRejectedValueOnce(new Error("globalState write failed")) + await expect(proxy.updateGlobalState("apiProvider", "anthropic")).rejects.toThrow( + "globalState write failed", + ) + + expect(proxy.getGlobalState("apiProvider")).toBeUndefined() + }) + + it("keeps a rejected pre-reset write from rolling back a write issued after the reset", async () => { + let failPending: (error: Error) => void = () => {} + mockGlobalState.update.mockImplementationOnce( + () => new Promise((_resolve, reject) => (failPending = reject)), + ) + const preReset = proxy.updateGlobalState("apiProvider", "openai") + + await proxy.resetAllState() + + // A write issued after the reset reuses this key's first sequence number, so a + // late rejection of the pre-reset write must not be mistaken for it. + let settlePostReset: (value: undefined) => void = () => {} + mockGlobalState.update.mockImplementationOnce(() => new Promise((resolve) => (settlePostReset = resolve))) + const postReset = proxy.updateGlobalState("apiProvider", "anthropic") + + failPending(new Error("globalState write failed")) + await expect(preReset).rejects.toThrow("globalState write failed") + + expect(proxy.getGlobalState("apiProvider")).toBe("anthropic") + + settlePostReset(undefined) + await postReset + expect(proxy.getGlobalState("apiProvider")).toBe("anthropic") + }) }) describe("invalid apiProvider migration", () => { From 4b3d007a1b728202166c9936fe9626b9bc2e4468 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 3 Nov 2026 19:57:31 +0800 Subject: [PATCH 13/17] fix(config): stop a discarded write from retiring a current one CodeRabbit review comment 4454293128 (Functional Correctness, Minor) against ec8850bc6. It held: the rejection handler called retireWrite() before checking the generation, so a write issued before resetAllState() decremented the in-flight count of writes issued after it. The next landing for that key then saw no writes running and copied its value into the mirror while a newer write was still pending. The generation check now comes first in the rejection handler - a discarded write reports its failure and leaves the current generation bookkeeping alone - which also made the second belongsToCurrentState() inside the restore condition redundant, so that one was removed rather than kept as untestable code. Test (47/47 in ContextProxy.spec.ts): a rejected pre-reset write must not retire one of two newer writes, so the older of the newer writes may not decide the mirror while the newest is still in flight. Sweep over the handler: 5 of 6 mutants killed (stale rejection still retires a write, any rejection rolls the mirror back, a pre-reset write may land after the reset, landing never repairs the mirror, rejection leaves the write in flight). The survivor is unchanged and still disclosed: dropping writeSequences.clear() from resetAllState is not observable because the generation guard already ignores that settlement. Regressions: full unit suite 58 failed / 12008 passed (12007 before), same 15 pre-existing Windows failures. check-types 114 pre-existing errors, none in a touched file. ESLint exits 0 with --max-warnings=0; eslint-suppressions.json untouched. --- src/core/config/ContextProxy.ts | 9 ++++- .../config/__tests__/ContextProxy.spec.ts | 33 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/core/config/ContextProxy.ts b/src/core/config/ContextProxy.ts index 66b1b7f047..db8ea8b48b 100644 --- a/src/core/config/ContextProxy.ts +++ b/src/core/config/ContextProxy.ts @@ -430,6 +430,13 @@ export class ContextProxy { } }, (error) => { + // A write from a discarded generation is not part of this generation's + // in-flight count. Retiring it would credit a newer write as finished and let + // that write decide the mirror while something newer is still running. + if (!belongsToCurrentState()) { + throw error + } + retireWrite() // The newest write for the key is the one storage would have ended up with, @@ -439,7 +446,7 @@ export class ContextProxy { // leaves the mirror to the newer write that is still in flight. // The map spans every key, so its value is the union over all keys - this // write's key is the one being restored. - if (belongsToCurrentState() && this.writeSequences.get(key) === sequence) { + if (this.writeSequences.get(key) === sequence) { this.stateCache[key] = this.persistedValues.get(key) as GlobalState[K] } throw error diff --git a/src/core/config/__tests__/ContextProxy.spec.ts b/src/core/config/__tests__/ContextProxy.spec.ts index 55dfd693c3..5cc372b815 100644 --- a/src/core/config/__tests__/ContextProxy.spec.ts +++ b/src/core/config/__tests__/ContextProxy.spec.ts @@ -679,6 +679,39 @@ describe("ContextProxy", () => { await postReset expect(proxy.getGlobalState("apiProvider")).toBe("anthropic") }) + + it("keeps a rejected pre-reset write out of the in-flight count of newer writes", async () => { + let failPreReset: (error: Error) => void = () => {} + mockGlobalState.update.mockImplementationOnce( + () => new Promise((_resolve, reject) => (failPreReset = reject)), + ) + const preReset = proxy.updateGlobalState("apiProvider", "openai") + + await proxy.resetAllState() + + let settleOlder: (value: undefined) => void = () => {} + let settleNewer: (value: undefined) => void = () => {} + mockGlobalState.update.mockImplementationOnce(() => new Promise((resolve) => (settleOlder = resolve))) + const older = proxy.updateGlobalState("apiProvider", "anthropic") + mockGlobalState.update.mockImplementationOnce(() => new Promise((resolve) => (settleNewer = resolve))) + const newer = proxy.updateGlobalState("apiProvider", "openrouter") + + // The stale rejection must not retire one of the post-reset writes; if it did, + // the older landing below would look like the last write standing. + failPreReset(new Error("globalState write failed")) + await expect(preReset).rejects.toThrow("globalState write failed") + + settleOlder(undefined) + await older + + // The newer write is still in flight, so its value is what the mirror holds. + expect(proxy.getGlobalState("apiProvider")).toBe("openrouter") + + settleNewer(undefined) + await newer + + expect(proxy.getGlobalState("apiProvider")).toBe("openrouter") + }) }) describe("invalid apiProvider migration", () => { From e265d53c4e29b090ded18e139e405b97390afe6b Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 3 Nov 2026 20:22:08 +0800 Subject: [PATCH 14/17] test(config): cover the post-reset rollback the rejected-newer path depends on CodeRabbit follow-up comment on the 4b3d007a1 review (Trivial, Functional Correctness, Quick win) against ContextProxy.spec.ts:710-713. It held: the test added in 4b3d007a1 settles both post-reset writes successfully, so nothing exercises the rollback record that a reset leaves empty. A regression that only records a landed write in persistedValues when no newer write is still in flight passed every test in the file. New test issues an older and a newer write for the same key after resetAllState(), resolves the older one, rejects the newer one, and asserts the mirror reports the landed value - both through getGlobalState() and through getValues(), which is the object export() reads. That test kills the regression CodeRabbit described: recording persistedValues only for the last write standing now fails it. Sweep over the handler: 6 of 7 mutants killed; the survivor is still dropping writeSequences.clear() from the reset, unobservable behind the generation guard. ContextProxy.spec.ts: 48/48. Full unit suite 58 failed / 12009 passed, same 15 pre-existing Windows failures. check-types: 114 pre-existing errors, none in a touched file. ESLint exits 0 with --max-warnings=0 and eslint-suppressions.json unchanged (a --prune-suppressions run rewrote the file without changing any count; reverted). --- .../config/__tests__/ContextProxy.spec.ts | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/core/config/__tests__/ContextProxy.spec.ts b/src/core/config/__tests__/ContextProxy.spec.ts index 5cc372b815..aa13c63b54 100644 --- a/src/core/config/__tests__/ContextProxy.spec.ts +++ b/src/core/config/__tests__/ContextProxy.spec.ts @@ -712,6 +712,32 @@ describe("ContextProxy", () => { expect(proxy.getGlobalState("apiProvider")).toBe("openrouter") }) + + it("restores the write that landed after the reset when a newer one is rejected", async () => { + await proxy.resetAllState() + + let settleOlder: (value: undefined) => void = () => {} + let failNewer: (error: Error) => void = () => {} + mockGlobalState.update.mockImplementationOnce(() => new Promise((resolve) => (settleOlder = resolve))) + const older = proxy.updateGlobalState("apiProvider", "anthropic") + mockGlobalState.update.mockImplementationOnce(() => new Promise((_resolve, reject) => (failNewer = reject))) + const newer = proxy.updateGlobalState("apiProvider", "openrouter") + + settleOlder(undefined) + await older + + // The newer write is still in flight, so the mirror still holds its value. + expect(proxy.getGlobalState("apiProvider")).toBe("openrouter") + + failNewer(new Error("globalState write failed")) + await expect(newer).rejects.toThrow("globalState write failed") + + // The reset emptied both the mirror and the rollback record, so the landing of + // the older write is the only thing storage holds - the rejected newer write + // falls back to it, not to nothing. + expect(proxy.getGlobalState("apiProvider")).toBe("anthropic") + expect(proxy.getValues().apiProvider).toBe("anthropic") + }) }) describe("invalid apiProvider migration", () => { From c61e97b2cdc18d512d2e5b294c94daaed2e6030c Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 3 Nov 2026 20:44:05 +0800 Subject: [PATCH 15/17] fix(config): report what landed when the last write standing for a key rejects CodeRabbit pre-merge check Persistence Integrity on e265d53c4. The scenario it names held: with persisted S and three writes A, B, C for one key, let C reject first, A land next and B reject last. C is the newest issued, so the mirror correctly fell back to S; A landed but was not the last write running, so it only advanced the rollback record; B rejected while being the last write standing, but it was not the newest issued, so nothing corrected the mirror. Storage held the value A landed and the cache kept reporting S. The rejection handler now takes the result of retireWrite() and restores the newest persisted value in either case: the rejection was the newest write issued for the key, or nothing is in flight for that key any more. Landing behaviour is unchanged. Test: keeps the landed value when the last write standing for the key rejects - the exact three-write order above, asserting the intermediate fallback to S as well as the final value, through getGlobalState() and getValues(). Sweep over the handler: 7 of 8 mutants killed (stale last-standing rejection keeps the stale mirror, newest rejection not rolled back, any rejection rolls the mirror back, landed write recorded only when last standing, stale rejection still retires a write, pre-reset write may land after the reset, landing never repairs the mirror). The survivor is unchanged: dropping writeSequences.clear() from the reset is not observable behind the generation guard. ContextProxy.spec.ts 49/49. Full unit suite 58 failed / 12010 passed, same 15 pre-existing Windows failures. check-types 114 pre-existing errors, none in a touched file. ESLint exits 0 with --max-warnings=0; eslint-suppressions.json untouched. --- src/core/config/ContextProxy.ts | 17 +++++---- .../config/__tests__/ContextProxy.spec.ts | 37 +++++++++++++++++++ 2 files changed, 46 insertions(+), 8 deletions(-) diff --git a/src/core/config/ContextProxy.ts b/src/core/config/ContextProxy.ts index db8ea8b48b..46d9e788cb 100644 --- a/src/core/config/ContextProxy.ts +++ b/src/core/config/ContextProxy.ts @@ -437,16 +437,17 @@ export class ContextProxy { throw error } - retireWrite() - - // The newest write for the key is the one storage would have ended up with, - // so its rejection is rolled back to the newest value that actually - // persisted, even while an older write for the same key is still running - - // otherwise readers report a value that was rejected. An older rejection - // leaves the mirror to the newer write that is still in flight. + const wasLastWriteStanding = retireWrite() + + // Two cases decide what the mirror holds: + // - this was the newest write issued for the key: storage will never take + // that value, so fall back to the newest value that persisted, even while + // an older write for the same key is still running; + // - nothing is in flight for this key any more: whatever landed and whatever + // failed, the mirror has to equal what storage actually holds. // The map spans every key, so its value is the union over all keys - this // write's key is the one being restored. - if (this.writeSequences.get(key) === sequence) { + if (wasLastWriteStanding || this.writeSequences.get(key) === sequence) { this.stateCache[key] = this.persistedValues.get(key) as GlobalState[K] } throw error diff --git a/src/core/config/__tests__/ContextProxy.spec.ts b/src/core/config/__tests__/ContextProxy.spec.ts index aa13c63b54..10ff1af4f6 100644 --- a/src/core/config/__tests__/ContextProxy.spec.ts +++ b/src/core/config/__tests__/ContextProxy.spec.ts @@ -330,6 +330,43 @@ describe("ContextProxy", () => { // deliberately leaves provider settings such as `apiProvider` out. expect(proxy.getValues().apiProvider).toBe("openai") }) + + it("keeps the landed value when the last write standing for the key rejects", async () => { + await proxy.updateGlobalState("apiProvider", "deepseek") + + let settleOldest: (value: undefined) => void = () => {} + let rejectMiddle: (error: Error) => void = () => {} + let rejectNewest: (error: Error) => void = () => {} + mockGlobalState.update.mockImplementationOnce(() => new Promise((resolve) => (settleOldest = resolve))) + const oldest = proxy.updateGlobalState("apiProvider", "openai") + mockGlobalState.update.mockImplementationOnce( + () => new Promise((_resolve, reject) => (rejectMiddle = reject)), + ) + const middle = proxy.updateGlobalState("apiProvider", "anthropic") + mockGlobalState.update.mockImplementationOnce( + () => new Promise((_resolve, reject) => (rejectNewest = reject)), + ) + const newest = proxy.updateGlobalState("apiProvider", "openrouter") + + // The newest write fails first, so the mirror falls back to what storage held + // before these three writes. + rejectNewest(new Error("globalState write failed")) + await expect(newest).rejects.toThrow("globalState write failed") + expect(proxy.getGlobalState("apiProvider")).toBe("deepseek") + + // The oldest write lands, so storage now holds its value while the middle one + // is still in flight. + settleOldest(undefined) + await oldest + + // The middle write is the last one standing and it fails too: the mirror has + // to report what landed, not what was there before all three writes. + rejectMiddle(new Error("globalState write failed")) + await expect(middle).rejects.toThrow("globalState write failed") + + expect(proxy.getGlobalState("apiProvider")).toBe("openai") + expect(proxy.getValues().apiProvider).toBe("openai") + }) }) describe("getSecret", () => { From d241d22e335571bcb74adf5b35d80425a52abae3 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 3 Nov 2026 20:44:51 +0800 Subject: [PATCH 16/17] test(config): assert the imported object that actually reaches storage CodeRabbit pre-merge check Regression Evidence (warning) on e265d53c4: the host-local path import test asserted the returned summary only. The value the extension uses is the one handed to contextProxy.setValues, so the test now pins that object: exactly one setValues call, mode "code" present, and none of lastSettingsExportPath, lastTaskExportPath, lastModeExportPath or lastImageSavePath. Dropping any key from hostLocalPathKeys is killed by this test (checked for two of the four: lastSettingsExportPath and lastImageSavePath). importExport.spec.ts: 66 passed / 1 failed, the failure being the pre-existing Windows "round-trips a prompt cache TTL through export and import" tracked by #2059. ESLint exits 0 with --max-warnings=0; eslint-suppressions.json untouched. --- src/core/config/__tests__/importExport.spec.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/core/config/__tests__/importExport.spec.ts b/src/core/config/__tests__/importExport.spec.ts index 84f968e4a3..8c1ad3dcba 100644 --- a/src/core/config/__tests__/importExport.spec.ts +++ b/src/core/config/__tests__/importExport.spec.ts @@ -413,6 +413,16 @@ describe("importExport", () => { 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. From 88df388ae505f6eea65ad9d50af5ea8d3e1d9900 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:12:00 +0800 Subject: [PATCH 17/17] fix(export): type host-local keys, cover remembered-over-workspace, assert the toast exactly Three review threads adjudicated against the head this branch carried, 0411945752894d9551855061dfff9db9599f26a9. hostLocalPathKeys is now a const tuple with `as const satisfies readonly (keyof GlobalSettings)[]`, so a schema rename or a mistyped host-local key fails at compile time while hostLocalPathKeys.has keeps its string argument. Measured: typing one key as lastImageSavePathTypo makes tsc print TS2820 at that row and exit 2. export.spec.ts gains the remembered-directory case with workspaceFolders set and the default useWorkspace, the priority edge the suite never exercised with a live remembered path. Measured: swapping the remembered and workspace blocks in utils/export.ts makes that test fail with the workspace folder chosen over the remembered directory, and it passes again once the order is restored. importExport.spec.ts asserts the whole echoed toast instead of two substrings, so a renamed interpolation parameter is caught rather than silently rendering a message without the path. Measured: renaming path to filePath at the call site makes that test fail. Checks run before this commit: tsc --noEmit over src, 0 errors. eslint --ext=ts --max-warnings=0 on the three touched files, clean, eslint-suppressions.json unchanged. prettier --check on the three touched files, clean. vitest, export.spec.ts 16 passed and importExport.spec.ts 67 passed. --- src/core/config/__tests__/importExport.spec.ts | 10 +++++----- src/core/config/importExport.ts | 6 ++++-- src/utils/__tests__/export.spec.ts | 12 ++++++++++++ 3 files changed, 21 insertions(+), 7 deletions(-) diff --git a/src/core/config/__tests__/importExport.spec.ts b/src/core/config/__tests__/importExport.spec.ts index 8c1ad3dcba..b595bb1b12 100644 --- a/src/core/config/__tests__/importExport.spec.ts +++ b/src/core/config/__tests__/importExport.spec.ts @@ -1987,12 +1987,12 @@ describe("importExport", () => { 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. + // 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( - expect.stringContaining("info.settings_exported"), - ) - expect(vscode.window.showInformationMessage).toHaveBeenCalledWith( - expect.stringContaining("/usb/zoo-code-settings.json"), + `common:info.settings_exported:{"path":"/usb/zoo-code-settings.json"}`, ) }) diff --git a/src/core/config/importExport.ts b/src/core/config/importExport.ts index ba63f84ac4..8fa2f650ac 100644 --- a/src/core/config/importExport.ts +++ b/src/core/config/importExport.ts @@ -86,12 +86,14 @@ function formatZodIssues(error: ZodError): string { * this machine. They are dropped on import and re-established by the next dialog * choice. */ -const hostLocalPathKeys = new Set([ +const hostLocalPathKeyNames = [ "lastSettingsExportPath", "lastTaskExportPath", "lastModeExportPath", "lastImageSavePath", -]) +] as const satisfies readonly (keyof GlobalSettings)[] + +const hostLocalPathKeys: ReadonlySet = new Set(hostLocalPathKeyNames) function sanitizeGlobalSettings(rawGlobalSettings: unknown): { sanitizedGlobalSettings: GlobalSettings diff --git a/src/utils/__tests__/export.spec.ts b/src/utils/__tests__/export.spec.ts index 97c89b2e0f..3b84a03030 100644 --- a/src/utils/__tests__/export.spec.ts +++ b/src/utils/__tests__/export.spec.ts @@ -73,6 +73,18 @@ describe("resolveDefaultSaveUri", () => { 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 })