mirror of
https://github.com/catlog22/Claude-Code-Workflow.git
synced 2026-02-28 09:23:08 +08:00
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:
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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 ==========
|
||||
|
||||
/**
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 安装",
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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',
|
||||
},
|
||||
|
||||
@@ -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) */
|
||||
|
||||
@@ -16,6 +16,9 @@ import {
|
||||
SettingsListResponse,
|
||||
SettingsOperationResult,
|
||||
SaveEndpointRequest,
|
||||
ExportedSettings,
|
||||
ImportOptions,
|
||||
ImportResult,
|
||||
validateSettings,
|
||||
createDefaultSettings
|
||||
} from '../types/cli-settings.js';
|
||||
@@ -471,3 +474,152 @@ export function validateEndpointName(name: string): { valid: boolean; error?: st
|
||||
|
||||
return { valid: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Export all CLI endpoint settings
|
||||
* Returns an ExportedSettings object with version, timestamp, and all endpoints
|
||||
*/
|
||||
export function exportAllSettings(): ExportedSettings {
|
||||
const { endpoints } = listAllSettings();
|
||||
|
||||
return {
|
||||
version: '1.0.0',
|
||||
timestamp: new Date().toISOString(),
|
||||
endpoints
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Import settings from an ExportedSettings object
|
||||
* Validates and applies imported settings with configurable conflict resolution
|
||||
*/
|
||||
export function importSettings(
|
||||
exportedData: unknown,
|
||||
options: ImportOptions = {}
|
||||
): ImportResult {
|
||||
const {
|
||||
conflictStrategy = 'skip',
|
||||
skipInvalid = true,
|
||||
disableImported = false
|
||||
} = options;
|
||||
|
||||
const result: ImportResult = {
|
||||
success: false,
|
||||
imported: 0,
|
||||
skipped: 0,
|
||||
errors: [],
|
||||
importedIds: []
|
||||
};
|
||||
|
||||
// Validate exported data structure
|
||||
if (!exportedData || typeof exportedData !== 'object') {
|
||||
result.errors.push('Invalid export data: must be an object');
|
||||
return result;
|
||||
}
|
||||
|
||||
const data = exportedData as Record<string, unknown>;
|
||||
|
||||
// Check for required fields
|
||||
if (!('endpoints' in data) || !Array.isArray(data.endpoints)) {
|
||||
result.errors.push('Invalid export data: missing or invalid endpoints array');
|
||||
return result;
|
||||
}
|
||||
|
||||
// Validate version (for future migration support)
|
||||
if ('version' in data && typeof data.version !== 'string') {
|
||||
result.errors.push('Invalid export data: version must be a string');
|
||||
return result;
|
||||
}
|
||||
|
||||
const endpoints = data.endpoints as unknown[];
|
||||
const existingIndex = loadIndex();
|
||||
|
||||
for (let i = 0; i < endpoints.length; i++) {
|
||||
const ep = endpoints[i];
|
||||
|
||||
// Validate endpoint structure
|
||||
if (!ep || typeof ep !== 'object') {
|
||||
if (!skipInvalid) {
|
||||
result.errors.push(`Endpoint at index ${i}: invalid structure`);
|
||||
}
|
||||
result.skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const endpoint = ep as Record<string, unknown>;
|
||||
|
||||
// Check required fields
|
||||
if (!endpoint.name || typeof endpoint.name !== 'string') {
|
||||
if (!skipInvalid) {
|
||||
result.errors.push(`Endpoint at index ${i}: missing or invalid name`);
|
||||
}
|
||||
result.skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!endpoint.settings || typeof endpoint.settings !== 'object') {
|
||||
if (!skipInvalid) {
|
||||
result.errors.push(`Endpoint at index ${i}: missing or invalid settings`);
|
||||
}
|
||||
result.skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Validate settings using provider-aware validation
|
||||
const provider: CliProvider = (endpoint.provider as CliProvider) || 'claude';
|
||||
if (!validateSettings(endpoint.settings, provider)) {
|
||||
if (!skipInvalid) {
|
||||
result.errors.push(`Endpoint "${endpoint.name}": invalid settings format`);
|
||||
}
|
||||
result.skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Determine endpoint ID
|
||||
const endpointId = (endpoint.id as string) || generateEndpointId();
|
||||
const exists = existingIndex.has(endpointId);
|
||||
|
||||
// Handle conflicts
|
||||
if (exists && conflictStrategy === 'skip') {
|
||||
result.skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Prepare import request
|
||||
const importRequest: SaveEndpointRequest = {
|
||||
id: endpointId,
|
||||
name: endpoint.name as string,
|
||||
description: endpoint.description as string | undefined,
|
||||
provider,
|
||||
settings: endpoint.settings as CliSettings,
|
||||
enabled: disableImported ? false : (endpoint.enabled as boolean) ?? true
|
||||
};
|
||||
|
||||
// For merge strategy, combine with existing if applicable
|
||||
if (exists && conflictStrategy === 'merge') {
|
||||
const existing = loadEndpointSettings(endpointId);
|
||||
if (existing) {
|
||||
importRequest.settings = {
|
||||
...existing.settings,
|
||||
...(endpoint.settings as CliSettings)
|
||||
} as CliSettings;
|
||||
importRequest.name = (endpoint.name as string) || existing.name;
|
||||
importRequest.description = (endpoint.description as string) ?? existing.description;
|
||||
}
|
||||
}
|
||||
|
||||
// Save the endpoint
|
||||
const saveResult = saveEndpointSettings(importRequest);
|
||||
|
||||
if (saveResult.success) {
|
||||
result.imported++;
|
||||
result.importedIds!.push(endpointId);
|
||||
} else {
|
||||
result.errors.push(`Endpoint "${endpoint.name}": ${saveResult.message || 'Failed to save'}`);
|
||||
result.skipped++;
|
||||
}
|
||||
}
|
||||
|
||||
result.success = result.imported > 0;
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -12,9 +12,11 @@ import {
|
||||
toggleEndpointEnabled,
|
||||
getSettingsFilePath,
|
||||
ensureSettingsDir,
|
||||
sanitizeEndpointId
|
||||
sanitizeEndpointId,
|
||||
exportAllSettings,
|
||||
importSettings
|
||||
} from '../../config/cli-settings-manager.js';
|
||||
import type { SaveEndpointRequest } from '../../types/cli-settings.js';
|
||||
import type { SaveEndpointRequest, ImportOptions } from '../../types/cli-settings.js';
|
||||
import { validateSettings } from '../../types/cli-settings.js';
|
||||
import { syncBuiltinToolsAvailability, getBuiltinToolsSyncReport } from '../../tools/claude-cli-tools.js';
|
||||
|
||||
@@ -275,5 +277,62 @@ export async function handleCliSettingsRoutes(ctx: RouteContext): Promise<boolea
|
||||
return true;
|
||||
}
|
||||
|
||||
// ========== EXPORT SETTINGS ==========
|
||||
// GET /api/cli/settings/export
|
||||
if (pathname === '/api/cli/settings/export' && req.method === 'GET') {
|
||||
try {
|
||||
const exportData = exportAllSettings();
|
||||
const jsonContent = JSON.stringify(exportData, null, 2);
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').substring(0, 19);
|
||||
const filename = `cli-settings-export-${timestamp}.json`;
|
||||
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
'Content-Length': Buffer.byteLength(jsonContent, 'utf-8')
|
||||
});
|
||||
res.end(jsonContent);
|
||||
} catch (err) {
|
||||
res.writeHead(500, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify({ error: (err as Error).message }));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ========== IMPORT SETTINGS ==========
|
||||
// POST /api/cli/settings/import
|
||||
if (pathname === '/api/cli/settings/import' && req.method === 'POST') {
|
||||
handlePostRequest(req, res, async (body: unknown) => {
|
||||
try {
|
||||
// Extract import options and data from request
|
||||
const request = body as { data?: unknown; options?: ImportOptions };
|
||||
|
||||
if (!request.data) {
|
||||
return { error: 'Missing export data in request body', status: 400 };
|
||||
}
|
||||
|
||||
const result = importSettings(request.data, request.options);
|
||||
|
||||
if (result.success) {
|
||||
// Broadcast import event
|
||||
broadcastToClients({
|
||||
type: 'CLI_SETTINGS_IMPORTED',
|
||||
payload: {
|
||||
imported: result.imported,
|
||||
skipped: result.skipped,
|
||||
importedIds: result.importedIds,
|
||||
timestamp: new Date().toISOString()
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (err) {
|
||||
return { error: (err as Error).message, status: 500 };
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -335,11 +335,15 @@ export class CliSessionManager {
|
||||
}
|
||||
|
||||
// Merge endpoint env vars with process.env (endpoint overrides process.env)
|
||||
const spawnEnv: Record<string, string> = {
|
||||
const spawnEnv: Record<string, string | undefined> = {
|
||||
...(process.env as Record<string, string>),
|
||||
...endpointEnv,
|
||||
};
|
||||
|
||||
// Unset CLAUDECODE to allow nested Claude Code sessions (SDK/subagent use case)
|
||||
// See: https://github.com/anthropics/claude-agent-sdk-python/issues/573
|
||||
delete spawnEnv.CLAUDECODE;
|
||||
|
||||
let pty: nodePty.IPty;
|
||||
try {
|
||||
pty = nodePty.spawn(file, args, {
|
||||
|
||||
@@ -136,46 +136,32 @@ export interface ClaudeCliCombinedConfig extends ClaudeCliToolsConfig {
|
||||
|
||||
// ========== Default Config ==========
|
||||
|
||||
// Default tools config - no model defaults, models come from user's cli-tools.json
|
||||
const DEFAULT_TOOLS_CONFIG: ClaudeCliToolsConfig = {
|
||||
version: '3.4.0',
|
||||
tools: {
|
||||
gemini: {
|
||||
enabled: true,
|
||||
primaryModel: 'gemini-2.5-pro',
|
||||
secondaryModel: 'gemini-2.5-flash',
|
||||
availableModels: ['gemini-2.5-pro', 'gemini-2.5-flash', 'gemini-2.0-flash', 'gemini-2.0-flash-thinking', 'gemini-1.5-pro'],
|
||||
tags: [],
|
||||
type: 'builtin'
|
||||
},
|
||||
qwen: {
|
||||
enabled: true,
|
||||
primaryModel: 'coder-model',
|
||||
secondaryModel: 'coder-model',
|
||||
availableModels: ['coder-model', 'vision-model', 'qwen-2.5-coder', 'qwen-2.5-72b'],
|
||||
tags: [],
|
||||
type: 'builtin'
|
||||
},
|
||||
codex: {
|
||||
enabled: true,
|
||||
primaryModel: 'gpt-5.2',
|
||||
secondaryModel: 'gpt-5.2',
|
||||
availableModels: ['gpt-5.2', 'gpt-5', 'gpt5-codex', 'o3', 'o1'],
|
||||
tags: [],
|
||||
type: 'builtin'
|
||||
},
|
||||
claude: {
|
||||
enabled: true,
|
||||
primaryModel: 'sonnet',
|
||||
secondaryModel: 'haiku',
|
||||
availableModels: ['opus', 'sonnet', 'haiku'],
|
||||
tags: [],
|
||||
type: 'builtin'
|
||||
},
|
||||
opencode: {
|
||||
enabled: true,
|
||||
primaryModel: 'opencode/glm-4.7-free',
|
||||
secondaryModel: 'opencode/glm-4.7-free',
|
||||
availableModels: ['opencode/glm-4.7-free', 'opencode/deepseek-v3-free'],
|
||||
tags: [],
|
||||
type: 'builtin'
|
||||
}
|
||||
|
||||
@@ -958,12 +958,16 @@ async function executeCliTool(
|
||||
|
||||
// Merge custom env with process.env (custom env takes precedence)
|
||||
// Also include rulesEnv for $PROTO and $TMPL template variables
|
||||
const spawnEnv = {
|
||||
const spawnEnv: Record<string, string | undefined> = {
|
||||
...process.env,
|
||||
...customEnv,
|
||||
...(rulesEnv || {})
|
||||
};
|
||||
|
||||
// Unset CLAUDECODE to allow nested Claude Code sessions (SDK/subagent use case)
|
||||
// See: https://github.com/anthropics/claude-agent-sdk-python/issues/573
|
||||
delete spawnEnv.CLAUDECODE;
|
||||
|
||||
debugLog('SPAWN', `Spawning process`, {
|
||||
command,
|
||||
args,
|
||||
|
||||
@@ -23,13 +23,6 @@ const CODE_EXTENSIONS = [
|
||||
'.ts', '.tsx', '.js', '.jsx', '.py', '.sh', '.go', '.rs'
|
||||
];
|
||||
|
||||
// Default models for each tool
|
||||
const DEFAULT_MODELS: Record<string, string> = {
|
||||
gemini: 'gemini-2.5-flash',
|
||||
qwen: 'coder-model',
|
||||
codex: 'gpt5-codex'
|
||||
};
|
||||
|
||||
// Template paths (relative to user home directory)
|
||||
const TEMPLATE_BASE = '~/.ccw/workflows/cli-templates/prompts/documentation';
|
||||
|
||||
@@ -141,20 +134,21 @@ function buildCliCommand(tool: string, promptFile: string, model: string): strin
|
||||
// Build the cat/read command based on platform
|
||||
const catCmd = isWindows ? `Get-Content -Raw "${normalizedPath}" | ` : `cat "${normalizedPath}" | `;
|
||||
|
||||
// Build model flag only if model is specified
|
||||
const modelFlag = model ? ` -m "${model}"` : '';
|
||||
|
||||
switch (tool) {
|
||||
case 'qwen':
|
||||
return model === 'coder-model'
|
||||
? `${catCmd}qwen --yolo`
|
||||
: `${catCmd}qwen -m "${model}" --yolo`;
|
||||
return `${catCmd}qwen${modelFlag} --yolo`;
|
||||
case 'codex':
|
||||
// codex uses different syntax - prompt as exec argument
|
||||
if (isWindows) {
|
||||
return `codex --full-auto exec (Get-Content -Raw "${normalizedPath}") -m "${model}" --skip-git-repo-check -s danger-full-access`;
|
||||
return `codex --full-auto exec (Get-Content -Raw "${normalizedPath}")${modelFlag} --skip-git-repo-check -s danger-full-access`;
|
||||
}
|
||||
return `codex --full-auto exec "$(cat "${normalizedPath}")" -m "${model}" --skip-git-repo-check -s danger-full-access`;
|
||||
return `codex --full-auto exec "$(cat "${normalizedPath}")"${modelFlag} --skip-git-repo-check -s danger-full-access`;
|
||||
case 'gemini':
|
||||
default:
|
||||
return `${catCmd}gemini -m "${model}" --yolo`;
|
||||
return `${catCmd}gemini${modelFlag} --yolo`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -273,7 +267,8 @@ export async function handler(params: Record<string, unknown>): Promise<ToolResu
|
||||
try {
|
||||
actualModel = getSecondaryModel(process.cwd(), tool);
|
||||
} catch {
|
||||
actualModel = DEFAULT_MODELS[tool] || DEFAULT_MODELS.gemini;
|
||||
// If config not available, don't specify model - let CLI decide
|
||||
actualModel = '';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -258,3 +258,43 @@ export function validateSettings(settings: unknown, provider?: CliProvider): set
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exported settings format for backup/restore
|
||||
*/
|
||||
export interface ExportedSettings {
|
||||
/** Export format version for future migrations */
|
||||
version: string;
|
||||
/** Export timestamp (ISO 8601) */
|
||||
timestamp: string;
|
||||
/** All endpoint settings */
|
||||
endpoints: EndpointSettings[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Import options for conflict resolution
|
||||
*/
|
||||
export interface ImportOptions {
|
||||
/** How to handle conflicts: 'skip' keeps existing, 'overwrite' replaces, 'merge' combines */
|
||||
conflictStrategy?: 'skip' | 'overwrite' | 'merge';
|
||||
/** Whether to skip invalid endpoints (default: true) */
|
||||
skipInvalid?: boolean;
|
||||
/** Whether to disable all imported endpoints (default: false) */
|
||||
disableImported?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Import result summary
|
||||
*/
|
||||
export interface ImportResult {
|
||||
/** Whether import was successful overall */
|
||||
success: boolean;
|
||||
/** Number of endpoints imported successfully */
|
||||
imported: number;
|
||||
/** Number of endpoints skipped (conflicts or validation errors) */
|
||||
skipped: number;
|
||||
/** Detailed error messages for failed imports */
|
||||
errors: string[];
|
||||
/** List of imported endpoint IDs */
|
||||
importedIds?: string[];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user