feat: add CLI settings export/import functionality

- Implemented exportSettings and importSettings APIs for CLI settings.
- Added hooks useExportSettings and useImportSettings for managing export/import operations in the frontend.
- Updated SettingsPage to include buttons for exporting and importing CLI settings.
- Enhanced backend to handle export and import requests, including validation and conflict resolution.
- Introduced new data structures for exported settings and import options.
- Updated localization files to support new export/import features.
- Refactored CLI tool configurations to remove hardcoded model defaults, allowing dynamic model retrieval.
This commit is contained in:
catlog22
2026-02-25 21:40:24 +08:00
parent 4c2bf31525
commit b2b8688d26
24 changed files with 1287 additions and 651 deletions

View File

@@ -129,7 +129,9 @@ export function CliConfigModal({
const toolConfig = cliTools[tool];
if (!toolConfig) return [];
if (toolConfig.availableModels?.length) return toolConfig.availableModels;
const models = [toolConfig.primaryModel];
// Build models from primaryModel/secondaryModel, filtering out undefined
const models: string[] = [];
if (toolConfig.primaryModel) models.push(toolConfig.primaryModel);
if (toolConfig.secondaryModel && toolConfig.secondaryModel !== toolConfig.primaryModel) {
models.push(toolConfig.secondaryModel);
}

View File

@@ -16,11 +16,15 @@ import {
fetchCliToolStatus,
fetchCcwInstallations,
upgradeCcwInstallation,
exportSettings,
importSettings,
type ChineseResponseStatus,
type WindowsPlatformStatus,
type CodexCliEnhancementStatus,
type CcwInstallStatus,
type CcwInstallationManifest,
type ExportedSettings,
type ImportOptions,
} from '../lib/api';
// Query key factory
@@ -32,6 +36,7 @@ export const systemSettingsKeys = {
aggregatedStatus: () => [...systemSettingsKeys.all, 'aggregatedStatus'] as const,
cliToolStatus: () => [...systemSettingsKeys.all, 'cliToolStatus'] as const,
ccwInstallations: () => [...systemSettingsKeys.all, 'ccwInstallations'] as const,
exportSettings: () => [...systemSettingsKeys.all, 'exportSettings'] as const,
};
const STALE_TIME = 60 * 1000; // 1 minute
@@ -285,3 +290,39 @@ export function useUpgradeCcwInstallation() {
error: mutation.error,
};
}
// ========================================
// Settings Export/Import Hooks
// ========================================
export function useExportSettings() {
const mutation = useMutation({
mutationFn: exportSettings,
});
return {
exportSettings: mutation.mutateAsync,
isPending: mutation.isPending,
error: mutation.error,
};
}
export function useImportSettings() {
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: ({ data, options }: { data: ExportedSettings; options?: ImportOptions }) =>
importSettings(data, options),
onSuccess: () => {
// Invalidate all system settings queries to refresh the UI
queryClient.invalidateQueries({ queryKey: systemSettingsKeys.all });
},
});
return {
importSettings: (data: ExportedSettings, options?: ImportOptions) =>
mutation.mutateAsync({ data, options }),
isPending: mutation.isPending,
error: mutation.error,
};
}

View File

