mirror of
https://github.com/catlog22/Claude-Code-Workflow.git
synced 2026-02-27 09:13:07 +08:00
feat(cli-settings): support multi-provider settings for Claude, Codex, and Gemini
Decouple CLI settings architecture from Claude-only to support multiple
providers. Each provider has independent settings UI and backend handling.
- Add CliProvider type discriminator ('claude' | 'codex' | 'gemini')
- Add CodexCliSettings (profile, authJson, configToml) and GeminiCliSettings types
- Update EndpointSettings with provider field (defaults 'claude' for backward compat)
- Refactor CliSettingsModal with provider selector and provider-specific forms
- Remove includeCoAuthoredBy field across all layers
- Extend CliConfigModal to show Config Profile for all tools (not just claude)
- Add provider-aware argument injection in cli-session-manager (--settings/--profile/env)
- Rename addClaudeCustomEndpoint to addCustomEndpoint (old name kept as deprecated alias)
- Replace providerBasedCount/directCount with per-provider counts in useCliSettings hook
- Update CliSettingsList with provider badges and per-provider stat cards
- Add Codex and Gemini test cases for validateSettings and createDefaultSettings
This commit is contained in:
@@ -63,23 +63,18 @@ function CliSettingsCard({
|
||||
}: CliSettingsCardProps) {
|
||||
const { formatMessage } = useIntl();
|
||||
|
||||
// Determine mode based on settings
|
||||
const isProviderBased = Boolean(
|
||||
cliSettings.settings.env.ANTHROPIC_BASE_URL &&
|
||||
!cliSettings.settings.env.ANTHROPIC_BASE_URL.includes('api.anthropic.com')
|
||||
);
|
||||
|
||||
const getModeBadge = () => {
|
||||
if (isProviderBased) {
|
||||
return (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{formatMessage({ id: 'apiSettings.cliSettings.providerBased' })}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
// Display provider badge
|
||||
const getProviderBadge = () => {
|
||||
const provider = cliSettings.provider || 'claude';
|
||||
const variants: Record<string, { variant: 'secondary' | 'outline' | 'default'; label: string }> = {
|
||||
claude: { variant: 'secondary', label: 'Claude' },
|
||||
codex: { variant: 'outline', label: 'Codex' },
|
||||
gemini: { variant: 'default', label: 'Gemini' },
|
||||
};
|
||||
const config = variants[provider] || variants.claude;
|
||||
return (
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{formatMessage({ id: 'apiSettings.cliSettings.direct' })}
|
||||
<Badge variant={config.variant} className="text-xs">
|
||||
{config.label}
|
||||
</Badge>
|
||||
);
|
||||
};
|
||||
@@ -91,6 +86,12 @@ function CliSettingsCard({
|
||||
return <Badge variant="success">{formatMessage({ id: 'apiSettings.common.enabled' })}</Badge>;
|
||||
};
|
||||
|
||||
// Get provider-appropriate endpoint URL for display
|
||||
const endpointUrl = (() => {
|
||||
const env = cliSettings.settings.env;
|
||||
return env.ANTHROPIC_BASE_URL || env.OPENAI_BASE_URL || '';
|
||||
})();
|
||||
|
||||
return (
|
||||
<Card className="p-4">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
@@ -99,7 +100,7 @@ function CliSettingsCard({
|
||||
<div className="flex items-center gap-3">
|
||||
<h3 className="text-lg font-semibold text-foreground truncate">{cliSettings.name}</h3>
|
||||
{getStatusBadge()}
|
||||
{getModeBadge()}
|
||||
{getProviderBadge()}
|
||||
</div>
|
||||
{cliSettings.description && (
|
||||
<p className="text-sm text-muted-foreground mt-1">{cliSettings.description}</p>
|
||||
@@ -107,17 +108,12 @@ function CliSettingsCard({
|
||||
<div className="flex items-center gap-4 mt-2 text-sm text-muted-foreground">
|
||||
<span className="flex items-center gap-1">
|
||||
<Settings className="w-3 h-3" />
|
||||
{cliSettings.settings.model || 'sonnet'}
|
||||
{cliSettings.settings.model || 'default'}
|
||||
</span>
|
||||
{cliSettings.settings.env.ANTHROPIC_BASE_URL && (
|
||||
<span className="flex items-center gap-1 truncate max-w-[200px]" title={cliSettings.settings.env.ANTHROPIC_BASE_URL}>
|
||||
{endpointUrl && (
|
||||
<span className="flex items-center gap-1 truncate max-w-[200px]" title={endpointUrl}>
|
||||
<LinkIcon className="w-3 h-3 flex-shrink-0" />
|
||||
{cliSettings.settings.env.ANTHROPIC_BASE_URL}
|
||||
</span>
|
||||
)}
|
||||
{cliSettings.settings.includeCoAuthoredBy !== undefined && (
|
||||
<span>
|
||||
{formatMessage({ id: 'apiSettings.cliSettings.coAuthoredBy' })}: {formatMessage({ id: cliSettings.settings.includeCoAuthoredBy ? 'common.yes' : 'common.no' })}
|
||||
{endpointUrl}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
@@ -168,8 +164,7 @@ export function CliSettingsList({
|
||||
cliSettings,
|
||||
totalCount,
|
||||
enabledCount,
|
||||
providerBasedCount,
|
||||
directCount,
|
||||
providerCounts,
|
||||
isLoading,
|
||||
refetch,
|
||||
} = useCliSettings();
|
||||
@@ -219,7 +214,7 @@ export function CliSettingsList({
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Stats Cards */}
|
||||
<div className="grid grid-cols-4 gap-4">
|
||||
<div className="grid grid-cols-2 sm:grid-cols-5 gap-4">
|
||||
<Card className="p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Settings className="w-5 h-5 text-primary" />
|
||||
@@ -240,21 +235,21 @@ export function CliSettingsList({
|
||||
</Card>
|
||||
<Card className="p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<LinkIcon className="w-5 h-5 text-blue-500" />
|
||||
<span className="text-2xl font-bold">{providerBasedCount}</span>
|
||||
<span className="text-2xl font-bold">{providerCounts.claude || 0}</span>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{formatMessage({ id: 'apiSettings.cliSettings.providerBased' })}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">Claude</p>
|
||||
</Card>
|
||||
<Card className="p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Settings className="w-5 h-5 text-orange-500" />
|
||||
<span className="text-2xl font-bold">{directCount}</span>
|
||||
<span className="text-2xl font-bold">{providerCounts.codex || 0}</span>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{formatMessage({ id: 'apiSettings.cliSettings.direct' })}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">Codex</p>
|
||||
</Card>
|
||||
<Card className="p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-2xl font-bold">{providerCounts.gemini || 0}</span>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mt-1">Gemini</p>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -26,8 +26,10 @@ import {
|
||||
SelectValue,
|
||||
} from '@/components/ui/Select';
|
||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/RadioGroup';
|
||||
import { useConfigStore, selectCliTools } from '@/stores/configStore';
|
||||
import { useCliSettings } from '@/hooks/useApiSettings';
|
||||
|
||||
export type CliTool = 'claude' | 'gemini' | 'qwen' | 'codex' | 'opencode';
|
||||
export type CliTool = string;
|
||||
export type LaunchMode = 'default' | 'yolo';
|
||||
export type ShellKind = 'bash' | 'pwsh' | 'cmd';
|
||||
|
||||
@@ -39,6 +41,8 @@ export interface CliSessionConfig {
|
||||
workingDir: string;
|
||||
/** Session tag for grouping (auto-generated if not provided) */
|
||||
tag: string;
|
||||
/** CLI Settings endpoint ID for custom API configuration */
|
||||
settingsEndpointId?: string;
|
||||
}
|
||||
|
||||
export interface CliConfigModalProps {
|
||||
@@ -48,23 +52,13 @@ export interface CliConfigModalProps {
|
||||
onCreateSession: (config: CliSessionConfig) => Promise<void>;
|
||||
}
|
||||
|
||||
const CLI_TOOLS: CliTool[] = ['claude', 'gemini', 'qwen', 'codex', 'opencode'];
|
||||
|
||||
const MODEL_OPTIONS: Record<CliTool, string[]> = {
|
||||
claude: ['sonnet', 'haiku'],
|
||||
gemini: ['gemini-2.5-pro', 'gemini-2.5-flash'],
|
||||
qwen: ['coder-model'],
|
||||
codex: ['gpt-5.2'],
|
||||
opencode: ['opencode/glm-4.7-free'],
|
||||
};
|
||||
|
||||
const AUTO_MODEL_VALUE = '__auto__';
|
||||
|
||||
/**
|
||||
* Generate a tag name: {tool}-{HHmmss}
|
||||
* Example: gemini-143052
|
||||
*/
|
||||
function generateTag(tool: CliTool): string {
|
||||
function generateTag(tool: string): string {
|
||||
const now = new Date();
|
||||
const time = now.toTimeString().slice(0, 8).replace(/:/g, '');
|
||||
return `${tool}-${time}`;
|
||||
@@ -78,8 +72,18 @@ export function CliConfigModal({
|
||||
}: CliConfigModalProps) {
|
||||
const { formatMessage } = useIntl();
|
||||
|
||||
// Dynamic tool data from configStore
|
||||
const cliTools = useConfigStore(selectCliTools);
|
||||
const enabledTools = React.useMemo(
|
||||
() =>
|
||||
Object.entries(cliTools)
|
||||
.filter(([, config]) => config.enabled)
|
||||
.map(([key]) => key),
|
||||
[cliTools]
|
||||
);
|
||||
|
||||
const [tool, setTool] = React.useState<CliTool>('gemini');
|
||||
const [model, setModel] = React.useState<string | undefined>(MODEL_OPTIONS.gemini[0]);
|
||||
const [model, setModel] = React.useState<string | undefined>(undefined);
|
||||
const [launchMode, setLaunchMode] = React.useState<LaunchMode>('yolo');
|
||||
// Default to 'cmd' on Windows for better compatibility with npm CLI tools (.cmd files)
|
||||
const [preferredShell, setPreferredShell] = React.useState<ShellKind>(
|
||||
@@ -91,7 +95,46 @@ export function CliConfigModal({
|
||||
const [isSubmitting, setIsSubmitting] = React.useState(false);
|
||||
const [error, setError] = React.useState<string | null>(null);
|
||||
|
||||
const modelOptions = React.useMemo(() => MODEL_OPTIONS[tool] ?? [], [tool]);
|
||||
// CLI Settings integration (for all tools)
|
||||
const { cliSettings } = useCliSettings({ enabled: true });
|
||||
|
||||
// Map tool names to provider types for filtering
|
||||
const toolProviderMap: Record<string, string> = {
|
||||
claude: 'claude',
|
||||
codex: 'codex',
|
||||
gemini: 'gemini',
|
||||
};
|
||||
const currentProvider = toolProviderMap[tool] || tool;
|
||||
|
||||
const enabledCliSettings = React.useMemo(
|
||||
() => (cliSettings || []).filter((s) => s.enabled && (s.provider || 'claude') === currentProvider),
|
||||
[cliSettings, currentProvider]
|
||||
);
|
||||
const [settingsEndpointId, setSettingsEndpointId] = React.useState<string | undefined>(undefined);
|
||||
|
||||
// Reset settingsEndpointId when tool changes
|
||||
React.useEffect(() => {
|
||||
setSettingsEndpointId(undefined);
|
||||
}, [tool]);
|
||||
|
||||
// Derive model options from configStore + CLI Settings profile override
|
||||
const modelOptions = React.useMemo(() => {
|
||||
// If a CLI Settings profile is selected and has availableModels, use those
|
||||
if (settingsEndpointId) {
|
||||
const endpoint = enabledCliSettings.find((s) => s.id === settingsEndpointId);
|
||||
if (endpoint?.settings.availableModels?.length) {
|
||||
return endpoint.settings.availableModels;
|
||||
}
|
||||
}
|
||||
const toolConfig = cliTools[tool];
|
||||
if (!toolConfig) return [];
|
||||
if (toolConfig.availableModels?.length) return toolConfig.availableModels;
|
||||
const models = [toolConfig.primaryModel];
|
||||
if (toolConfig.secondaryModel && toolConfig.secondaryModel !== toolConfig.primaryModel) {
|
||||
models.push(toolConfig.secondaryModel);
|
||||
}
|
||||
return models;
|
||||
}, [cliTools, tool, settingsEndpointId, enabledCliSettings]);
|
||||
|
||||
// Generate new tag when modal opens or tool changes
|
||||
const regenerateTag = React.useCallback(() => {
|
||||
@@ -104,6 +147,7 @@ export function CliConfigModal({
|
||||
const nextWorkingDir = defaultWorkingDir ?? '';
|
||||
setWorkingDir(nextWorkingDir);
|
||||
setError(null);
|
||||
setSettingsEndpointId(undefined);
|
||||
regenerateTag();
|
||||
}, [isOpen, defaultWorkingDir, regenerateTag]);
|
||||
|
||||
@@ -113,12 +157,23 @@ export function CliConfigModal({
|
||||
const suffix = tag.split('-').pop() || '';
|
||||
setTag(`${tool}-${suffix}`);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- only re-run when tool changes, reading tag intentionally stale
|
||||
}, [tool]);
|
||||
|
||||
// Sync initial model when tool/modelOptions change
|
||||
React.useEffect(() => {
|
||||
if (modelOptions.length > 0 && (!model || !modelOptions.includes(model))) {
|
||||
setModel(modelOptions[0]);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- only re-run when modelOptions changes
|
||||
}, [modelOptions]);
|
||||
|
||||
const handleToolChange = (nextTool: string) => {
|
||||
const next = nextTool as CliTool;
|
||||
setTool(next);
|
||||
const nextModels = MODEL_OPTIONS[next] ?? [];
|
||||
setTool(nextTool as CliTool);
|
||||
const nextConfig = cliTools[nextTool];
|
||||
const nextModels = nextConfig?.availableModels?.length
|
||||
? nextConfig.availableModels
|
||||
: [nextConfig?.primaryModel, nextConfig?.secondaryModel].filter(Boolean) as string[];
|
||||
if (!model || !nextModels.includes(model)) {
|
||||
setModel(nextModels[0]);
|
||||
}
|
||||
@@ -148,6 +203,7 @@ export function CliConfigModal({
|
||||
preferredShell,
|
||||
workingDir: dir,
|
||||
tag: finalTag,
|
||||
settingsEndpointId,
|
||||
});
|
||||
onClose();
|
||||
} catch (err) {
|
||||
@@ -209,7 +265,7 @@ export function CliConfigModal({
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{CLI_TOOLS.map((t) => (
|
||||
{enabledTools.map((t) => (
|
||||
<SelectItem key={t} value={t}>
|
||||
{t}
|
||||
</SelectItem>
|
||||
@@ -245,6 +301,45 @@ export function CliConfigModal({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Config Profile (all tools with settings) */}
|
||||
{enabledCliSettings.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="cli-config-profile">
|
||||
{formatMessage({ id: 'terminalDashboard.cliConfig.configProfile', defaultMessage: 'Config Profile' })}
|
||||
</Label>
|
||||
<Select
|
||||
value={settingsEndpointId ?? '__default__'}
|
||||
onValueChange={(v) => {
|
||||
const id = v === '__default__' ? undefined : v;
|
||||
setSettingsEndpointId(id);
|
||||
// If profile has availableModels, use those for model dropdown
|
||||
if (id) {
|
||||
const endpoint = enabledCliSettings.find((s) => s.id === id);
|
||||
if (endpoint?.settings.availableModels?.length) {
|
||||
setModel(endpoint.settings.availableModels[0]);
|
||||
}
|
||||
}
|
||||
}}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
<SelectTrigger id="cli-config-profile">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="__default__">
|
||||
{formatMessage({ id: 'terminalDashboard.cliConfig.defaultProfile', defaultMessage: 'Default' })}
|
||||
</SelectItem>
|
||||
{enabledCliSettings.map((s) => (
|
||||
<SelectItem key={s.id} value={s.id}>{s.name}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{formatMessage({ id: 'terminalDashboard.cliConfig.configProfileHint', defaultMessage: 'Select a CLI Settings profile for custom API configuration.' })}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Mode */}
|
||||
<div className="space-y-2">
|
||||
<Label>{formatMessage({ id: 'terminalDashboard.cliConfig.mode' })}</Label>
|
||||
|
||||
@@ -699,8 +699,8 @@ export interface UseCliSettingsReturn {
|
||||
cliSettings: CliSettingsEndpoint[];
|
||||
totalCount: number;
|
||||
enabledCount: number;
|
||||
providerBasedCount: number;
|
||||
directCount: number;
|
||||
/** Count per provider type */
|
||||
providerCounts: Record<string, number>;
|
||||
isLoading: boolean;
|
||||
isFetching: boolean;
|
||||
error: Error | null;
|
||||
@@ -723,13 +723,12 @@ export function useCliSettings(options: UseCliSettingsOptions = {}): UseCliSetti
|
||||
const cliSettings = query.data?.endpoints ?? [];
|
||||
const enabledCliSettings = cliSettings.filter((s) => s.enabled);
|
||||
|
||||
// Determine mode based on whether settings have providerId in description or env vars
|
||||
const providerBasedCount = cliSettings.filter((s) => {
|
||||
// Provider-based: has ANTHROPIC_BASE_URL set to provider's apiBase
|
||||
return s.settings.env.ANTHROPIC_BASE_URL && !s.settings.env.ANTHROPIC_BASE_URL.includes('api.anthropic.com');
|
||||
}).length;
|
||||
|
||||
const directCount = cliSettings.length - providerBasedCount;
|
||||
// Count settings per provider type
|
||||
const providerCounts = cliSettings.reduce<Record<string, number>>((acc, s) => {
|
||||
const provider = s.provider || 'claude';
|
||||
acc[provider] = (acc[provider] || 0) + 1;
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
const refetch = async () => {
|
||||
await query.refetch();
|
||||
@@ -743,8 +742,7 @@ export function useCliSettings(options: UseCliSettingsOptions = {}): UseCliSetti
|
||||
cliSettings,
|
||||
totalCount: cliSettings.length,
|
||||
enabledCount: enabledCliSettings.length,
|
||||
providerBasedCount,
|
||||
directCount,
|
||||
providerCounts,
|
||||
isLoading: query.isLoading,
|
||||
isFetching: query.isFetching,
|
||||
error: query.error,
|
||||
|
||||
@@ -6020,23 +6020,50 @@ export async function uninstallCcwLitellm(): Promise<{ success: boolean; message
|
||||
* CLI Settings (Claude CLI endpoint configuration)
|
||||
* Maps to backend EndpointSettings from /api/cli/settings
|
||||
*/
|
||||
/**
|
||||
* CLI Provider type
|
||||
*/
|
||||
export type CliProvider = 'claude' | 'codex' | 'gemini';
|
||||
|
||||
/**
|
||||
* Base settings fields shared across all providers
|
||||
*/
|
||||
export interface CliSettingsBase {
|
||||
env: Record<string, string | undefined>;
|
||||
model?: string;
|
||||
tags?: string[];
|
||||
availableModels?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Claude-specific settings
|
||||
*/
|
||||
export interface ClaudeCliSettingsApi extends CliSettingsBase {
|
||||
settingsFile?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Codex-specific settings
|
||||
*/
|
||||
export interface CodexCliSettingsApi extends CliSettingsBase {
|
||||
profile?: string;
|
||||
authJson?: string;
|
||||
configToml?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gemini-specific settings
|
||||
*/
|
||||
export interface GeminiCliSettingsApi extends CliSettingsBase {
|
||||
}
|
||||
|
||||
export interface CliSettingsEndpoint {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
settings: {
|
||||
env: {
|
||||
ANTHROPIC_AUTH_TOKEN?: string;
|
||||
ANTHROPIC_BASE_URL?: string;
|
||||
DISABLE_AUTOUPDATER?: string;
|
||||
[key: string]: string | undefined;
|
||||
};
|
||||
model?: string;
|
||||
includeCoAuthoredBy?: boolean;
|
||||
settingsFile?: string;
|
||||
availableModels?: string[];
|
||||
tags?: string[];
|
||||
};
|
||||
/** CLI provider type (defaults to 'claude' for backward compat) */
|
||||
provider: CliProvider;
|
||||
settings: ClaudeCliSettingsApi | CodexCliSettingsApi | GeminiCliSettingsApi;
|
||||
enabled: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
@@ -6057,19 +6084,9 @@ export interface SaveCliSettingsRequest {
|
||||
id?: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
settings: {
|
||||
env: {
|
||||
ANTHROPIC_AUTH_TOKEN?: string;
|
||||
ANTHROPIC_BASE_URL?: string;
|
||||
DISABLE_AUTOUPDATER?: string;
|
||||
[key: string]: string | undefined;
|
||||
};
|
||||
model?: string;
|
||||
includeCoAuthoredBy?: boolean;
|
||||
settingsFile?: string;
|
||||
availableModels?: string[];
|
||||
tags?: string[];
|
||||
};
|
||||
/** CLI provider type */
|
||||
provider?: CliProvider;
|
||||
settings: ClaudeCliSettingsApi | CodexCliSettingsApi | GeminiCliSettingsApi;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
@@ -6565,6 +6582,8 @@ export interface CreateCliSessionInput {
|
||||
resumeKey?: string;
|
||||
/** Launch mode for native CLI sessions (default or yolo). */
|
||||
launchMode?: 'default' | 'yolo';
|
||||
/** Settings endpoint ID for injecting env vars and settings into CLI process. */
|
||||
settingsEndpointId?: string;
|
||||
}
|
||||
|
||||
function withPath(url: string, projectPath?: string): string {
|
||||
|
||||
@@ -10,7 +10,8 @@ import { join } from 'path';
|
||||
import * as os from 'os';
|
||||
import { getCCWHome, ensureStorageDir } from './storage-paths.js';
|
||||
import {
|
||||
ClaudeCliSettings,
|
||||
CliSettings,
|
||||
CliProvider,
|
||||
EndpointSettings,
|
||||
SettingsListResponse,
|
||||
SettingsOperationResult,
|
||||
@@ -19,8 +20,8 @@ import {
|
||||
createDefaultSettings
|
||||
} from '../types/cli-settings.js';
|
||||
import {
|
||||
addClaudeCustomEndpoint,
|
||||
removeClaudeCustomEndpoint
|
||||
addCustomEndpoint,
|
||||
removeCustomEndpoint
|
||||
} from '../tools/claude-cli-tools.js';
|
||||
|
||||
/**
|
||||
@@ -108,6 +109,7 @@ export function saveEndpointSettings(request: SaveEndpointRequest): SettingsOper
|
||||
id: endpointId,
|
||||
name: request.name,
|
||||
description: request.description,
|
||||
provider: request.provider || 'claude',
|
||||
enabled: request.enabled ?? true,
|
||||
createdAt: existing?.createdAt || now,
|
||||
updatedAt: now
|
||||
@@ -129,13 +131,13 @@ export function saveEndpointSettings(request: SaveEndpointRequest): SettingsOper
|
||||
// Merge user-provided tags with cli-wrapper tag for proper type registration
|
||||
const userTags = request.settings.tags || [];
|
||||
const tags = [...new Set([...userTags, 'cli-wrapper'])]; // Dedupe and ensure cli-wrapper tag
|
||||
addClaudeCustomEndpoint(projectDir, {
|
||||
addCustomEndpoint(projectDir, {
|
||||
id: endpointId,
|
||||
name: request.name,
|
||||
enabled: request.enabled ?? true,
|
||||
tags,
|
||||
availableModels: request.settings.availableModels,
|
||||
settingsFile: request.settings.settingsFile
|
||||
settingsFile: 'settingsFile' in request.settings ? (request.settings as any).settingsFile : undefined
|
||||
});
|
||||
console.log(`[CliSettings] Synced endpoint ${endpointId} to cli-tools.json tools (cli-wrapper)`);
|
||||
} catch (syncError) {
|
||||
@@ -182,13 +184,15 @@ export function loadEndpointSettings(endpointId: string): EndpointSettings | nul
|
||||
|
||||
const settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));
|
||||
|
||||
if (!validateSettings(settings)) {
|
||||
const provider = (metadata as any).provider || 'claude';
|
||||
if (!validateSettings(settings, provider)) {
|
||||
console.error(`[CliSettings] Invalid settings format for ${endpointId}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
...metadata,
|
||||
provider,
|
||||
settings
|
||||
};
|
||||
} catch (e) {
|
||||
@@ -225,7 +229,7 @@ export function deleteEndpointSettings(endpointId: string): SettingsOperationRes
|
||||
// Step 3: Remove from cli-tools.json tools (api-endpoint type)
|
||||
try {
|
||||
const projectDir = os.homedir();
|
||||
removeClaudeCustomEndpoint(projectDir, endpointId);
|
||||
removeCustomEndpoint(projectDir, endpointId);
|
||||
console.log(`[CliSettings] Removed endpoint ${endpointId} from cli-tools.json tools`);
|
||||
} catch (syncError) {
|
||||
console.warn(`[CliSettings] Failed to remove from cli-tools.json: ${syncError}`);
|
||||
@@ -262,10 +266,12 @@ export function listAllSettings(): SettingsListResponse {
|
||||
|
||||
try {
|
||||
const settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));
|
||||
const provider: CliProvider = (metadata as any).provider || 'claude';
|
||||
|
||||
if (validateSettings(settings)) {
|
||||
if (validateSettings(settings, provider)) {
|
||||
endpoints.push({
|
||||
...metadata,
|
||||
provider,
|
||||
settings
|
||||
});
|
||||
}
|
||||
@@ -315,13 +321,13 @@ export function toggleEndpointEnabled(endpointId: string, enabled: boolean): Set
|
||||
const endpoint = loadEndpointSettings(endpointId);
|
||||
const userTags = endpoint?.settings.tags || [];
|
||||
const tags = [...new Set([...userTags, 'cli-wrapper'])]; // Dedupe and ensure cli-wrapper tag
|
||||
addClaudeCustomEndpoint(projectDir, {
|
||||
addCustomEndpoint(projectDir, {
|
||||
id: endpointId,
|
||||
name: metadata.name,
|
||||
enabled: enabled,
|
||||
tags,
|
||||
availableModels: endpoint?.settings.availableModels,
|
||||
settingsFile: endpoint?.settings.settingsFile
|
||||
settingsFile: endpoint?.settings && 'settingsFile' in endpoint.settings ? (endpoint.settings as any).settingsFile : undefined
|
||||
});
|
||||
console.log(`[CliSettings] Synced endpoint ${endpointId} enabled=${enabled} to cli-tools.json tools`);
|
||||
} catch (syncError) {
|
||||
@@ -368,9 +374,8 @@ export function createSettingsFromProvider(provider: {
|
||||
name?: string;
|
||||
}, options?: {
|
||||
model?: string;
|
||||
includeCoAuthoredBy?: boolean;
|
||||
}): ClaudeCliSettings {
|
||||
const settings = createDefaultSettings();
|
||||
}): CliSettings {
|
||||
const settings = createDefaultSettings('claude');
|
||||
|
||||
// Map provider credentials to env
|
||||
if (provider.apiKey) {
|
||||
@@ -384,9 +389,6 @@ export function createSettingsFromProvider(provider: {
|
||||
if (options?.model) {
|
||||
settings.model = options.model;
|
||||
}
|
||||
if (options?.includeCoAuthoredBy !== undefined) {
|
||||
settings.includeCoAuthoredBy = options.includeCoAuthoredBy;
|
||||
}
|
||||
|
||||
return settings;
|
||||
}
|
||||
|
||||
@@ -56,8 +56,8 @@ export async function handleCliSettingsRoutes(ctx: RouteContext): Promise<boolea
|
||||
if (!request.settings || !request.settings.env) {
|
||||
return { error: 'settings.env is required', status: 400 };
|
||||
}
|
||||
// Deep validation of settings object
|
||||
if (!validateSettings(request.settings)) {
|
||||
// Deep validation of settings object (provider-aware)
|
||||
if (!validateSettings(request.settings, request.provider)) {
|
||||
return { error: 'Invalid settings object format', status: 400 };
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,8 @@ import { getCliSessionPolicy } from './cli-session-policy.js';
|
||||
import { appendCliSessionAudit } from './cli-session-audit.js';
|
||||
import { getLaunchConfig } from './cli-launch-registry.js';
|
||||
import { assembleInstruction, type InstructionType } from './cli-instruction-assembler.js';
|
||||
import { loadEndpointSettings } from '../../config/cli-settings-manager.js';
|
||||
import { getToolConfig } from '../../tools/claude-cli-tools.js';
|
||||
|
||||
export interface CliSession {
|
||||
sessionKey: string;
|
||||
@@ -41,6 +43,8 @@ export interface CreateCliSessionOptions {
|
||||
resumeKey?: string;
|
||||
/** Launch mode for native CLI sessions. */
|
||||
launchMode?: 'default' | 'yolo';
|
||||
/** Settings endpoint ID for injecting env vars and settings into CLI process. */
|
||||
settingsEndpointId?: string;
|
||||
}
|
||||
|
||||
export interface ExecuteInCliSessionOptions {
|
||||
@@ -221,15 +225,56 @@ export class CliSessionManager {
|
||||
let args: string[];
|
||||
let cliTool: string | undefined;
|
||||
|
||||
// Load settings endpoint env vars and extra args if specified
|
||||
let endpointEnv: Record<string, string> = {};
|
||||
let endpointExtraArgs: string[] = [];
|
||||
|
||||
if (options.settingsEndpointId) {
|
||||
try {
|
||||
const endpoint = loadEndpointSettings(options.settingsEndpointId);
|
||||
if (endpoint) {
|
||||
// Merge env vars (skip undefined/empty values)
|
||||
for (const [key, value] of Object.entries(endpoint.settings.env)) {
|
||||
if (value !== undefined && value !== '') {
|
||||
endpointEnv[key] = value;
|
||||
}
|
||||
}
|
||||
// Provider-specific argument injection
|
||||
const provider = endpoint.provider || 'claude';
|
||||
if (provider === 'claude' && 'settingsFile' in endpoint.settings && endpoint.settings.settingsFile) {
|
||||
endpointExtraArgs.push('--settings', endpoint.settings.settingsFile);
|
||||
} else if (provider === 'codex' && 'profile' in endpoint.settings && endpoint.settings.profile) {
|
||||
endpointExtraArgs.push('--profile', endpoint.settings.profile);
|
||||
}
|
||||
// Gemini: env vars only, no extra CLI flags
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[CliSessionManager] Failed to load settings endpoint:', options.settingsEndpointId, err);
|
||||
}
|
||||
} else if (options.tool) {
|
||||
// Fallback: read settingsFile from cli-tools.json for the tool
|
||||
try {
|
||||
const toolConfig = getToolConfig(this.projectRoot, options.tool);
|
||||
if (options.tool === 'claude' && toolConfig.settingsFile) {
|
||||
endpointExtraArgs.push('--settings', toolConfig.settingsFile);
|
||||
}
|
||||
} catch (err) {
|
||||
// Non-fatal: continue without settings file
|
||||
}
|
||||
}
|
||||
|
||||
if (options.tool) {
|
||||
// Native CLI interactive session: spawn the CLI process directly
|
||||
const launchMode = options.launchMode ?? 'default';
|
||||
const config = getLaunchConfig(options.tool, launchMode);
|
||||
cliTool = options.tool;
|
||||
|
||||
// Append endpoint-specific extra args (e.g., --settings for claude)
|
||||
const allArgs = [...config.args, ...endpointExtraArgs];
|
||||
|
||||
// Build the full command string with arguments
|
||||
const fullCommand = config.args.length > 0
|
||||
? `${config.command} ${config.args.join(' ')}`
|
||||
const fullCommand = allArgs.length > 0
|
||||
? `${config.command} ${allArgs.join(' ')}`
|
||||
: config.command;
|
||||
|
||||
// On Windows, CLI tools installed via npm are typically .cmd files.
|
||||
@@ -275,7 +320,7 @@ export class CliSessionManager {
|
||||
// Unix: direct spawn works for most CLI tools
|
||||
shellKind = 'git-bash';
|
||||
file = config.command;
|
||||
args = config.args;
|
||||
args = allArgs;
|
||||
}
|
||||
|
||||
} else {
|
||||
@@ -289,6 +334,12 @@ export class CliSessionManager {
|
||||
args = picked.args;
|
||||
}
|
||||
|
||||
// Merge endpoint env vars with process.env (endpoint overrides process.env)
|
||||
const spawnEnv: Record<string, string> = {
|
||||
...(process.env as Record<string, string>),
|
||||
...endpointEnv,
|
||||
};
|
||||
|
||||
let pty: nodePty.IPty;
|
||||
try {
|
||||
pty = nodePty.spawn(file, args, {
|
||||
@@ -296,7 +347,7 @@ export class CliSessionManager {
|
||||
cols: options.cols ?? 120,
|
||||
rows: options.rows ?? 30,
|
||||
cwd: workingDir,
|
||||
env: process.env as Record<string, string>
|
||||
env: spawnEnv
|
||||
});
|
||||
} catch (spawnError: unknown) {
|
||||
const errorMsg = spawnError instanceof Error ? spawnError.message : String(spawnError);
|
||||
|
||||
@@ -859,12 +859,12 @@ export function removeClaudeApiEndpoint(
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use addClaudeApiEndpoint instead
|
||||
* Adds tool to config based on tags:
|
||||
* Add a custom CLI settings endpoint tool to cli-tools.json
|
||||
* Adds tool based on tags:
|
||||
* - cli-wrapper tag -> type: 'cli-wrapper'
|
||||
* - others -> type: 'api-endpoint'
|
||||
*/
|
||||
export function addClaudeCustomEndpoint(
|
||||
export function addCustomEndpoint(
|
||||
projectDir: string,
|
||||
endpoint: { id: string; name: string; enabled: boolean; tags?: string[]; availableModels?: string[]; settingsFile?: string }
|
||||
): ClaudeCliToolsConfig {
|
||||
@@ -895,10 +895,13 @@ export function addClaudeCustomEndpoint(
|
||||
return config;
|
||||
}
|
||||
|
||||
/** @deprecated Use addCustomEndpoint instead */
|
||||
export const addClaudeCustomEndpoint = addCustomEndpoint;
|
||||
|
||||
/**
|
||||
* Remove endpoint tool (cli-wrapper or api-endpoint)
|
||||
*/
|
||||
export function removeClaudeCustomEndpoint(
|
||||
export function removeCustomEndpoint(
|
||||
projectDir: string,
|
||||
endpointId: string
|
||||
): ClaudeCliToolsConfig {
|
||||
@@ -918,6 +921,9 @@ export function removeClaudeCustomEndpoint(
|
||||
return config;
|
||||
}
|
||||
|
||||
/** @deprecated Use removeCustomEndpoint instead */
|
||||
export const removeClaudeCustomEndpoint = removeCustomEndpoint;
|
||||
|
||||
/**
|
||||
* Get config source info
|
||||
*/
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
/**
|
||||
* CLI Settings Type Definitions
|
||||
* Supports Claude CLI --settings parameter format
|
||||
* Supports multi-provider CLI settings: Claude, Codex, Gemini
|
||||
*/
|
||||
|
||||
/**
|
||||
* CLI Provider type discriminator
|
||||
*/
|
||||
export type CliProvider = 'claude' | 'codex' | 'gemini';
|
||||
|
||||
/**
|
||||
* Claude CLI Settings 文件格式
|
||||
* 对应 `claude --settings <file-or-json>` 参数
|
||||
@@ -21,8 +26,6 @@ export interface ClaudeCliSettings {
|
||||
};
|
||||
/** 模型选择 */
|
||||
model?: 'opus' | 'sonnet' | 'haiku' | string;
|
||||
/** 是否包含 co-authored-by */
|
||||
includeCoAuthoredBy?: boolean;
|
||||
/** CLI工具标签 (用于标签路由) */
|
||||
tags?: string[];
|
||||
/** 可用模型列表 (显示在下拉菜单中) */
|
||||
@@ -31,6 +34,60 @@ export interface ClaudeCliSettings {
|
||||
settingsFile?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Codex CLI Settings
|
||||
* Codex 使用 --profile 传递配置, auth.json / config.toml 管理凭证和设置
|
||||
*/
|
||||
export interface CodexCliSettings {
|
||||
/** 环境变量配置 */
|
||||
env: {
|
||||
/** OpenAI API Key */
|
||||
OPENAI_API_KEY?: string;
|
||||
/** OpenAI API Base URL */
|
||||
OPENAI_BASE_URL?: string;
|
||||
/** 其他自定义环境变量 */
|
||||
[key: string]: string | undefined;
|
||||
};
|
||||
/** Codex profile 名称 (传递为 --profile <name>) */
|
||||
profile?: string;
|
||||
/** 模型选择 */
|
||||
model?: string;
|
||||
/** auth.json 内容 (JSON 字符串) */
|
||||
authJson?: string;
|
||||
/** config.toml 内容 (TOML 字符串) */
|
||||
configToml?: string;
|
||||
/** CLI工具标签 */
|
||||
tags?: string[];
|
||||
/** 可用模型列表 */
|
||||
availableModels?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gemini CLI Settings
|
||||
*/
|
||||
export interface GeminiCliSettings {
|
||||
/** 环境变量配置 */
|
||||
env: {
|
||||
/** Gemini API Key */
|
||||
GEMINI_API_KEY?: string;
|
||||
/** Google API Key (alternative) */
|
||||
GOOGLE_API_KEY?: string;
|
||||
/** 其他自定义环境变量 */
|
||||
[key: string]: string | undefined;
|
||||
};
|
||||
/** 模型选择 */
|
||||
model?: string;
|
||||
/** CLI工具标签 */
|
||||
tags?: string[];
|
||||
/** 可用模型列表 */
|
||||
availableModels?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Union type for all provider settings
|
||||
*/
|
||||
export type CliSettings = ClaudeCliSettings | CodexCliSettings | GeminiCliSettings;
|
||||
|
||||
/**
|
||||
* 端点 Settings 配置(带元数据)
|
||||
*/
|
||||
@@ -41,8 +98,10 @@ export interface EndpointSettings {
|
||||
name: string;
|
||||
/** 端点描述 */
|
||||
description?: string;
|
||||
/** Claude CLI Settings */
|
||||
settings: ClaudeCliSettings;
|
||||
/** CLI provider 类型 (默认 'claude' 兼容旧数据) */
|
||||
provider: CliProvider;
|
||||
/** CLI Settings (provider-specific) */
|
||||
settings: CliSettings;
|
||||
/** 是否启用 */
|
||||
enabled: boolean;
|
||||
/** 创建时间 */
|
||||
@@ -76,7 +135,9 @@ export interface SaveEndpointRequest {
|
||||
id?: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
settings: ClaudeCliSettings;
|
||||
/** CLI provider 类型 */
|
||||
provider?: CliProvider;
|
||||
settings: CliSettings;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
@@ -104,22 +165,39 @@ export function mapProviderToClaudeEnv(provider: {
|
||||
/**
|
||||
* 创建默认 Settings
|
||||
*/
|
||||
export function createDefaultSettings(): ClaudeCliSettings {
|
||||
return {
|
||||
env: {
|
||||
DISABLE_AUTOUPDATER: '1'
|
||||
},
|
||||
model: 'sonnet',
|
||||
includeCoAuthoredBy: false,
|
||||
tags: [],
|
||||
availableModels: []
|
||||
};
|
||||
export function createDefaultSettings(provider: CliProvider = 'claude'): CliSettings {
|
||||
switch (provider) {
|
||||
case 'codex':
|
||||
return {
|
||||
env: {},
|
||||
model: '',
|
||||
tags: [],
|
||||
availableModels: []
|
||||
} satisfies CodexCliSettings;
|
||||
case 'gemini':
|
||||
return {
|
||||
env: {},
|
||||
model: '',
|
||||
tags: [],
|
||||
availableModels: []
|
||||
} satisfies GeminiCliSettings;
|
||||
case 'claude':
|
||||
default:
|
||||
return {
|
||||
env: {
|
||||
DISABLE_AUTOUPDATER: '1'
|
||||
},
|
||||
model: 'sonnet',
|
||||
tags: [],
|
||||
availableModels: []
|
||||
} satisfies ClaudeCliSettings;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证 Settings 格式
|
||||
* 验证 Settings 格式 (provider-aware)
|
||||
*/
|
||||
export function validateSettings(settings: unknown): settings is ClaudeCliSettings {
|
||||
export function validateSettings(settings: unknown, provider?: CliProvider): settings is CliSettings {
|
||||
if (!settings || typeof settings !== 'object') {
|
||||
return false;
|
||||
}
|
||||
@@ -136,7 +214,6 @@ export function validateSettings(settings: unknown): settings is ClaudeCliSettin
|
||||
for (const key in envObj) {
|
||||
if (Object.prototype.hasOwnProperty.call(envObj, key)) {
|
||||
const value = envObj[key];
|
||||
// 允许 undefined 或 string,其他类型(包括 null)都拒绝
|
||||
if (value !== undefined && typeof value !== 'string') {
|
||||
return false;
|
||||
}
|
||||
@@ -148,11 +225,6 @@ export function validateSettings(settings: unknown): settings is ClaudeCliSettin
|
||||
return false;
|
||||
}
|
||||
|
||||
// includeCoAuthoredBy 可选,但如果存在必须是布尔值
|
||||
if (s.includeCoAuthoredBy !== undefined && typeof s.includeCoAuthoredBy !== 'boolean') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// tags 可选,但如果存在必须是数组
|
||||
if (s.tags !== undefined && !Array.isArray(s.tags)) {
|
||||
return false;
|
||||
@@ -163,9 +235,25 @@ export function validateSettings(settings: unknown): settings is ClaudeCliSettin
|
||||
return false;
|
||||
}
|
||||
|
||||
// settingsFile 可选,但如果存在必须是字符串
|
||||
if (s.settingsFile !== undefined && typeof s.settingsFile !== 'string') {
|
||||
return false;
|
||||
// Provider-specific validation
|
||||
if (provider === 'codex') {
|
||||
// profile 可选,但如果存在必须是字符串
|
||||
if (s.profile !== undefined && typeof s.profile !== 'string') {
|
||||
return false;
|
||||
}
|
||||
// authJson 可选,但如果存在必须是字符串
|
||||
if (s.authJson !== undefined && typeof s.authJson !== 'string') {
|
||||
return false;
|
||||
}
|
||||
// configToml 可选,但如果存在必须是字符串
|
||||
if (s.configToml !== undefined && typeof s.configToml !== 'string') {
|
||||
return false;
|
||||
}
|
||||
} else if (provider === 'claude' || !provider) {
|
||||
// settingsFile 可选,但如果存在必须是字符串
|
||||
if (s.settingsFile !== undefined && typeof s.settingsFile !== 'string') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
@@ -17,13 +17,15 @@ import {
|
||||
} from '../../dist/types/cli-settings.js';
|
||||
|
||||
// Type for testing (interfaces are erased in JS)
|
||||
type ClaudeCliSettings = {
|
||||
type CliSettings = {
|
||||
env: Record<string, string | undefined>;
|
||||
model?: string;
|
||||
includeCoAuthoredBy?: boolean;
|
||||
tags?: string[];
|
||||
availableModels?: string[];
|
||||
settingsFile?: string;
|
||||
profile?: string;
|
||||
authJson?: string;
|
||||
configToml?: string;
|
||||
};
|
||||
|
||||
describe('cli-settings.ts', () => {
|
||||
@@ -37,7 +39,6 @@ describe('cli-settings.ts', () => {
|
||||
DISABLE_AUTOUPDATER: '1',
|
||||
},
|
||||
model: 'sonnet',
|
||||
includeCoAuthoredBy: true,
|
||||
tags: ['分析', 'Debug'],
|
||||
availableModels: ['opus', 'sonnet', 'haiku'],
|
||||
settingsFile: '/path/to/settings.json',
|
||||
@@ -241,23 +242,72 @@ describe('cli-settings.ts', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('should validate includeCoAuthoredBy field', () => {
|
||||
it('should accept boolean includeCoAuthoredBy', () => {
|
||||
describe('should validate codex-specific fields', () => {
|
||||
it('should accept valid codex settings with profile', () => {
|
||||
const settings = {
|
||||
env: {},
|
||||
includeCoAuthoredBy: true,
|
||||
env: { OPENAI_API_KEY: 'sk-test' },
|
||||
model: 'gpt-5.2',
|
||||
profile: 'default',
|
||||
};
|
||||
|
||||
assert.strictEqual(validateSettings(settings), true);
|
||||
assert.strictEqual(validateSettings(settings, 'codex'), true);
|
||||
});
|
||||
|
||||
it('should reject non-boolean includeCoAuthoredBy', () => {
|
||||
it('should reject non-string profile for codex', () => {
|
||||
const settings = {
|
||||
env: {},
|
||||
includeCoAuthoredBy: 'true',
|
||||
profile: 123,
|
||||
};
|
||||
|
||||
assert.strictEqual(validateSettings(settings), false);
|
||||
assert.strictEqual(validateSettings(settings, 'codex'), false);
|
||||
});
|
||||
|
||||
it('should accept codex settings with authJson and configToml', () => {
|
||||
const settings = {
|
||||
env: { OPENAI_API_KEY: 'sk-test' },
|
||||
authJson: '{"OPENAI_API_KEY": "sk-test"}',
|
||||
configToml: 'model = "gpt-5.2"',
|
||||
};
|
||||
|
||||
assert.strictEqual(validateSettings(settings, 'codex'), true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('should validate gemini-specific fields', () => {
|
||||
it('should accept valid gemini settings', () => {
|
||||
const settings = {
|
||||
env: { GEMINI_API_KEY: 'AIza-test' },
|
||||
model: 'gemini-2.5-flash',
|
||||
};
|
||||
|
||||
assert.strictEqual(validateSettings(settings, 'gemini'), true);
|
||||
});
|
||||
|
||||
it('should accept gemini settings with GOOGLE_API_KEY', () => {
|
||||
const settings = {
|
||||
env: { GOOGLE_API_KEY: 'AIza-test' },
|
||||
model: 'gemini-2.5-pro',
|
||||
tags: ['分析'],
|
||||
availableModels: ['gemini-2.5-flash', 'gemini-2.5-pro'],
|
||||
};
|
||||
|
||||
assert.strictEqual(validateSettings(settings, 'gemini'), true);
|
||||
});
|
||||
|
||||
it('should accept gemini settings with empty env', () => {
|
||||
const settings = {
|
||||
env: {},
|
||||
};
|
||||
|
||||
assert.strictEqual(validateSettings(settings, 'gemini'), true);
|
||||
});
|
||||
|
||||
it('should reject gemini settings with non-string env value', () => {
|
||||
const settings = {
|
||||
env: { GEMINI_API_KEY: 12345 },
|
||||
};
|
||||
|
||||
assert.strictEqual(validateSettings(settings, 'gemini'), false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -358,7 +408,6 @@ describe('cli-settings.ts', () => {
|
||||
CUSTOM_VAR: 'custom-value',
|
||||
},
|
||||
model: 'custom-model',
|
||||
includeCoAuthoredBy: false,
|
||||
tags: [],
|
||||
availableModels: [],
|
||||
settingsFile: '/path/to/settings.json',
|
||||
@@ -436,53 +485,59 @@ describe('cli-settings.ts', () => {
|
||||
});
|
||||
|
||||
describe('createDefaultSettings', () => {
|
||||
it('should create valid default settings', () => {
|
||||
it('should create valid default claude settings', () => {
|
||||
const settings = createDefaultSettings();
|
||||
|
||||
assert.strictEqual(validateSettings(settings), true);
|
||||
});
|
||||
|
||||
it('should include all default fields', () => {
|
||||
it('should create valid default codex settings', () => {
|
||||
const settings = createDefaultSettings('codex');
|
||||
|
||||
assert.strictEqual(validateSettings(settings, 'codex'), true);
|
||||
});
|
||||
|
||||
it('should create valid default gemini settings', () => {
|
||||
const settings = createDefaultSettings('gemini');
|
||||
|
||||
assert.strictEqual(validateSettings(settings, 'gemini'), true);
|
||||
});
|
||||
|
||||
it('should include all default fields for claude', () => {
|
||||
const settings = createDefaultSettings();
|
||||
|
||||
assert.ok('env' in settings);
|
||||
assert.ok('model' in settings);
|
||||
assert.ok('includeCoAuthoredBy' in settings);
|
||||
assert.ok('tags' in settings);
|
||||
assert.ok('availableModels' in settings);
|
||||
});
|
||||
|
||||
it('should have correct default values', () => {
|
||||
it('should have correct default values for claude', () => {
|
||||
const settings = createDefaultSettings();
|
||||
|
||||
assert.deepStrictEqual(settings.env, {
|
||||
DISABLE_AUTOUPDATER: '1',
|
||||
});
|
||||
assert.strictEqual(settings.model, 'sonnet');
|
||||
assert.strictEqual(settings.includeCoAuthoredBy, false);
|
||||
assert.deepStrictEqual(settings.tags, []);
|
||||
assert.deepStrictEqual(settings.availableModels, []);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TypeScript type safety', () => {
|
||||
it('should enforce ClaudeCliSettings interface structure', () => {
|
||||
// This test verifies TypeScript compilation catches type errors
|
||||
it('should enforce CliSettings interface structure', () => {
|
||||
const validSettings = {
|
||||
env: {
|
||||
ANTHROPIC_AUTH_TOKEN: 'sk-ant-123',
|
||||
},
|
||||
model: 'opus',
|
||||
includeCoAuthoredBy: true,
|
||||
tags: ['tag1'],
|
||||
availableModels: ['model1'],
|
||||
settingsFile: '/path/to/file',
|
||||
};
|
||||
|
||||
// Type assertion: all fields should be present and of correct type
|
||||
assert.strictEqual(typeof validSettings.env, 'object');
|
||||
assert.strictEqual(typeof validSettings.model, 'string');
|
||||
assert.strictEqual(typeof validSettings.includeCoAuthoredBy, 'boolean');
|
||||
assert.strictEqual(Array.isArray(validSettings.tags), true);
|
||||
assert.strictEqual(Array.isArray(validSettings.availableModels), true);
|
||||
assert.strictEqual(typeof validSettings.settingsFile, 'string');
|
||||
|
||||
Reference in New Issue
Block a user