import { safeWriteJson } from "../../utils/safeWriteJson" import os from "os" import * as path from "path" import fs from "fs/promises" import * as vscode from "vscode" import { z, ZodError } from "zod" import { globalSettingsSchema, providerSettingsWithIdSchema, isProviderName, retiredProviderIdentifiers, type GlobalSettings, type ProviderSettingsWithId, } from "@roo-code/types" import { TelemetryService } from "@roo-code/telemetry" import { ProviderSettingsManager, providerProfilesSchema } from "./ProviderSettingsManager" import { ContextProxy } from "./ContextProxy" import { CustomModesManager } from "./CustomModesManager" import { downgradeLegacyRooConfig, ROUTER_REMOVAL_IMPORT_WARNING } from "./routerRemoval" import { resolveDefaultSaveUri, saveLastExportPath } from "../../utils/export" import { t } from "../../i18n" import { commandListConfiguration, rollbackFailedCommandListWrite, sanitizeCommandList, type CommandListConfigKey, } from "../auto-approval/commandScope" export type ImportOptions = { providerSettingsManager: ProviderSettingsManager contextProxy: ContextProxy customModesManager: CustomModesManager } type ExportOptions = { providerSettingsManager: ProviderSettingsManager contextProxy: ContextProxy } type ImportWithProviderOptions = ImportOptions & { provider: { settingsImportedAt?: number postStateToWebview: () => Promise } } /** * Sanitizes a provider config by resetting invalid/removed apiProvider values. * Returns the sanitized config and a warning message if the provider was invalid. */ function sanitizeProviderConfig(configName: string, apiConfig: unknown): { config: unknown; warning?: string } { if (typeof apiConfig !== "object" || apiConfig === null) { return { config: apiConfig } } const { config, migrated } = downgradeLegacyRooConfig(apiConfig as Record) if (migrated) { return { config, warning: `Profile "${configName}": ${ROUTER_REMOVAL_IMPORT_WARNING}`, } } // Check if apiProvider is set and if it's still valid if (config.apiProvider !== undefined && !isProviderName(config.apiProvider)) { const invalidProvider = config.apiProvider // Return a new config object without the invalid apiProvider const { apiProvider: _apiProvider, ...restConfig } = config return { config: restConfig, warning: `Profile "${configName}": Invalid provider "${invalidProvider}" was removed. Please reconfigure this profile.`, } } return { config: apiConfig } } const globalSettingsShape = globalSettingsSchema.shape as Record function formatZodIssues(error: ZodError): string { return error.issues.map((issue) => `[${issue.path.join(".") || "value"}]: ${issue.message}`).join(", ") } function sanitizeGlobalSettings(rawGlobalSettings: unknown): { sanitizedGlobalSettings: GlobalSettings warnings: string[] } { const warnings: string[] = [] const sanitizedGlobalSettings: Record = {} if (typeof rawGlobalSettings === "undefined") { return { sanitizedGlobalSettings: sanitizedGlobalSettings as GlobalSettings, warnings } } if (typeof rawGlobalSettings !== "object" || rawGlobalSettings === null || Array.isArray(rawGlobalSettings)) { warnings.push( `Setting "globalSettings" was skipped: Expected object, received ${Array.isArray(rawGlobalSettings) ? "array" : typeof rawGlobalSettings}.`, ) return { sanitizedGlobalSettings: sanitizedGlobalSettings as GlobalSettings, warnings } } for (const [key, rawValue] of Object.entries(rawGlobalSettings)) { const path = `globalSettings.${key}` // The schema accepts this key, so without this branch the import reports // success and stores a value the enforcement path never reads: the gate is // read from VS Code user settings only. if (key === "workspaceCommandListsEnabled") { warnings.push( `Setting "${path}" was skipped: The workspace command-list gate applies only from VS Code user settings, not from an imported file.`, ) continue } const schema = globalSettingsShape[key as keyof GlobalSettings] if (!schema) { warnings.push(`Setting "${path}" was skipped: Unknown setting.`) continue } let valueToValidate = rawValue if (key === "imageGenerationProvider" && rawValue === retiredProviderIdentifiers.roo) { warnings.push(`Setting "${path}" used unsupported value "roo" and was cleared during import.`) valueToValidate = undefined } const result = schema.safeParse(valueToValidate) if (result.success) { sanitizedGlobalSettings[key] = result.data } else { warnings.push(`Setting "${path}" was skipped: ${formatZodIssues(result.error)}`) } } return { sanitizedGlobalSettings: sanitizedGlobalSettings as GlobalSettings, warnings } } /** * Imports configuration from a specific file path. * Shares base functionality for import settings for both the manual * and automatic settings importing. * * Holds the command-list lock for the whole import. Every caller resolves its * file path first — the settings dialog runs in `importSettings`, the auto-import * path checks its configured file — so the lock is never held across a dialog. * * Uses lenient parsing to handle invalid/removed providers gracefully: * - Invalid apiProvider values are removed (profile is kept but needs reconfiguration) * - Completely invalid profiles are skipped * - Warnings are returned for any issues encountered */ export function importSettingsFromPath(filePath: string, options: ImportOptions) { return withCommandListLock(() => applySettingsImport(filePath, options)) } /** The import body. It runs inside {@link withCommandListLock}. */ async function applySettingsImport( filePath: string, { providerSettingsManager, contextProxy, customModesManager }: ImportOptions, ) { // Use a lenient schema that accepts any apiConfigs, then validate each individually const lenientProviderProfilesSchema = providerProfilesSchema.extend({ apiConfigs: z.record(z.string(), z.any()), }) const lenientSchema = z.object({ providerProfiles: lenientProviderProfilesSchema, globalSettings: z.unknown().optional(), }) // A failed import leaves both stores as they were. The settings file is only // written after a successful import, so it needs no restore; the two command-list // stores are written below, and these hold the copies the failure path puts back. let priorStateCopy: Pick | undefined // The command-list keys this import writes into extension state. Empty until the // snapshot is taken, because the settings are not parsed before then. let stateCommandListKeys: readonly (keyof Pick)[] = [] let importedCommandLists: ImportedCommandListWrite[] = [] try { const previousProviderProfiles = await providerSettingsManager.export() const rawData = JSON.parse(await fs.readFile(filePath, "utf-8")) const { providerProfiles: rawProviderProfiles, globalSettings: rawGlobalSettings } = lenientSchema.parse(rawData) // Track warnings for profiles that had issues const warnings: string[] = [] const validApiConfigs: Record = {} // Process each apiConfig individually with sanitization for (const [configName, rawConfig] of Object.entries(rawProviderProfiles.apiConfigs)) { // First sanitize to handle invalid apiProvider values const { config: sanitizedConfig, warning } = sanitizeProviderConfig(configName, rawConfig) if (warning) { warnings.push(warning) } // Then validate the sanitized config const result = providerSettingsWithIdSchema.safeParse(sanitizedConfig) if (result.success) { validApiConfigs[configName] = result.data } else { // Profile is completely invalid - skip it const issues = result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join(", ") warnings.push(`Profile "${configName}" was skipped: ${issues}`) } } // If no valid configs were imported and there were issues, report them if (Object.keys(validApiConfigs).length === 0 && warnings.length > 0) { return { success: false, error: `No valid profiles could be imported:\n${warnings.join("\n")}`, } } // Determine the currentApiConfigName: // 1. If the imported currentApiConfigName exists in validApiConfigs, use it // 2. Otherwise, fall back to the first valid imported profile // 3. If no valid profiles were imported, keep the previous currentApiConfigName let currentApiConfigName = rawProviderProfiles.currentApiConfigName const validProfileNames = Object.keys(validApiConfigs) if (!validApiConfigs[currentApiConfigName]) { if (validProfileNames.length > 0) { currentApiConfigName = validProfileNames[0] warnings.push( `Profile "${rawProviderProfiles.currentApiConfigName}" was not available; defaulting to "${currentApiConfigName}".`, ) } else { // No valid imported profiles; keep the existing currentApiConfigName currentApiConfigName = previousProviderProfiles.currentApiConfigName } } const providerProfiles = { currentApiConfigName, apiConfigs: { ...previousProviderProfiles.apiConfigs, ...validApiConfigs, }, modeApiConfigs: { ...previousProviderProfiles.modeApiConfigs, ...rawProviderProfiles.modeApiConfigs, }, } const { sanitizedGlobalSettings, warnings: globalSettingsWarnings } = sanitizeGlobalSettings(rawGlobalSettings) warnings.push(...globalSettingsWarnings) await Promise.all( (sanitizedGlobalSettings.customModes ?? []).map((mode) => customModesManager.updateCustomMode(mode.slug, mode), ), ) // OpenAI Compatible settings are now correctly stored in codebaseIndexConfig // They will be imported automatically with the config - no special handling needed await providerSettingsManager.import(providerProfiles) // Read through the same proxy the write below uses, because extension state // is the store this function writes. Captured before either write so a // partial `setValues` is restored too, not only a failure that follows it. priorStateCopy = { allowedCommands: contextProxy.getValue("allowedCommands"), deniedCommands: contextProxy.getValue("deniedCommands"), } // The state write is one `setValues` call, so the command-list keys it can // touch are exactly the ones the settings carry as arrays. The same predicate // gates `writeImportedCommandLists`, so the restore below names the keys the // import wrote rather than both keys of the snapshot. A provider-only import // therefore rewrites no list and reports no restore error for one. stateCommandListKeys = (["allowedCommands", "deniedCommands"] as const).filter((key) => Array.isArray(sanitizedGlobalSettings[key]), ) // The configuration half comes first, matching the save's order. With one // order, the two writers cannot interleave into stores that disagree, and a // failure below can undo this half against a fresh read. The helper appends // to this array as each key lands, so the catch below sees a partial write. importedCommandLists = [] await writeImportedCommandLists(sanitizedGlobalSettings, importedCommandLists) await contextProxy.setValues(sanitizedGlobalSettings) // Set the current provider. const currentProviderName = providerProfiles.currentApiConfigName const currentProvider = providerProfiles.apiConfigs[currentProviderName] await contextProxy.setValue("currentApiConfigName", currentProviderName) // TODO: It seems like we don't need to have the provider settings in // the proxy; we can just use providerSettingsManager as the source of // truth. if (currentProvider) { await contextProxy.setProviderSettings(currentProvider) } await contextProxy.setValue("listApiConfigMeta", await providerSettingsManager.listConfig()) return { providerProfiles, globalSettings: sanitizedGlobalSettings, success: true, warnings: warnings.length > 0 ? warnings : undefined, } } catch (e) { let error = "Unknown error" if (e instanceof ZodError) { error = e.issues.map((issue) => `[${issue.path.join(".")}]: ${issue.message}`).join("\n") TelemetryService.instance.captureSchemaValidationError({ schemaName: "ImportExport", error: e }) } else if (e instanceof Error) { error = e.message } if (priorStateCopy) { const unrestoredKeys: string[] = [] for (const key of stateCommandListKeys) { // A restore that rejects is reported in the error text rather than // thrown, so the caller always learns the import failed. try { await contextProxy.setValue(key, priorStateCopy[key]) } catch { unrestoredKeys.push(key) } } if (unrestoredKeys.length > 0) { error = `${error}\nThe prior ${unrestoredKeys.join(", ")} value(s) could not be restored in extension state.` } } // The configuration half is undone by delta, so an entry another writer added // while the import ran survives. Only the keys this import wrote are named. if (importedCommandLists.length > 0) { error = `${error}${await rollBackImportedCommandLists(importedCommandLists, error)}` } return { success: false, error } } } /** * Import settings from a file using a file dialog * @param options - Import options containing managers and proxy * @returns Promise resolving to import result */ export const importSettings = async ({ providerSettingsManager, contextProxy, customModesManager }: ImportOptions) => { // Use the last export path as a sensible default, falling back to Downloads const defaultUri = resolveDefaultSaveUri(contextProxy, "lastSettingsExportPath", "zoo-code-settings.json", { useWorkspace: false, fallbackDir: path.join(os.homedir(), "Downloads"), }) const uris = await vscode.window.showOpenDialog({ filters: { JSON: ["json"] }, canSelectMany: false, defaultUri, }) if (!uris) { return { success: false, error: "User cancelled file selection" } } return importSettingsFromPath(uris[0].fsPath, { providerSettingsManager, contextProxy, customModesManager, }) } /** * Import settings from a specific file * * @internal * @param options - Import options containing managers and proxy * @param fileUri - URI of the file to import from * @returns Promise resolving to import result */ export const importSettingsFromFile = async ( { providerSettingsManager, contextProxy, customModesManager }: ImportOptions, fileUri: vscode.Uri, ) => { return importSettingsFromPath(fileUri.fsPath, { providerSettingsManager, contextProxy, customModesManager, }) } export const exportSettings = async ({ providerSettingsManager, contextProxy }: ExportOptions) => { const defaultUri = await resolveDefaultSaveUri(contextProxy, "lastSettingsExportPath", "zoo-code-settings.json", { useWorkspace: false, fallbackDir: path.join(os.homedir(), "Downloads"), }) const uri = await vscode.window.showSaveDialog({ filters: { JSON: ["json"] }, defaultUri, }) if (!uri) { return } await saveLastExportPath(contextProxy, "lastSettingsExportPath", uri) try { const providerProfiles = await providerSettingsManager.export() const globalSettings = await contextProxy.export() // It's okay if there are no global settings, but if there are no // provider profile configured then don't export. If we wanted to // support this case then the `importSettings` function would need to // be updated to handle the case where there are no provider profiles. if (typeof providerProfiles === "undefined") { return } // OpenAI Compatible settings are now correctly stored in codebaseIndexConfig // No workaround needed - they will be exported automatically with the config const dirname = path.dirname(uri.fsPath) await fs.mkdir(dirname, { recursive: true }) await safeWriteJson(uri.fsPath, { providerProfiles, globalSettings }) } catch (e) { console.error("Failed to export settings:", e) // Don't re-throw - the UI will handle showing error messages } } /** * Serialises the command-list writes of a save and an import. * * A save writes the configuration global layer and then the extension state * copy; an import writes the same two in the same order. With one order, the * only interleaving that could still diverge the stores is one writer landing * its second half after the other writer landed both, so mutual exclusion over * the whole pair closes it. * * The lock is not re-entrant. A writer that already holds it must not call this * function again, and an import acquires it inside `importSettingsFromPath`, * which every caller reaches only after its file path is resolved. That is what * keeps the lock off the file dialog: the dialog runs before this function is * entered, so a save never waits on a human's choice. * * @param write - The pair to run. It may throw; the lock is released either way. * @returns Whatever `write` returned. */ export async function withCommandListLock(write: () => Promise): Promise { const previous = commandListLockTail let release!: () => void // The tail the next caller waits on. It resolves when this caller's write // settles, so waiting callers queue instead of all entering at once. commandListLockTail = new Promise((resolve) => { release = resolve }) await previous try { return await write() } finally { release() } } /** The last queued caller's completion, or a settled promise when the lock is free. */ let commandListLockTail: Promise = Promise.resolve() /** * The keys an import wrote to the configuration, with the layer each held * before the write, so a failed state half can undo them. */ interface ImportedCommandListWrite { key: CommandListConfigKey imported: string[] priorLayer: string[] | undefined /** * Whether the pre-write layer could not be read. Such a record has no * baseline to undo against, and its rollback clears nothing rather than * treat the failed read as an absent layer. */ priorLayerUnknown?: boolean } /** * Writes the command lists an import carried into the user settings file. * * The configuration global layer is the only persisted home for these lists, * and its absence is what a later save reads as the user having deleted the key. * An import that skipped this write would leave its entries in the state copy * alone, and the next save would drop them as removals. So this is the import * pair's first half, not an optional mirror. * * A key the import file did not carry is skipped, so the state copy never * becomes the source. * * The caller owns `written`, because a rejection between two keys must reach its * rollback: each append follows the write it records, so the caller holds exactly * the keys that landed rather than nothing at all. * * @param globalSettings - The sanitized settings the import file carried. * @param written - The caller's accumulator. A key is appended after its write resolves. */ async function writeImportedCommandLists( globalSettings: GlobalSettings | undefined, written: ImportedCommandListWrite[], ): Promise { const config = commandListConfiguration() for (const key of ["allowedCommands", "deniedCommands"] as const) { const imported = globalSettings?.[key] if (!Array.isArray(imported)) { continue } let priorLayer: string[] | undefined let priorLayerUnknown = false try { priorLayer = config.inspect(key)?.globalValue } catch { // The read threw, so the prior layer is unknown, not absent. Recording // that lets the rollback leave the key alone: a failed read is no // evidence that nothing was there, and clearing on it would destroy a // list this import never saw. priorLayer = undefined priorLayerUnknown = true } await config.update(key, sanitizeCommandList(imported), vscode.ConfigurationTarget.Global) // Appended after the write resolves, so the rollback's baseline and its // `globalWriteApplied: true` describe a write that landed. written.push({ key, imported: sanitizeCommandList(imported), priorLayer, priorLayerUnknown }) } } /** * Undoes the configuration half of an import whose state half failed. * * The undo is the save path's own delta rollback, so an entry another writer * added while the import ran survives. The state copy is restored separately by * the caller, from the values it captured before the write. * * @param written - The keys the import's first half wrote. * @param failure - The failure text of the state write that threw. * @returns A sentence to append to the error when an undo could not land. */ async function rollBackImportedCommandLists(written: ImportedCommandListWrite[], failure: string): Promise { const config = commandListConfiguration() const unrestored: string[] = [] for (const { key, imported, priorLayer, priorLayerUnknown } of written) { if (priorLayerUnknown) { // There is no baseline to undo against, so any write here would guess. // The key keeps the imported list and the caller names it as unrestored. unrestored.push(key) continue } const outcome = await rollbackFailedCommandListWrite({ key, failure, globalWrite: imported, configGlobalAtSaveStart: priorLayer ?? [], globalLayerAtSaveStart: priorLayer, globalWriteApplied: true, readGlobalLayer: () => config.inspect(key)?.globalValue, writeGlobalLayer: (value) => config.update(key, value, vscode.ConfigurationTarget.Global), }) if (outcome.status === "re-read-failed" || outcome.status === "restore-failed") { unrestored.push(key) } } return unrestored.length > 0 ? `\nThe prior ${unrestored.join(", ")} value(s) could not be restored in VS Code user settings.` : "" } /** * Import settings with complete UI feedback and provider state updates * * The file path is resolved before `importSettingsFromPath`, which takes the * command-list lock. A save dispatched while the dialog is open therefore * completes instead of waiting for the user's answer. The notifications below * stay outside the lock as well: their promises settle only on dismissal. * * @param options - Import options with provider instance * @param filePath - Optional file path to import from. If not provided, a file dialog will be shown. * @returns Promise that resolves when import is complete */ export const importSettingsWithFeedback = async ( { providerSettingsManager, contextProxy, customModesManager, provider }: ImportWithProviderOptions, filePath?: string, ) => { const options = { providerSettingsManager, contextProxy, customModesManager } let result if (filePath) { // Validate file path and check if file exists try { // Check if file exists and is readable await fs.access(filePath, fs.constants.F_OK | fs.constants.R_OK) result = await importSettingsFromPath(filePath, options) } catch (error) { result = { success: false, error: `Cannot access file at path "${filePath}": ${error instanceof Error ? error.message : "Unknown error"}`, } } } else { result = await importSettings(options) } if (result.success) { provider.settingsImportedAt = Date.now() await provider.postStateToWebview() provider.settingsImportedAt = undefined const warnings = "warnings" in result ? result.warnings : undefined // Show warnings if any profiles had issues but were still imported (with modifications) if (warnings && warnings.length > 0) { // Log full details to the console for debugging console.warn("Settings import completed with warnings:", warnings) // Show a short summary in the toast notification const count = warnings.length const summary = count === 1 ? `1 item had issues during import.` : `${count} items had issues during import.` await vscode.window.showWarningMessage( `${t("common:info.settings_imported")} ${summary} See Developer Tools console for details.`, ) } else { await vscode.window.showInformationMessage(t("common:info.settings_imported")) } } else if (result.error) { await vscode.window.showErrorMessage(t("common:errors.settings_import_failed", { error: result.error })) } }