@@ -6482,6 +6482,68 @@ export async function upgradeCcwInstallation(
});
}
// ========== CLI Settings Export/Import API ==========
/**
* Exported settings structure from backend
*/
export interface ExportedSettings {
version: string;
exportedAt: string;
settings: {
cliTools?: Record<string, unknown>;
chineseResponse?: {
claudeEnabled: boolean;
codexEnabled: boolean;
};
windowsPlatform?: {
enabled: boolean;
};
codexCliEnhancement?: {
enabled: boolean;
};
};
}
/**
* Import options for settings import
*/
export interface ImportOptions {
overwrite?: boolean;
dryRun?: boolean;
}
/**
* Import result from backend
*/
export interface ImportResult {
success: boolean;
imported: number;
skipped: number;
errors: string[];
importedIds: string[];
}
/**
* Export CLI settings to JSON file
*/
export async function exportSettings(): Promise<ExportedSettings> {
return fetchApi('/api/cli/settings/export');
}
/**
* Import CLI settings from JSON data
*/
export async function importSettings(
data: ExportedSettings,
options?: ImportOptions
): Promise<ImportResult> {
return fetchApi('/api/cli/settings/import', {
method: 'POST',
body: JSON.stringify({ data, options }),
});
}
// ========== CCW Tools API ==========
/**

View File

@@ -77,7 +77,19 @@
"refreshConfig": "Refresh Config",
"migrationWarning": "Old format detected, please disable and re-enable to migrate",
"enabled": "Enabled",
"disabled": "Disabled"
"disabled": "Disabled",
"export": "Export",
"import": "Import",
"exporting": "Exporting...",
"importing": "Importing...",
"exportImportHint": "Export or import CLI settings configuration",
"exportSuccess": "Settings exported successfully",
"exportError": "Failed to export settings",
"importSuccess": "Settings imported successfully ({imported} imported, {skipped} skipped)",
"importError": "Failed to import settings",
"importInvalidFile": "Please select a valid JSON file",
"importInvalidJson": "Invalid JSON format in file",
"importInvalidStructure": "Invalid settings file structure"
},
"systemStatus": {
"title": "CCW Installation",

View File

@@ -77,7 +77,19 @@
"refreshConfig": "刷新配置",
"migrationWarning": "检测到旧格式,请关闭后重新启用以迁移",
"enabled": "已启用",
"disabled": "已禁用"
"disabled": "已禁用",
"export": "导出",
"import": "导入",
"exporting": "导出中...",
"importing": "导入中...",
"exportImportHint": "导出或导入 CLI 设置配置",
"exportSuccess": "设置导出成功",
"exportError": "导出设置失败",
"importSuccess": "设置导入成功(已导入 {imported} 项,跳过 {skipped} 项)",
"importError": "导入设置失败",
"importInvalidFile": "请选择有效的 JSON 文件",
"importInvalidJson": "文件 JSON 格式无效",
"importInvalidStructure": "设置文件结构无效"
},
"systemStatus": {
"title": "CCW 安装",

View File

@@ -3,7 +3,7 @@
// ========================================
// Application settings and configuration with CLI tools management
import { useState, useCallback, useEffect } from 'react';
import { useState, useCallback, useEffect, useRef } from 'react';
import { useIntl } from 'react-intl';
import {
Settings,
@@ -30,6 +30,8 @@ import {
File,
ArrowUpCircle,
Save,
Download,
Upload,
} from 'lucide-react';
import { Card } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
@@ -54,7 +56,10 @@ import {
useCliToolStatus,
useCcwInstallations,
useUpgradeCcwInstallation,
useExportSettings,
useImportSettings,
} from '@/hooks/useSystemSettings';
import type { ExportedSettings } from '@/lib/api';
import { RemoteNotificationSection } from '@/components/settings/RemoteNotificationSection';
import { A2UIPreferencesSection } from '@/components/settings/A2UIPreferencesSection';
@@ -520,6 +525,72 @@ function ResponseLanguageSection() {
const { data: cliEnhStatus, isLoading: cliEnhLoading } = useCodexCliEnhancementStatus();
const { toggle: toggleCliEnh, isPending: cliEnhToggling } = useToggleCodexCliEnhancement();
const { refresh: refreshCliEnh, isPending: refreshing } = useRefreshCodexCliEnhancement();
const { exportSettings: doExport, isPending: exporting } = useExportSettings();
const { importSettings: doImport, isPending: importing } = useImportSettings();
const fileInputRef = useRef<HTMLInputElement>(null);
const handleExport = useCallback(async () => {
try {
const data = await doExport();
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
a.href = url;
a.download = `ccw-settings-${timestamp}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
toast.success(formatMessage({ id: 'settings.responseLanguage.exportSuccess' }));
} catch (error) {
toast.error(formatMessage({ id: 'settings.responseLanguage.exportError' }));
}
}, [doExport, formatMessage]);
const handleFileImport = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
// Reset file input so the same file can be re-selected
e.target.value = '';
// Validate file type
if (!file.name.endsWith('.json') && file.type !== 'application/json') {
toast.error(formatMessage({ id: 'settings.responseLanguage.importInvalidFile' }));
return;
}
try {
const text = await file.text();
const data = JSON.parse(text) as ExportedSettings;
// Validate basic structure
if (!data.version || !data.settings) {
toast.error(formatMessage({ id: 'settings.responseLanguage.importInvalidStructure' }));
return;
}
const result = await doImport(data);
if (result.success) {
toast.success(
formatMessage(
{ id: 'settings.responseLanguage.importSuccess' },
{ imported: result.imported, skipped: result.skipped }
)
);
} else {
toast.error(formatMessage({ id: 'settings.responseLanguage.importError' }));
}
} catch (error) {
if (error instanceof SyntaxError) {
toast.error(formatMessage({ id: 'settings.responseLanguage.importInvalidJson' }));
} else {
toast.error(formatMessage({ id: 'settings.responseLanguage.importError' }));
}
}
}, [doImport, formatMessage]);
return (
<Card className="p-6">
@@ -542,9 +613,17 @@ function ResponseLanguageSection() {
disabled={chineseLoading || chineseToggling}
onClick={() => toggleChinese(!chineseStatus?.claudeEnabled, 'claude')}
>
{chineseStatus?.claudeEnabled
? formatMessage({ id: 'settings.responseLanguage.enabled' })
: formatMessage({ id: 'settings.responseLanguage.disabled' })}
{chineseStatus?.claudeEnabled ? (
<>
<Check className="w-4 h-4 mr-1" />
{formatMessage({ id: 'settings.responseLanguage.enabled' })}
</>
) : (
<>
<X className="w-4 h-4 mr-1" />
{formatMessage({ id: 'settings.responseLanguage.disabled' })}
</>
)}
</Button>
</div>
<p className="text-xs text-muted-foreground">
@@ -566,9 +645,17 @@ function ResponseLanguageSection() {
disabled={chineseLoading || chineseToggling}
onClick={() => toggleChinese(!chineseStatus?.codexEnabled, 'codex')}
>
{chineseStatus?.codexEnabled
? formatMessage({ id: 'settings.responseLanguage.enabled' })
: formatMessage({ id: 'settings.responseLanguage.disabled' })}
{chineseStatus?.codexEnabled ? (
<>
<Check className="w-4 h-4 mr-1" />
{formatMessage({ id: 'settings.responseLanguage.enabled' })}
</>
) : (
<>
<X className="w-4 h-4 mr-1" />
{formatMessage({ id: 'settings.responseLanguage.disabled' })}
</>
)}
</Button>
</div>
<p className="text-xs text-muted-foreground">
@@ -596,9 +683,17 @@ function ResponseLanguageSection() {
disabled={windowsLoading || windowsToggling}
onClick={() => toggleWindows(!windowsStatus?.enabled)}
>
{windowsStatus?.enabled
? formatMessage({ id: 'settings.responseLanguage.enabled' })
: formatMessage({ id: 'settings.responseLanguage.disabled' })}
{windowsStatus?.enabled ? (
<>
<Check className="w-4 h-4 mr-1" />
{formatMessage({ id: 'settings.responseLanguage.enabled' })}
</>
) : (
<>
<X className="w-4 h-4 mr-1" />
{formatMessage({ id: 'settings.responseLanguage.disabled' })}
</>
)}
</Button>
</div>
<p className="text-xs text-muted-foreground">
@@ -634,9 +729,17 @@ function ResponseLanguageSection() {
disabled={cliEnhLoading || cliEnhToggling}
onClick={() => toggleCliEnh(!cliEnhStatus?.enabled)}
>
{cliEnhStatus?.enabled
? formatMessage({ id: 'settings.responseLanguage.enabled' })
: formatMessage({ id: 'settings.responseLanguage.disabled' })}
{cliEnhStatus?.enabled ? (
<>
<Check className="w-4 h-4 mr-1" />
{formatMessage({ id: 'settings.responseLanguage.enabled' })}
</>
) : (
<>
<X className="w-4 h-4 mr-1" />
{formatMessage({ id: 'settings.responseLanguage.disabled' })}
</>
)}
</Button>
</div>
</div>
@@ -650,6 +753,62 @@ function ResponseLanguageSection() {
)}
</div>
</div>
{/* Export/Import Actions */}
<div className="mt-4 pt-4 border-t border-border">
<div className="flex items-center justify-between">
<p className="text-xs text-muted-foreground">
{formatMessage({ id: 'settings.responseLanguage.exportImportHint' })}
</p>
<div className="flex items-center gap-2">
<input
ref={fileInputRef}
type="file"
accept=".json,application/json"
onChange={handleFileImport}
className="hidden"
/>
<Button
variant="outline"
size="sm"
className="h-7"
disabled={importing}
onClick={() => fileInputRef.current?.click()}
>
{importing ? (
<>
<div className="w-3.5 h-3.5 border-2 border-border border-t-accent rounded-full animate-spin mr-1" />
{formatMessage({ id: 'settings.responseLanguage.importing' })}
</>
) : (
<>
<Upload className="w-3.5 h-3.5 mr-1" />
{formatMessage({ id: 'settings.responseLanguage.import' })}
</>
)}
</Button>
<Button
variant="outline"
size="sm"
className="h-7"
disabled={exporting}
onClick={handleExport}
>
{exporting ? (
<>
<div className="w-3.5 h-3.5 border-2 border-border border-t-accent rounded-full animate-spin mr-1" />
{formatMessage({ id: 'settings.responseLanguage.exporting' })}
</>
) : (
<>
<Download className="w-3.5 h-3.5 mr-1" />
{formatMessage({ id: 'settings.responseLanguage.export' })}
</>
)}
</Button>
</div>
</div>
</div>
</Card>
);
}

