Skip to content

Commit 931ea84

Browse files
fix(config): carry the export failure to the user even when the notification fails
Two review rows on PR 1405 asked for executable lines in the export route: - The notification being awaited unguarded inside the catch that cannot see a throwing notification. showErrorMessage is now awaited inside its own try, so a notification channel that rejects cannot turn a failure this route deliberately swallows into a rejection that webviewMessageHandler - which awaits exportSettings without a try - would surface as an unhandled failure. - The mock writer being the only writer in the refusal path. One row lifts the writer mock for a single test and re-imports the module, so exportSettings drives the real safeWriteJson: an ordinary destination written to a real temporary directory holds the exported payload, and a real junction planted where the user asked for the file is refused, leaves the entry a link, gains nothing in its referent, and is reported to the user through the same key the import route uses. The row runs with only the dialog doubled; a file symlink cannot be created on the Windows lane this branch was tested on (EPERM), so the link is a junction, which needs no privileges. Both new rows measured red on the pull head before the change and green after it, and the refusal row was also run with the writer left mocked, where it fails with ENOENT on the destination, which is what proves it exercises the real writer.
1 parent 0fd6d59 commit 931ea84

2 files changed

Lines changed: 160 additions & 1 deletion

File tree

‎src/core/config/__tests__/importExport.spec.ts‎

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1735,6 +1735,157 @@ describe("importExport", () => {
17351735
consoleErrorSpy.mockRestore()
17361736
})
17371737