View File

@@ -14,40 +14,30 @@ import type {
A2UIPreferences,
} from '../types/store';
// Default CLI tools configuration
// Default CLI tools configuration - no model defaults, models come from user's cli-tools.json
const defaultCliTools: Record<string, CliToolConfig> = {
gemini: {
enabled: true,
primaryModel: 'gemini-2.5-pro',
secondaryModel: 'gemini-2.5-flash',
tags: ['analysis', 'debug'],
type: 'builtin',
},
qwen: {
enabled: true,
primaryModel: 'coder-model',
secondaryModel: 'coder-model',
tags: [],
type: 'builtin',
},
codex: {
enabled: true,
primaryModel: 'gpt-5.2',
secondaryModel: 'gpt-5.2',
tags: [],
type: 'builtin',
},
claude: {
enabled: true,
primaryModel: 'sonnet',
secondaryModel: 'haiku',
tags: [],
type: 'builtin',
},
opencode: {
enabled: true,
primaryModel: 'opencode/glm-4.7-free',
secondaryModel: 'opencode/glm-4.7-free',
tags: [],
type: 'builtin',
},

View File

@@ -387,8 +387,8 @@ export type WorkflowStore = WorkflowState & WorkflowActions;
export interface CliToolConfig {
enabled: boolean;
primaryModel: string;
secondaryModel: string;
primaryModel?: string;
secondaryModel?: string;
tags: string[];
type: 'builtin' | 'cli-wrapper' | 'api-endpoint';
/** Path to .env file for environment variables (gemini/qwen/opencode) */