1738+
// The writer mocked at the top of this file answers every path with undefined, so it cannot
1739+
// say what a refusal looks like on disk. This row lifts that mock for one test, re-imports
1740+
// the module so exportSettings calls the real writer, and plants a real link at the path the
1741+
// dialog returned: the ordinary destination gets the payload, the linked one keeps its own
1742+
// content and the user is told. Only vscode's dialog stays doubled, as everywhere else here.
1743+
it("publishes through the real writer to an ordinary destination and refuses a link the user never chose", async () => {
1744+
const fsActual = await vi.importActual<typeof import("fs/promises")>("fs/promises")
1745+
const osActual = await vi.importActual<typeof import("os")>("os")
1746+
1747+
vi.doUnmock("../../../utils/safeWriteJson")
1748+
vi.doUnmock("fs/promises")
1749+
vi.resetModules()
1750+
const { exportSettings: exportWithRealWriter } = await import("../importExport")
1751+
// resetModules gave the module under test a fresh vscode mock, so the dialog has to be
1752+
// steered on that instance rather than on the one this file imported at the top.
1753+
const vscodeFresh = await import("vscode")
1754+
1755+
const providerProfiles = {
1756+
currentApiConfigName: "real",
1757+
apiConfigs: { real: { apiProvider: providerIdentifiers.openai, id: "real-id" } },
1758+
migrations: { rateLimitSecondsMigrated: false },
1759+
}
1760+
const globalSettings = { mode: "code" }
1761+
const fakeProviderSettingsManager = { export: vi.fn().mockResolvedValue(providerProfiles) }
1762+
const fakeContextProxy = {
1763+
getValue: vi.fn().mockReturnValue(undefined),
1764+
setValue: vi.fn().mockResolvedValue(undefined),
1765+
export: vi.fn().mockResolvedValue(globalSettings),
1766+
}
1767+
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
1768+
// The fresh instance carries the real vscode signatures, so the doubled dialogs are read
1769+
// through the same Mock cast the rest of this file uses.
1770+
const showSaveDialogFresh = vscodeFresh.window.showSaveDialog as Mock
1771+
const showErrorMessageSpy = vscodeFresh.window.showErrorMessage as Mock
1772+
const roots: string[] = []
1773+
try {
1774+
// Ordinary destination: a real directory, no link anywhere on the route.
1775+
const ordinaryDir = await fsActual.mkdtemp(path.join(osActual.tmpdir(), "zoo-export-ordinary-"))
1776+
roots.push(ordinaryDir)
1777+
const ordinaryPath = path.join(ordinaryDir, "zoo-code-settings.json")
1778+
showSaveDialogFresh.mockResolvedValue({ fsPath: ordinaryPath })
1779+
1780+
await expect(
1781+
exportWithRealWriter({
1782+
providerSettingsManager: fakeProviderSettingsManager as never,
1783+
contextProxy: fakeContextProxy as never,
1784+
}),
1785+
).resolves.toBeUndefined()
1786+
1787+
expect(JSON.parse(await fsActual.readFile(ordinaryPath, "utf8"))).toEqual({
1788+
providerProfiles,
1789+
globalSettings,
1790+
})
1791+
expect(showErrorMessageSpy).not.toHaveBeenCalled()
1792+
1793+
// Linked destination: a junction standing where the user asked for the file. Creating
1794+
// it needs no privileges, unlike a file symlink, which this box refuses with EPERM.
1795+
const linkDir = await fsActual.mkdtemp(path.join(osActual.tmpdir(), "zoo-export-link-"))
1796+
roots.push(linkDir)
1797+
const referentDir = path.join(linkDir, "referent")
1798+
await fsActual.mkdir(referentDir)
1799+
const linkedPath = path.join(linkDir, "zoo-code-settings.json")
1800+
let planted = true
1801+
try {
1802+
await fsActual.symlink(referentDir, linkedPath, "junction")
1803+
} catch (error) {
1804+
planted = false
1805+
console.log("skipping the linked half: this platform refused to plant a link:", String(error))
1806+
}
1807+
if (planted) {
1808+
showErrorMessageSpy.mockReset()
1809+
showSaveDialogFresh.mockResolvedValue({ fsPath: linkedPath })
1810+
1811+
await expect(
1812+
exportWithRealWriter({
1813+
providerSettingsManager: fakeProviderSettingsManager as never,
1814+
contextProxy: fakeContextProxy as never,
1815+
}),
1816+
).resolves.toBeUndefined()
1817+
1818+
// Nothing was published onto the link: the entry is still the link itself and the
1819+
// referent directory gained no payload.
1820+
expect((await fsActual.lstat(linkedPath)).isSymbolicLink()).toBe(true)
1821+
expect(await fsActual.readdir(referentDir)).toEqual([])
1822+
expect(showErrorMessageSpy).toHaveBeenCalledTimes(1)
1823+
const reported = consoleErrorSpy.mock.calls.find((call) => call[0] === "Failed to export settings:")
1824+
expect(reported).toBeDefined()
1825+
const reportedError = reported?.[1]
1826+
expect(showErrorMessageSpy).toHaveBeenCalledWith(
1827+
t("common:errors.settings_export_failed", {
1828+
error: reportedError instanceof Error ? reportedError.message : String(reportedError),
1829+
}),
1830+
)
1831+
expect(showErrorMessageSpy).toHaveBeenCalledWith(
1832+
expect.stringContaining("errors.settings_export_failed"),
1833+
)
1834+
}
1835+
} finally {
1836+
consoleErrorSpy.mockRestore()
1837+
showErrorMessageSpy.mockRestore()
1838+
for (const root of roots) {
1839+
await fsActual.rm(root, { recursive: true, force: true }).catch(() => {})
1840+
}
1841+
// Put the writer mock back and clear the registry so later rows keep the file's setup.
1842+
vi.doMock("../../../utils/safeWriteJson")
1843+
vi.resetModules()
1844+
}
1845+
})
1846+
1847+
// The route is awaited by webviewMessageHandler without a try, so a notification channel that
1848+
// fails must not turn the swallowed write failure into a rejection the webview never sees.
1849+
it("swallows a failing failure notification instead of rejecting the export route", async () => {
1850+
;(vscode.window.showSaveDialog as Mock).mockResolvedValue({
1851+
fsPath: "/mock/path/zoo-code-settings.json",
1852+
})
1853+
mockProviderSettingsManager.export.mockResolvedValue({
1854+
currentApiConfigName: "test",
1855+
apiConfigs: { test: { apiProvider: providerIdentifiers.openai, id: "test-id" } },
1856+
migrations: { rateLimitSecondsMigrated: false },
1857+
})
1858+
mockContextProxy.export.mockResolvedValue({ mode: "code" })
1859+
1860+
const refusal = new Error(
1861+
"safeWriteJson: refusing to write through the symlink at /mock/path/zoo-code-settings.json",
1862+
)
1863+
;(safeWriteJson as Mock).mockRejectedValueOnce(refusal)
1864+
1865+
const notificationFailure = new Error("Notification channel closed")
1866+
const showErrorMessageSpy = vi
1867+
.spyOn(vscode.window, "showErrorMessage")
1868+
.mockRejectedValueOnce(notificationFailure)
1869+
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
1870+
1871+
await expect(
1872+
exportSettings({
1873+
providerSettingsManager: mockProviderSettingsManager,
1874+
contextProxy: mockContextProxy,
1875+
}),
1876+
).resolves.toBeUndefined()
1877+
1878+
expect(consoleErrorSpy).toHaveBeenCalledWith("Failed to export settings:", refusal)
1879+
expect(showErrorMessageSpy).toHaveBeenCalledTimes(1)
1880+
expect(consoleErrorSpy).toHaveBeenCalledWith(
1881+
"Failed to notify the user about the export failure:",
1882+
notificationFailure,
1883+
)
1884+
1885+
showErrorMessageSpy.mockRestore()
1886+
consoleErrorSpy.mockRestore()
1887+
})
1888+
17381889
it("should handle errors during directory creation", async () => {
17391890
;(vscode.window.showSaveDialog as Mock).mockResolvedValue({
17401891
fsPath: "/mock/path/zoo-code-settings.json",

‎src/core/config/importExport.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -357,7 +357,15 @@ export const exportSettings = async ({ providerSettingsManager, contextProxy }:
357357
// refused and the destination it would have written through, so the reason travels with the
358358
// message.
359359
const reason = e instanceof Error ? e.message : String(e)
360-
await vscode.window.showErrorMessage(t("common:errors.settings_export_failed", { error: reason }))
360+
try {
361+
await vscode.window.showErrorMessage(t("common:errors.settings_export_failed", { error: reason }))
362+
} catch (notificationError) {
363+
// The route is awaited by webviewMessageHandler without a try of its own, so a notification
364+
// channel that itself fails must not turn this swallowed write failure into a rejection the
365+
// webview never sees. The console line above already names the write failure; this one names
366+
// the notification that could not carry it.
367+
console.error("Failed to notify the user about the export failure:", notificationError)
368+
}
361369
}
362370
}
363371

0 commit comments

Comments
 (0)