Merge pull request #77 from kaitranntt/kai/feat/api-profile-ux

feat(ui): refactor profile creation UX with dialog interface and validation
This commit is contained in:
Kai (Tam Nhu) Tran
2025-12-10 23:44:23 -05:00
committed by GitHub
17 changed files with 2491 additions and 336 deletions
+165 -36
View File
@@ -93,7 +93,7 @@ function validateApiName(name: string): string | null {
}
/**
* Validate URL format
* Validate URL format and warn about common mistakes
*/
function validateUrl(url: string): string | null {
if (!url) {
@@ -107,6 +107,25 @@ function validateUrl(url: string): string | null {
}
}
/**
* Check if URL looks like it includes endpoint path (common mistake)
* Returns warning message if problematic, null if OK
*/
function getUrlWarning(url: string): string | null {
const problematicPaths = ['/chat/completions', '/v1/messages', '/messages', '/completions'];
const lowerUrl = url.toLowerCase();
for (const path of problematicPaths) {
if (lowerUrl.endsWith(path)) {
return (
`URL ends with "${path}" - Claude appends this automatically.\n` +
` You likely want: ${url.replace(new RegExp(path + '$', 'i'), '')}`
);
}
}
return null;
}
/**
* Check if unified config mode is active
*/
@@ -130,11 +149,24 @@ function apiExists(name: string): boolean {
}
}
/** Model mapping for API profiles */
interface ModelMapping {
default: string;
opus: string;
sonnet: string;
haiku: string;
}
/**
* Create settings.json file for API profile
* Includes all 4 model fields for proper Claude CLI integration
*/
function createSettingsFile(name: string, baseUrl: string, apiKey: string, model: string): string {
function createSettingsFile(
name: string,
baseUrl: string,
apiKey: string,
models: ModelMapping
): string {
const ccsDir = getCcsDir();
const settingsPath = path.join(ccsDir, `${name}.settings.json`);
@@ -142,10 +174,10 @@ function createSettingsFile(name: string, baseUrl: string, apiKey: string, model
env: {
ANTHROPIC_BASE_URL: baseUrl,
ANTHROPIC_AUTH_TOKEN: apiKey,
ANTHROPIC_MODEL: model,
ANTHROPIC_DEFAULT_OPUS_MODEL: model,
ANTHROPIC_DEFAULT_SONNET_MODEL: model,
ANTHROPIC_DEFAULT_HAIKU_MODEL: model,
ANTHROPIC_MODEL: models.default,
ANTHROPIC_DEFAULT_OPUS_MODEL: models.opus,
ANTHROPIC_DEFAULT_SONNET_MODEL: models.sonnet,
ANTHROPIC_DEFAULT_HAIKU_MODEL: models.haiku,
},
};
@@ -192,7 +224,7 @@ function createApiProfileUnified(
name: string,
baseUrl: string,
apiKey: string,
model: string
models: ModelMapping
): void {
const ccsDir = path.join(os.homedir(), '.ccs');
const settingsFile = `${name}.settings.json`;
@@ -203,10 +235,10 @@ function createApiProfileUnified(
env: {
ANTHROPIC_BASE_URL: baseUrl,
ANTHROPIC_AUTH_TOKEN: apiKey,
ANTHROPIC_MODEL: model,
ANTHROPIC_DEFAULT_OPUS_MODEL: model,
ANTHROPIC_DEFAULT_SONNET_MODEL: model,
ANTHROPIC_DEFAULT_HAIKU_MODEL: model,
ANTHROPIC_MODEL: models.default,
ANTHROPIC_DEFAULT_OPUS_MODEL: models.opus,
ANTHROPIC_DEFAULT_SONNET_MODEL: models.sonnet,
ANTHROPIC_DEFAULT_HAIKU_MODEL: models.haiku,
},
};
@@ -293,9 +325,12 @@ async function handleCreate(args: string[]): Promise<void> {
// Step 2: Base URL
let baseUrl = parsedArgs.baseUrl;
if (!baseUrl) {
baseUrl = await InteractivePrompt.input('API Base URL (e.g., https://api.example.com)', {
validate: validateUrl,
});
baseUrl = await InteractivePrompt.input(
'API Base URL (e.g., https://api.example.com/v1 - without /chat/completions)',
{
validate: validateUrl,
}
);
} else {
const error = validateUrl(baseUrl);
if (error) {
@@ -304,6 +339,23 @@ async function handleCreate(args: string[]): Promise<void> {
}
}
// Check for common URL mistakes and warn
const urlWarning = getUrlWarning(baseUrl);
if (urlWarning) {
console.log('');
console.log(warn(urlWarning));
const continueAnyway = await InteractivePrompt.confirm('Continue with this URL anyway?', {
default: false,
});
if (!continueAnyway) {
// Let user re-enter URL
baseUrl = await InteractivePrompt.input('API Base URL', {
validate: validateUrl,
default: baseUrl.replace(/\/(chat\/completions|v1\/messages|messages|completions)$/i, ''),
});
}
}
// Step 3: API Key
let apiKey = parsedArgs.apiKey;
if (!apiKey) {
@@ -318,50 +370,127 @@ async function handleCreate(args: string[]): Promise<void> {
const defaultModel = 'claude-sonnet-4-5-20250929';
let model = parsedArgs.model;
if (!model && !parsedArgs.yes) {
model = await InteractivePrompt.input('Default model', {
model = await InteractivePrompt.input('Default model (ANTHROPIC_MODEL)', {
default: defaultModel,
});
}
model = model || defaultModel;
// Step 5: Model mapping for Opus/Sonnet/Haiku
// Auto-show if user entered a custom model, otherwise ask
let opusModel = model;
let sonnetModel = model;
let haikuModel = model;
const isCustomModel = model !== defaultModel;
if (!parsedArgs.yes) {
// If user entered custom model, auto-prompt for model mapping
// Otherwise, ask if they want to configure it
let wantCustomMapping = isCustomModel;
if (!isCustomModel) {
console.log('');
console.log(dim('Some API proxies route different model types to different backends.'));
wantCustomMapping = await InteractivePrompt.confirm(
'Configure different models for Opus/Sonnet/Haiku?',
{ default: false }
);
}
if (wantCustomMapping) {
console.log('');
if (isCustomModel) {
console.log(dim('Configure model IDs for each tier (defaults to your model):'));
} else {
console.log(dim('Leave blank to use the default model for each.'));
}
opusModel =
(await InteractivePrompt.input('Opus model (ANTHROPIC_DEFAULT_OPUS_MODEL)', {
default: model,
})) || model;
sonnetModel =
(await InteractivePrompt.input('Sonnet model (ANTHROPIC_DEFAULT_SONNET_MODEL)', {
default: model,
})) || model;
haikuModel =
(await InteractivePrompt.input('Haiku model (ANTHROPIC_DEFAULT_HAIKU_MODEL)', {
default: model,
})) || model;
}
}
// Build model mapping
const models: ModelMapping = {
default: model,
opus: opusModel,
sonnet: sonnetModel,
haiku: haikuModel,
};
// Check if custom model mapping is configured
const hasCustomMapping = opusModel !== model || sonnetModel !== model || haikuModel !== model;
// Create files
console.log('');
console.log(info('Creating API profile...'));
try {
const settingsFile = `~/.ccs/${name}.settings.json`;
if (isUnifiedMode()) {
// Use unified config format
createApiProfileUnified(name, baseUrl, apiKey, model);
createApiProfileUnified(name, baseUrl, apiKey, models);
console.log('');
console.log(
infoBox(
`API: ${name}\n` +
`Config: ~/.ccs/config.yaml\n` +
`Secrets: ~/.ccs/secrets.yaml\n` +
`Base URL: ${baseUrl}\n` +
`Model: ${model}`,
'API Profile Created (Unified Config)'
)
);
// Build info message
let infoMsg =
`API: ${name}\n` +
`Config: ~/.ccs/config.yaml\n` +
`Settings: ${settingsFile}\n` +
`Base URL: ${baseUrl}\n` +
`Model: ${model}`;
if (hasCustomMapping) {
infoMsg +=
`\n\nModel Mapping:\n` +
` Opus: ${opusModel}\n` +
` Sonnet: ${sonnetModel}\n` +
` Haiku: ${haikuModel}`;
}
console.log(infoBox(infoMsg, 'API Profile Created'));
} else {
// Use legacy JSON format
const settingsPath = createSettingsFile(name, baseUrl, apiKey, model);
const settingsPath = createSettingsFile(name, baseUrl, apiKey, models);
updateConfig(name, settingsPath);
console.log('');
console.log(
infoBox(
`API: ${name}\n` +
`Settings: ~/.ccs/${name}.settings.json\n` +
`Base URL: ${baseUrl}\n` +
`Model: ${model}`,
'API Profile Created'
)
);
let infoMsg =
`API: ${name}\n` +
`Settings: ${settingsFile}\n` +
`Base URL: ${baseUrl}\n` +
`Model: ${model}`;
if (hasCustomMapping) {
infoMsg +=
`\n\nModel Mapping:\n` +
` Opus: ${opusModel}\n` +
` Sonnet: ${sonnetModel}\n` +
` Haiku: ${haikuModel}`;
}
console.log(infoBox(infoMsg, 'API Profile Created'));
}
console.log('');
console.log(header('Usage'));
console.log(` ${color(`ccs ${name} "your prompt"`, 'command')}`);
console.log('');
console.log(header('Edit Settings'));
console.log(` ${dim('To modify env vars later:')}`);
console.log(` ${color(`nano ${settingsFile.replace('~', '$HOME')}`, 'command')}`);
console.log('');
} catch (error) {
console.log(fail(`Failed to create API profile: ${(error as Error).message}`));
process.exit(1);
+251 -7
View File
@@ -77,17 +77,34 @@ function isConfigured(profileName: string, config: Config): boolean {
}
}
/** Model mapping for API profiles */
interface ModelMapping {
model?: string;
opusModel?: string;
sonnetModel?: string;
haikuModel?: string;
}
/**
* Helper: Create settings file for profile
*/
function createSettingsFile(name: string, baseUrl: string, apiKey: string, model?: string): string {
function createSettingsFile(
name: string,
baseUrl: string,
apiKey: string,
models: ModelMapping = {}
): string {
const settingsPath = path.join(getCcsDir(), `${name}.settings.json`);
const { model, opusModel, sonnetModel, haikuModel } = models;
const settings: Settings = {
env: {
ANTHROPIC_BASE_URL: baseUrl,
ANTHROPIC_AUTH_TOKEN: apiKey,
...(model && { ANTHROPIC_MODEL: model }),
...(opusModel && { ANTHROPIC_DEFAULT_OPUS_MODEL: opusModel }),
...(sonnetModel && { ANTHROPIC_DEFAULT_SONNET_MODEL: sonnetModel }),
...(haikuModel && { ANTHROPIC_DEFAULT_HAIKU_MODEL: haikuModel }),
},
};
@@ -100,7 +117,14 @@ function createSettingsFile(name: string, baseUrl: string, apiKey: string, model
*/
function updateSettingsFile(
name: string,
updates: { baseUrl?: string; apiKey?: string; model?: string }
updates: {
baseUrl?: string;
apiKey?: string;
model?: string;
opusModel?: string;
sonnetModel?: string;
haikuModel?: string;
}
): void {
const settingsPath = path.join(getCcsDir(), `${name}.settings.json`);
@@ -129,6 +153,34 @@ function updateSettingsFile(
}
}
// Handle model mapping fields
if (updates.opusModel !== undefined) {
settings.env = settings.env || {};
if (updates.opusModel) {
settings.env.ANTHROPIC_DEFAULT_OPUS_MODEL = updates.opusModel;
} else {
delete settings.env.ANTHROPIC_DEFAULT_OPUS_MODEL;
}
}
if (updates.sonnetModel !== undefined) {
settings.env = settings.env || {};
if (updates.sonnetModel) {
settings.env.ANTHROPIC_DEFAULT_SONNET_MODEL = updates.sonnetModel;
} else {
delete settings.env.ANTHROPIC_DEFAULT_SONNET_MODEL;
}
}
if (updates.haikuModel !== undefined) {
settings.env = settings.env || {};
if (updates.haikuModel) {
settings.env.ANTHROPIC_DEFAULT_HAIKU_MODEL = updates.haikuModel;
} else {
delete settings.env.ANTHROPIC_DEFAULT_HAIKU_MODEL;
}
}
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n');
}
@@ -166,7 +218,7 @@ apiRoutes.get('/profiles', (_req: Request, res: Response) => {
* POST /api/profiles - Create new profile
*/
apiRoutes.post('/profiles', (req: Request, res: Response): void => {
const { name, baseUrl, apiKey, model } = req.body;
const { name, baseUrl, apiKey, model, opusModel, sonnetModel, haikuModel } = req.body;
if (!name || !baseUrl || !apiKey) {
res.status(400).json({ error: 'Missing required fields: name, baseUrl, apiKey' });
@@ -185,8 +237,13 @@ apiRoutes.post('/profiles', (req: Request, res: Response): void => {
fs.mkdirSync(getCcsDir(), { recursive: true });
}
// Create settings file
const settingsPath = createSettingsFile(name, baseUrl, apiKey, model);
// Create settings file with model mapping
const settingsPath = createSettingsFile(name, baseUrl, apiKey, {
model,
opusModel,
sonnetModel,
haikuModel,
});
// Update config
config.profiles[name] = settingsPath;
@@ -200,7 +257,7 @@ apiRoutes.post('/profiles', (req: Request, res: Response): void => {
*/
apiRoutes.put('/profiles/:name', (req: Request, res: Response): void => {
const { name } = req.params;
const { baseUrl, apiKey, model } = req.body;
const { baseUrl, apiKey, model, opusModel, sonnetModel, haikuModel } = req.body;
const config = readConfigSafe();
@@ -210,7 +267,7 @@ apiRoutes.put('/profiles/:name', (req: Request, res: Response): void => {
}
try {
updateSettingsFile(name, { baseUrl, apiKey, model });
updateSettingsFile(name, { baseUrl, apiKey, model, opusModel, sonnetModel, haikuModel });
res.json({ name, updated: true });
} catch (error) {
res.status(500).json({ error: (error as Error).message });
@@ -779,3 +836,190 @@ apiRoutes.get('/secrets/:profile/exists', (req: Request, res: Response) => {
keys: Object.keys(secrets), // Only key names, not values
});
});
// ==================== Generic File API (Issue #73) ====================
/**
* Security: Validate file path is within allowed directories
* - ~/.ccs/ directory: read/write allowed
* - ~/.claude/settings.json: read-only
*/
function validateFilePath(filePath: string): { valid: boolean; readonly: boolean; error?: string } {
const expandedPath = expandPath(filePath);
const normalizedPath = path.normalize(expandedPath);
const ccsDir = getCcsDir();
const claudeSettingsPath = expandPath('~/.claude/settings.json');
// Check if path is within ~/.ccs/
if (normalizedPath.startsWith(ccsDir)) {
// Block access to sensitive subdirectories
const relativePath = normalizedPath.slice(ccsDir.length);
if (relativePath.includes('/.git/') || relativePath.includes('/node_modules/')) {
return { valid: false, readonly: false, error: 'Access to this path is not allowed' };
}
return { valid: true, readonly: false };
}
// Allow read-only access to ~/.claude/settings.json
if (normalizedPath === claudeSettingsPath) {
return { valid: true, readonly: true };
}
return { valid: false, readonly: false, error: 'Access to this path is not allowed' };
}
/**
* GET /api/file - Read a file with path validation
* Query params: path (required)
* Returns: { content: string, mtime: number, readonly: boolean, path: string }
*/
apiRoutes.get('/file', (req: Request, res: Response): void => {
const filePath = req.query.path as string;
if (!filePath) {
res.status(400).json({ error: 'Missing required query parameter: path' });
return;
}
const validation = validateFilePath(filePath);
if (!validation.valid) {
res.status(403).json({ error: validation.error });
return;
}
const expandedPath = expandPath(filePath);
if (!fs.existsSync(expandedPath)) {
res.status(404).json({ error: 'File not found' });
return;
}
try {
const stat = fs.statSync(expandedPath);
const content = fs.readFileSync(expandedPath, 'utf8');
res.json({
content,
mtime: stat.mtime.getTime(),
readonly: validation.readonly,
path: expandedPath,
});
} catch (error) {
res.status(500).json({ error: (error as Error).message });
}
});
/**
* PUT /api/file - Write a file with conflict detection and backup
* Query params: path (required)
* Body: { content: string, expectedMtime?: number }
* Returns: { success: true, mtime: number, backupPath?: string }
*/
apiRoutes.put('/file', (req: Request, res: Response): void => {
const filePath = req.query.path as string;
const { content, expectedMtime } = req.body;
if (!filePath) {
res.status(400).json({ error: 'Missing required query parameter: path' });
return;
}
if (typeof content !== 'string') {
res.status(400).json({ error: 'Missing required field: content' });
return;
}
const validation = validateFilePath(filePath);
if (!validation.valid) {
res.status(403).json({ error: validation.error });
return;
}
if (validation.readonly) {
res.status(403).json({ error: 'File is read-only' });
return;
}
const expandedPath = expandPath(filePath);
const ccsDir = getCcsDir();
// Conflict detection (if file exists and expectedMtime provided)
if (fs.existsSync(expandedPath) && expectedMtime !== undefined) {
const stat = fs.statSync(expandedPath);
if (stat.mtime.getTime() !== expectedMtime) {
res.status(409).json({
error: 'File modified externally',
currentMtime: stat.mtime.getTime(),
});
return;
}
}
try {
// Create backup if file exists
let backupPath: string | undefined;
if (fs.existsSync(expandedPath)) {
const backupDir = path.join(ccsDir, 'backups');
if (!fs.existsSync(backupDir)) {
fs.mkdirSync(backupDir, { recursive: true });
}
const filename = path.basename(expandedPath);
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
backupPath = path.join(backupDir, `${filename}.${timestamp}.bak`);
fs.copyFileSync(expandedPath, backupPath);
}
// Ensure parent directory exists
const parentDir = path.dirname(expandedPath);
if (!fs.existsSync(parentDir)) {
fs.mkdirSync(parentDir, { recursive: true });
}
// Write atomically
const tempPath = expandedPath + '.tmp';
fs.writeFileSync(tempPath, content);
fs.renameSync(tempPath, expandedPath);
const newStat = fs.statSync(expandedPath);
res.json({
success: true,
mtime: newStat.mtime.getTime(),
backupPath,
});
} catch (error) {
res.status(500).json({ error: (error as Error).message });
}
});
/**
* GET /api/files - List editable files in ~/.ccs/
* Returns: { files: Array<{ name: string, path: string, mtime: number }> }
*/
apiRoutes.get('/files', (_req: Request, res: Response): void => {
const ccsDir = getCcsDir();
if (!fs.existsSync(ccsDir)) {
res.json({ files: [] });
return;
}
try {
const entries = fs.readdirSync(ccsDir, { withFileTypes: true });
const files = entries
.filter((entry) => entry.isFile() && entry.name.endsWith('.json'))
.map((entry) => {
const filePath = path.join(ccsDir, entry.name);
const stat = fs.statSync(filePath);
return {
name: entry.name,
path: `~/.ccs/${entry.name}`,
mtime: stat.mtime.getTime(),
};
})
.sort((a, b) => a.name.localeCompare(b.name));
res.json({ files });
} catch (error) {
res.status(500).json({ error: (error as Error).message });
}
});
+15
View File
@@ -12,6 +12,7 @@
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-popover": "^1.1.15",
"@radix-ui/react-scroll-area": "^1.2.10",
"@radix-ui/react-select": "^2.2.6",
"@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-tabs": "^1.1.13",
@@ -23,11 +24,13 @@
"clsx": "^2.1.1",
"date-fns": "^4.1.0",
"lucide-react": "^0.556.0",
"prism-react-renderer": "^2.4.1",
"react": "^19.2.0",
"react-day-picker": "^9.12.0",
"react-dom": "^19.2.0",
"react-hook-form": "^7.68.0",
"react-router-dom": "^7.10.1",
"react-simple-code-editor": "^0.14.1",
"recharts": "^2.12.0",
"sonner": "^2.0.7",
"tailwind-merge": "^3.4.0",
@@ -243,6 +246,8 @@
"@radix-ui/react-scroll-area": ["@radix-ui/react-scroll-area@1.2.10", "", { "dependencies": { "@radix-ui/number": "1.1.1", "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-tAXIa1g3sM5CGpVT0uIbUx/U3Gs5N8T52IICuCtObaos1S8fzsrPXG5WObkQN3S6NVl6wKgPhAIiBGbWnvc97A=="],
"@radix-ui/react-select": ["@radix-ui/react-select@2.2.6", "", { "dependencies": { "@radix-ui/number": "1.1.1", "@radix-ui/primitive": "1.1.3", "@radix-ui/react-collection": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-dismissable-layer": "1.1.11", "@radix-ui/react-focus-guards": "1.1.3", "@radix-ui/react-focus-scope": "1.1.7", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-popper": "1.2.8", "@radix-ui/react-portal": "1.1.9", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-layout-effect": "1.1.1", "@radix-ui/react-use-previous": "1.1.1", "@radix-ui/react-visually-hidden": "1.2.3", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.6.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-I30RydO+bnn2PQztvo25tswPH+wFBjehVGtmagkU78yMdwTwVf12wnAOF+AeP8S2N8xD+5UPbGhkUfPyvT+mwQ=="],
"@radix-ui/react-separator": ["@radix-ui/react-separator@1.1.8", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-sDvqVY4itsKwwSMEe0jtKgfTh+72Sy3gPmQpjqcQneqQ4PFmr/1I0YA+2/puilhggCe2gJcx5EBAYFkWkdpa5g=="],
"@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.4", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Jl+bCv8HxKnlTLVrcDE8zTMJ09R9/ukw4qBs/oZClOfoQk/cOTbDn+NceXfV7j09YPVQUryJPHurafcSg6EVKA=="],
@@ -261,6 +266,8 @@
"@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="],
"@radix-ui/react-use-previous": ["@radix-ui/react-use-previous@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-2dHfToCj/pzca2Ck724OZ5L0EVrr3eHRNsG/b3xQJLA2hZpVCS99bLAX+hm1IHXDEnzU6by5z/5MIY794/a8NQ=="],
"@radix-ui/react-use-rect": ["@radix-ui/react-use-rect@1.1.1", "", { "dependencies": { "@radix-ui/rect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-QTYuDesS0VtuHNNvMh+CjlKJ4LJickCMUAqjlE3+j8w+RlRpwyX3apEQKGFzbZGdo7XNG1tXa+bQqIE7HIXT2w=="],
"@radix-ui/react-use-size": ["@radix-ui/react-use-size@1.1.1", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-ewrXRDTAqAXlkl6t/fkXWNAhFX9I+CkKlw6zjEwk86RSPKwZr3xpBRso655aqYafwtnbpHLj6toFzmd6xdVptQ=="],
@@ -387,6 +394,8 @@
"@types/node": ["@types/node@24.10.1", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ=="],
"@types/prismjs": ["@types/prismjs@1.26.5", "", {}, "sha512-AUZTa7hQ2KY5L7AmtSiqxlhWxb4ina0yd8hNbl4TWuqnv/pFP0nDMb3YrfSBf4hJVGLh2YEIBfKaBW/9UEl6IQ=="],
"@types/react": ["@types/react@19.2.7", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-MWtvHrGZLFttgeEj28VXHxpmwYbor/ATPYbBfSFZEIRK0ecCFLl2Qo55z52Hss+UV9CRN7trSeq1zbgx7YDWWg=="],
"@types/react-dom": ["@types/react-dom@19.2.3", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ=="],
@@ -677,6 +686,8 @@
"prettier": ["prettier@3.7.4", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-v6UNi1+3hSlVvv8fSaoUbggEM5VErKmmpGA7Pl3HF8V6uKY7rvClBOJlH6yNwQtfTueNkGVpOv/mtWL9L4bgRA=="],
"prism-react-renderer": ["prism-react-renderer@2.4.1", "", { "dependencies": { "@types/prismjs": "^1.26.0", "clsx": "^2.0.0" }, "peerDependencies": { "react": ">=16.0.0" } }, "sha512-ey8Ls/+Di31eqzUxC46h8MksNuGx/n0AAC8uKpwFau4RPDYLuE3EXTp8N8G2vX2N7UC/+IXeNUnlWBGGcAG+Ig=="],
"prop-types": ["prop-types@15.8.1", "", { "dependencies": { "loose-envify": "^1.4.0", "object-assign": "^4.1.1", "react-is": "^16.13.1" } }, "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg=="],
"punycode": ["punycode@2.3.1", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="],
@@ -701,6 +712,8 @@
"react-router-dom": ["react-router-dom@7.10.1", "", { "dependencies": { "react-router": "7.10.1" }, "peerDependencies": { "react": ">=18", "react-dom": ">=18" } }, "sha512-JNBANI6ChGVjA5bwsUIwJk7LHKmqB4JYnYfzFwyp2t12Izva11elds2jx7Yfoup2zssedntwU0oZ5DEmk5Sdaw=="],
"react-simple-code-editor": ["react-simple-code-editor@0.14.1", "", { "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-BR5DtNRy+AswWJECyA17qhUDvrrCZ6zXOCfkQY5zSmb96BVUbpVAv03WpcjcwtCwiLbIANx3gebHOcXYn1EHow=="],
"react-smooth": ["react-smooth@4.0.4", "", { "dependencies": { "fast-equals": "^5.0.1", "prop-types": "^15.8.1", "react-transition-group": "^4.4.5" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-gnGKTpYwqL0Iii09gHobNolvX4Kiq4PKx6eWBCYYix+8cdw+cGo3do906l1NBPKkSWx1DghC1dlWG9L2uGd61Q=="],
"react-style-singleton": ["react-style-singleton@2.2.3", "", { "dependencies": { "get-nonce": "^1.0.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ=="],
@@ -799,6 +812,8 @@
"@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
"@radix-ui/react-select/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
"@radix-ui/react-separator/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.4", "", { "dependencies": { "@radix-ui/react-slot": "1.2.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-9hQc4+GNVtJAIEPEqlYqW5RiYdrr8ea5XQ0ZOnD6fgru+83kqT15mq2OCcbe8KnjRZl5vF3ks69AKz3kh1jrhg=="],
"@radix-ui/react-tooltip/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
+3
View File
@@ -23,6 +23,7 @@
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-popover": "^1.1.15",
"@radix-ui/react-scroll-area": "^1.2.10",
"@radix-ui/react-select": "^2.2.6",
"@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-tabs": "^1.1.13",
@@ -34,11 +35,13 @@
"clsx": "^2.1.1",
"date-fns": "^4.1.0",
"lucide-react": "^0.556.0",
"prism-react-renderer": "^2.4.1",
"react": "^19.2.0",
"react-day-picker": "^9.12.0",
"react-dom": "^19.2.0",
"react-hook-form": "^7.68.0",
"react-router-dom": "^7.10.1",
"react-simple-code-editor": "^0.14.1",
"recharts": "^2.12.0",
"sonner": "^2.0.7",
"tailwind-merge": "^3.4.0",
+7 -5
View File
@@ -43,16 +43,18 @@ function Layout() {
return (
<SidebarProvider>
<AppSidebar />
<main className="flex-1 overflow-auto">
<header className="flex h-12 items-center justify-end px-4 border-b">
<main className="flex-1 flex flex-col min-h-0 overflow-hidden">
<header className="flex h-12 items-center justify-end px-4 border-b shrink-0">
<div className="flex items-center gap-4">
<ConnectionIndicator />
<ThemeToggle />
</div>
</header>
<Suspense fallback={<PageLoader />}>
<Outlet />
</Suspense>
<div className="flex-1 overflow-auto min-h-0">
<Suspense fallback={<PageLoader />}>
<Outlet />
</Suspense>
</div>
<LocalhostDisclaimer />
</main>
</SidebarProvider>
+237
View File
@@ -0,0 +1,237 @@
/**
* Code Editor Component
* Lightweight JSON editor with syntax highlighting, line numbers, and validation
* Uses react-simple-code-editor + prism-react-renderer for minimal bundle size (~18KB)
*/
import { useState, useCallback, useMemo, useEffect, useRef } from 'react';
import Editor from 'react-simple-code-editor';
import { Highlight, themes } from 'prism-react-renderer';
import { useTheme } from '@/hooks/use-theme';
import { cn } from '@/lib/utils';
import { isSensitiveKey } from '@/lib/sensitive-keys';
import { AlertCircle, CheckCircle2, Eye, EyeOff } from 'lucide-react';
import { Button } from '@/components/ui/button';
interface CodeEditorProps {
value: string;
onChange: (value: string) => void;
language?: 'json' | 'yaml';
readonly?: boolean;
className?: string;
minHeight?: string;
}
interface ValidationResult {
valid: boolean;
error?: string;
line?: number;
}
/**
* Validate JSON and extract error location
*/
function validateJson(code: string): ValidationResult {
if (!code.trim()) {
return { valid: true };
}
try {
JSON.parse(code);
return { valid: true };
} catch (e) {
const error = e as SyntaxError;
const message = error.message;
// Try to extract line number from error message
// Format: "... at position X" or "... at line Y column Z"
const posMatch = message.match(/position (\d+)/);
if (posMatch) {
const pos = parseInt(posMatch[1], 10);
const lines = code.substring(0, pos).split('\n');
return {
valid: false,
error: message,
line: lines.length,
};
}
return {
valid: false,
error: message,
};
}
}
export function CodeEditor({
value,
onChange,
language = 'json',
readonly = false,
className,
minHeight = '300px',
}: CodeEditorProps) {
const { isDark } = useTheme();
const [isFocused, setIsFocused] = useState(false);
const [isMasked, setIsMasked] = useState(true);
// Force Editor remount when theme changes (works around react-simple-code-editor caching)
const [editorKey, setEditorKey] = useState(0);
const isFirstRender = useRef(true);
useEffect(() => {
// Skip first render, only trigger on theme changes
if (isFirstRender.current) {
isFirstRender.current = false;
return;
}
setEditorKey((k) => k + 1);
}, [isDark]);
// Validate on every change for JSON
const validation = useMemo(() => {
if (language === 'json') {
return validateJson(value);
}
return { valid: true };
}, [value, language]);
// Highlight function using prism-react-renderer
// Note: Line numbers removed - they break textarea/pre alignment in react-simple-code-editor
const highlightCode = useCallback(
(code: string) => (
<Highlight theme={isDark ? themes.nightOwl : themes.github} code={code} language={language}>
{({ tokens, getLineProps, getTokenProps }) => {
let nextValueIsSensitive = false;
return (
<>
{tokens.map((line, i) => (
<div
key={i}
{...getLineProps({ line })}
className={cn(validation.line === i + 1 && 'bg-destructive/20')}
>
{line.map((token, key) => {
let isSensitive = false;
// Check for sensitive keys
if (token.types.includes('property')) {
const content = token.content.replace(/['"]/g, '');
// Use shared sensitive key detection utility
if (isSensitiveKey(content)) {
nextValueIsSensitive = true;
} else {
nextValueIsSensitive = false;
}
}
// Apply masking to values following sensitive keys
else if (
(token.types.includes('string') ||
token.types.includes('number') ||
token.types.includes('boolean')) &&
nextValueIsSensitive
) {
isSensitive = true;
// Consumes the flag for this value
nextValueIsSensitive = false;
}
// Reset flag on commas or new keys (handled by property check),
// but persist through colons and whitespace
else if (token.types.includes('punctuation')) {
if (
token.content !== ':' &&
token.content !== '[' &&
token.content !== '{'
) {
nextValueIsSensitive = false;
}
}
const tokenProps = getTokenProps({ token });
if (isSensitive && isMasked) {
tokenProps.className = cn(
tokenProps.className,
'blur-[3px] select-none opacity-70 transition-all duration-200'
);
}
return <span key={key} {...tokenProps} />;
})}
</div>
))}
</>
);
}}
</Highlight>
),
[isDark, language, validation.line, isMasked]
);
return (
<div className={cn('flex flex-col', className)}>
{/* Editor container */}
<div
className={cn(
'relative rounded-md border overflow-hidden',
'bg-muted/30',
isFocused && 'ring-2 ring-ring ring-offset-2 ring-offset-background',
readonly && 'opacity-70 cursor-not-allowed',
!validation.valid && 'border-destructive'
)}
style={{ minHeight }}
>
<Editor
value={value}
onValueChange={readonly ? () => {} : onChange}
highlight={highlightCode}
key={editorKey}
padding={12}
disabled={readonly}
onFocus={() => setIsFocused(true)}
onBlur={() => setIsFocused(false)}
textareaClassName={cn(
'focus:outline-none font-mono text-sm',
readonly && 'cursor-not-allowed'
)}
preClassName="font-mono text-sm"
style={{
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
fontSize: '0.875rem',
minHeight,
}}
/>
{/* Secrets Toggle Overlay */}
<div className="absolute top-2 right-2 z-10 opacity-50 hover:opacity-100 transition-opacity">
<Button
variant="ghost"
size="icon"
className="h-6 w-6 bg-background/50 hover:bg-background border shadow-sm rounded-full"
onClick={() => setIsMasked(!isMasked)}
title={isMasked ? 'Reveal sensitive values' : 'Mask sensitive values'}
>
{isMasked ? <Eye className="h-3 w-3" /> : <EyeOff className="h-3 w-3" />}
</Button>
</div>
</div>
{/* Validation status */}
<div className="flex items-center gap-2 mt-2 text-xs">
{validation.valid ? (
<span className="flex items-center gap-1 text-muted-foreground">
<CheckCircle2 className="w-3 h-3 text-green-500" />
Valid {language.toUpperCase()}
</span>
) : (
<span className="flex items-center gap-1 text-destructive">
<AlertCircle className="w-3 h-3" />
{validation.error}
{validation.line && ` (line ${validation.line})`}
</span>
)}
{readonly && <span className="ml-auto text-muted-foreground">(Read-only)</span>}
</div>
</div>
);
}
+1 -18
View File
@@ -1,30 +1,13 @@
import { Shield, X } from 'lucide-react';
import { useState } from 'react';
import { useSidebar } from '@/hooks/use-sidebar';
export function LocalhostDisclaimer() {
const [dismissed, setDismissed] = useState(false);
const { state, isMobile } = useSidebar();
if (dismissed) return null;
// Calculate the left margin based on sidebar state
// When expanded: sidebar width is 16rem
// When collapsed: sidebar width is 3rem
// On mobile: sidebar is overlay, no margin needed
const getLeftMargin = () => {
if (isMobile) return '0';
return state === 'expanded' ? '16rem' : '3rem';
};
return (
<div
className="fixed bottom-0 bg-yellow-50 dark:bg-yellow-900/20 border-t border-yellow-200 dark:border-yellow-800 px-4 py-2 transition-all duration-200 ease-linear z-50"
style={{
left: getLeftMargin(),
right: '0',
}}
>
<div className="w-full bg-yellow-50 dark:bg-yellow-900/20 border-t border-yellow-200 dark:border-yellow-800 px-4 py-2 transition-colors duration-200">
<div className="flex items-center justify-center gap-4">
<div className="flex items-center gap-2 text-sm text-yellow-800 dark:text-yellow-200">
<Shield className="w-4 h-4 flex-shrink-0" />
+344
View File
@@ -0,0 +1,344 @@
/**
* Profile Create Dialog Component
* Modal dialog with tabbed interface for creating new API profiles
* Includes Quick Start templates and advanced model configuration
*/
import { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { useCreateProfile } from '@/hooks/use-profiles';
import { Loader2, Plus, AlertTriangle, Info, Eye, EyeOff } from 'lucide-react';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';
const DEFAULT_MODEL = 'claude-sonnet-4-5-20250929';
const schema = z.object({
name: z
.string()
.min(1, 'Name is required')
.regex(/^[a-zA-Z][a-zA-Z0-9._-]*$/, 'Must start with letter, only letters/numbers/.-_'),
baseUrl: z.string().url('Invalid URL format'),
apiKey: z.string().min(1, 'API key is required'),
model: z.string().optional(),
opusModel: z.string().optional(),
sonnetModel: z.string().optional(),
haikuModel: z.string().optional(),
});
type FormData = z.infer<typeof schema>;
interface ProfileCreateDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onSuccess: (name: string) => void;
}
// Common URL mistakes to warn about
const PROBLEMATIC_PATHS = ['/chat/completions', '/v1/messages', '/messages', '/completions'];
export function ProfileCreateDialog({ open, onOpenChange, onSuccess }: ProfileCreateDialogProps) {
const createMutation = useCreateProfile();
const [activeTab, setActiveTab] = useState('basic');
const [urlWarning, setUrlWarning] = useState<string | null>(null);
const [showApiKey, setShowApiKey] = useState(false);
const {
register,
handleSubmit,
formState: { errors },
watch,
reset,
} = useForm<FormData>({
resolver: zodResolver(schema),
defaultValues: {
name: '',
baseUrl: '',
apiKey: '',
model: '',
opusModel: '',
sonnetModel: '',
haikuModel: '',
},
});
const baseUrlValue = watch('baseUrl');
// Reset form when dialog opens
useEffect(() => {
if (open) {
reset();
setActiveTab('basic');
setUrlWarning(null);
setShowApiKey(false);
}
}, [open, reset]);
// Check for common URL mistakes
useEffect(() => {
if (baseUrlValue) {
const lowerUrl = baseUrlValue.toLowerCase();
for (const path of PROBLEMATIC_PATHS) {
if (lowerUrl.endsWith(path)) {
const suggestedUrl = baseUrlValue.replace(new RegExp(path + '$', 'i'), '');
setUrlWarning(
`URL ends with "${path}" - Claude appends this automatically. You likely want: ${suggestedUrl}`
);
return;
}
}
}
setUrlWarning(null);
}, [baseUrlValue]);
const onSubmit = async (data: FormData) => {
try {
await createMutation.mutateAsync(data);
toast.success(`Profile "${data.name}" created`);
onSuccess(data.name);
onOpenChange(false);
} catch (error) {
toast.error((error as Error).message || 'Failed to create profile');
}
};
const hasBasicErrors = !!errors.name || !!errors.baseUrl || !!errors.apiKey;
const hasModelErrors =
!!errors.model || !!errors.opusModel || !!errors.sonnetModel || !!errors.haikuModel;
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[600px] p-0 gap-0 overflow-hidden">
<DialogHeader className="p-6 pb-4 border-b">
<DialogTitle className="flex items-center gap-2">
<Plus className="w-5 h-5 text-primary" />
Create API Profile
</DialogTitle>
<DialogDescription>Configure a custom API endpoint for Claude Code.</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit(onSubmit)}>
<Tabs value={activeTab} onValueChange={setActiveTab} className="flex flex-col">
<div className="px-6 pt-4">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="basic" className="relative">
Basic Information
{hasBasicErrors && (
<span className="absolute top-1 right-2 w-2 h-2 rounded-full bg-destructive animate-pulse" />
)}
</TabsTrigger>
<TabsTrigger value="models" className="relative">
Model Configuration
{hasModelErrors && (
<span className="absolute top-1 right-2 w-2 h-2 rounded-full bg-destructive animate-pulse" />
)}
</TabsTrigger>
</TabsList>
</div>
<div className="flex-1 overflow-y-auto max-h-[60vh]">
<TabsContent value="basic" className="p-6 space-y-6 mt-0">
<div className="space-y-4">
{/* Name */}
<div className="space-y-1.5">
<Label htmlFor="name">
Profile Name <span className="text-destructive">*</span>
</Label>
<Input
id="name"
{...register('name')}
placeholder="my-api"
className="font-mono"
/>
{errors.name ? (
<p className="text-xs text-destructive">{errors.name.message}</p>
) : (
<p className="text-xs text-muted-foreground">
Used in CLI:{' '}
<code className="bg-muted px-1 rounded text-[10px]">
ccs my-api "prompt"
</code>
</p>
)}
</div>
{/* Base URL */}
<div className="space-y-1.5">
<Label htmlFor="baseUrl">
API Base URL <span className="text-destructive">*</span>
</Label>
<Input
id="baseUrl"
{...register('baseUrl')}
placeholder="https://api.example.com/v1"
/>
{errors.baseUrl ? (
<p className="text-xs text-destructive">{errors.baseUrl.message}</p>
) : urlWarning ? (
<div className="flex items-start gap-2 text-xs text-yellow-600 bg-yellow-50 dark:bg-yellow-900/20 p-2 rounded">
<AlertTriangle className="w-4 h-4 shrink-0 mt-0.5" />
<span>{urlWarning}</span>
</div>
) : (
<p className="text-xs text-muted-foreground">
The endpoint that accepts OpenAI-compatible and Anthropic requests
</p>
)}
</div>
{/* API Key */}
<div className="space-y-1.5">
<Label htmlFor="apiKey">
API Key <span className="text-destructive">*</span>
</Label>
<div className="relative">
<Input
id="apiKey"
type={showApiKey ? 'text' : 'password'}
{...register('apiKey')}
placeholder="sk-..."
className="pr-10"
/>
<Button
type="button"
variant="ghost"
size="icon"
className="absolute right-0 top-0 h-9 w-9 text-muted-foreground hover:text-foreground"
onClick={() => setShowApiKey(!showApiKey)}
tabIndex={-1}
>
{showApiKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
<span className="sr-only">Toggle API key visibility</span>
</Button>
</div>
{errors.apiKey && (
<p className="text-xs text-destructive">{errors.apiKey.message}</p>
)}
</div>
</div>
</TabsContent>
<TabsContent value="models" className="p-6 mt-0 space-y-6">
<div className="flex items-start gap-3 p-4 bg-blue-50 dark:bg-blue-950/20 text-blue-800 dark:text-blue-300 rounded-md text-sm border border-blue-100 dark:border-blue-900/30">
<Info className="w-5 h-5 shrink-0 mt-0.5" />
<div>
<p className="font-medium mb-1">Model Mapping</p>
<p className="text-xs opacity-90">
Claude Code requests specific model tiers (Opus/Sonnet/Haiku). Map these tiers
to the specific models supported by your API provider.
</p>
</div>
</div>
<div className="space-y-5">
<div className="space-y-1.5">
<Label htmlFor="model">
Default Model
<Badge variant="outline" className="ml-2 text-[10px] font-mono">
ANTHROPIC_MODEL
</Badge>
</Label>
<Input
id="model"
{...register('model')}
placeholder={DEFAULT_MODEL}
className="font-mono text-sm"
/>
<p className="text-xs text-muted-foreground">
Fallback model if no specific tier is requested
</p>
</div>
<div className="grid gap-4 pt-2 border-t">
<div className="space-y-1.5">
<Label htmlFor="sonnetModel" className="text-sm">
Sonnet Mapping (Primary)
<Badge variant="outline" className="ml-2 text-[10px] font-mono">
DEFAULT_SONNET
</Badge>
</Label>
<Input
id="sonnetModel"
{...register('sonnetModel')}
placeholder="e.g. gpt-4o, claude-3-5-sonnet"
className="font-mono text-sm h-9"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="opusModel" className="text-sm">
Opus Mapping (Complex Tasks)
<Badge variant="outline" className="ml-2 text-[10px] font-mono">
DEFAULT_OPUS
</Badge>
</Label>
<Input
id="opusModel"
{...register('opusModel')}
placeholder="e.g. o1-preview, claude-3-opus"
className="font-mono text-sm h-9"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="haikuModel" className="text-sm">
Haiku Mapping (Fast Tasks)
<Badge variant="outline" className="ml-2 text-[10px] font-mono">
DEFAULT_HAIKU
</Badge>
</Label>
<Input
id="haikuModel"
{...register('haikuModel')}
placeholder="e.g. gpt-4o-mini, claude-3-haiku"
className="font-mono text-sm h-9"
/>
</div>
</div>
</div>
</TabsContent>
</div>
<DialogFooter className="p-6 pt-2 border-t bg-muted/10">
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button
type="submit"
disabled={createMutation.isPending}
className={cn(createMutation.isPending && 'opacity-80')}
>
{createMutation.isPending ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
Creating...
</>
) : (
<>
<Plus className="w-4 h-4 mr-2" />
Create Profile
</>
)}
</Button>
</DialogFooter>
</Tabs>
</form>
</DialogContent>
</Dialog>
);
}
+100 -3
View File
@@ -1,8 +1,10 @@
/**
* Profile Dialog Component
* Phase 03: REST API Routes & CRUD
* Updated: Added model mapping fields for Opus/Sonnet/Haiku
*/
import { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
@@ -12,6 +14,9 @@ import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useCreateProfile, useUpdateProfile } from '@/hooks/use-profiles';
import type { Profile } from '@/lib/api-client';
import { ChevronDown, ChevronRight } from 'lucide-react';
const DEFAULT_MODEL = 'claude-sonnet-4-5-20250929';
const schema = z.object({
name: z
@@ -21,6 +26,9 @@ const schema = z.object({
baseUrl: z.string().url('Invalid URL'),
apiKey: z.string().min(10, 'API key must be at least 10 characters'),
model: z.string().optional(),
opusModel: z.string().optional(),
sonnetModel: z.string().optional(),
haikuModel: z.string().optional(),
});
type FormData = z.infer<typeof schema>;
@@ -34,12 +42,14 @@ interface ProfileDialogProps {
export function ProfileDialog({ open, onClose, profile }: ProfileDialogProps) {
const createMutation = useCreateProfile();
const updateMutation = useUpdateProfile();
const [showModelMapping, setShowModelMapping] = useState(false);
const {
register,
handleSubmit,
formState: { errors },
reset,
watch,
} = useForm<FormData>({
resolver: zodResolver(schema),
defaultValues: profile
@@ -48,10 +58,30 @@ export function ProfileDialog({ open, onClose, profile }: ProfileDialogProps) {
baseUrl: '',
apiKey: '',
model: '',
opusModel: '',
sonnetModel: '',
haikuModel: '',
}
: undefined,
});
// Watch model field to auto-expand model mapping when custom model is entered
const modelValue = watch('model');
useEffect(() => {
// Auto-show model mapping if user enters a custom model (not default)
if (modelValue && modelValue !== DEFAULT_MODEL && modelValue.trim() !== '') {
setShowModelMapping(true);
}
}, [modelValue]);
// Reset state when dialog opens/closes
useEffect(() => {
if (!open) {
setShowModelMapping(false);
}
}, [open]);
const onSubmit = async (data: FormData) => {
try {
if (profile) {
@@ -62,6 +92,9 @@ export function ProfileDialog({ open, onClose, profile }: ProfileDialogProps) {
baseUrl: data.baseUrl,
apiKey: data.apiKey,
model: data.model,
opusModel: data.opusModel,
sonnetModel: data.sonnetModel,
haikuModel: data.haikuModel,
},
});
} else {
@@ -78,7 +111,7 @@ export function ProfileDialog({ open, onClose, profile }: ProfileDialogProps) {
return (
<Dialog open={open} onOpenChange={onClose}>
<DialogContent>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>{profile ? 'Edit Profile' : 'Create API Profile'}</DialogTitle>
</DialogHeader>
@@ -104,8 +137,72 @@ export function ProfileDialog({ open, onClose, profile }: ProfileDialogProps) {
</div>
<div>
<Label htmlFor="model">Model (optional)</Label>
<Input id="model" {...register('model')} placeholder="claude-sonnet-4-5-20250929" />
<Label htmlFor="model">Default Model (ANTHROPIC_MODEL)</Label>
<Input id="model" {...register('model')} placeholder={DEFAULT_MODEL} />
<p className="text-xs text-muted-foreground mt-1">
Leave blank to use: {DEFAULT_MODEL}
</p>
</div>
{/* Model Mapping Section */}
<div className="border rounded-md">
<button
type="button"
className="w-full flex items-center justify-between p-3 text-sm font-medium hover:bg-muted/50 transition-colors"
onClick={() => setShowModelMapping(!showModelMapping)}
>
<span>Model Mapping (Opus/Sonnet/Haiku)</span>
{showModelMapping ? (
<ChevronDown className="w-4 h-4" />
) : (
<ChevronRight className="w-4 h-4" />
)}
</button>
{showModelMapping && (
<div className="p-3 pt-0 space-y-3 border-t">
<p className="text-xs text-muted-foreground">
Configure different model IDs for each tier. Useful for API proxies that route
different model types to different backends.
</p>
<div>
<Label htmlFor="opusModel" className="text-xs">
Opus Model (ANTHROPIC_DEFAULT_OPUS_MODEL)
</Label>
<Input
id="opusModel"
{...register('opusModel')}
placeholder={modelValue || DEFAULT_MODEL}
className="h-8 text-sm"
/>
</div>
<div>
<Label htmlFor="sonnetModel" className="text-xs">
Sonnet Model (ANTHROPIC_DEFAULT_SONNET_MODEL)
</Label>
<Input
id="sonnetModel"
{...register('sonnetModel')}
placeholder={modelValue || DEFAULT_MODEL}
className="h-8 text-sm"
/>
</div>
<div>
<Label htmlFor="haikuModel" className="text-xs">
Haiku Model (ANTHROPIC_DEFAULT_HAIKU_MODEL)
</Label>
<Input
id="haikuModel"
{...register('haikuModel')}
placeholder={modelValue || DEFAULT_MODEL}
className="h-8 text-sm"
/>
</div>
</div>
)}
</div>
<div className="flex justify-end gap-2 pt-2">
+506
View File
@@ -0,0 +1,506 @@
/**
* Profile Editor Component
* Inline editor for API profile settings with 2-column layout (Friendly UI + Raw JSON)
*/
import { useState, useMemo, useCallback, lazy, Suspense } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { MaskedInput } from '@/components/ui/masked-input';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Badge } from '@/components/ui/badge';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { Save, Loader2, Code2, Trash2, RefreshCw, Plus, X, Info } from 'lucide-react';
import { toast } from 'sonner';
import { CopyButton } from '@/components/ui/copy-button';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
// Lazy load CodeEditor to reduce initial bundle size
const CodeEditor = lazy(() =>
import('@/components/code-editor').then((m) => ({ default: m.CodeEditor }))
);
interface Settings {
env?: Record<string, string>;
}
interface SettingsResponse {
profile: string;
settings: Settings;
mtime: number;
path: string;
}
interface ProfileEditorProps {
profileName: string;
onDelete?: () => void;
}
export function ProfileEditor({ profileName, onDelete }: ProfileEditorProps) {
const [localEdits, setLocalEdits] = useState<Record<string, string>>({});
const [conflictDialog, setConflictDialog] = useState(false);
const [rawJsonEdits, setRawJsonEdits] = useState<string | null>(null);
const [newEnvKey, setNewEnvKey] = useState('');
const queryClient = useQueryClient();
// Fetch settings for selected profile
const { data, isLoading, refetch } = useQuery<SettingsResponse>({
queryKey: ['settings', profileName],
queryFn: () => fetch(`/api/settings/${profileName}/raw`).then((r) => r.json()),
});
// Derive raw JSON content
const settings = data?.settings;
const rawJsonContent = useMemo(() => {
if (rawJsonEdits !== null) {
return rawJsonEdits;
}
if (settings) {
return JSON.stringify(settings, null, 2);
}
return '';
}, [rawJsonEdits, settings]);
const handleRawJsonChange = useCallback((value: string) => {
setRawJsonEdits(value);
}, []);
// Derive current settings by merging original data with local edits
// Prioritize rawJsonEdits if available
const currentSettings = useMemo((): Settings | undefined => {
if (rawJsonEdits !== null) {
try {
return JSON.parse(rawJsonEdits);
} catch {
// If invalid JSON, fall back to undefined or partial state
// The UI will likely show empty or potentially broken state if JSON is invalid,
// but the Raw Editor will show the error.
}
}
if (!settings) return undefined;
return {
...settings,
env: {
...settings.env,
...localEdits,
},
};
}, [settings, localEdits, rawJsonEdits]);
// Sync Visual Editor changes to Raw JSON
const updateEnvValue = (key: string, value: string) => {
const newEnv = { ...(currentSettings?.env || {}), [key]: value };
// Update local edits
setLocalEdits((prev) => ({
...prev,
[key]: value,
}));
// Update rawJsonEdits to keep sync
const newSettings = { ...currentSettings, env: newEnv };
setRawJsonEdits(JSON.stringify(newSettings, null, 2));
};
const addNewEnvVar = () => {
if (!newEnvKey.trim()) return;
const key = newEnvKey.trim();
const newEnv = { ...(currentSettings?.env || {}), [key]: '' };
setLocalEdits((prev) => ({
...prev,
[key]: '',
}));
const newSettings = { ...currentSettings, env: newEnv };
setRawJsonEdits(JSON.stringify(newSettings, null, 2));
setNewEnvKey('');
};
// Check if raw JSON is valid
const isRawJsonValid = useMemo(() => {
try {
JSON.parse(rawJsonContent);
return true;
} catch {
return false;
}
}, [rawJsonContent]);
// Check if there are unsaved changes
const hasChanges = useMemo(() => {
if (rawJsonEdits !== null) {
return rawJsonEdits !== JSON.stringify(settings, null, 2);
}
return Object.keys(localEdits).length > 0;
}, [rawJsonEdits, localEdits, settings]);
// Save mutation
const saveMutation = useMutation({
mutationFn: async () => {
let settingsToSave: Settings;
try {
// Always save from rawJsonContent as it's the source of truth
settingsToSave = JSON.parse(rawJsonContent);
} catch {
// Fallback (should typically not happen if validation is correct)
settingsToSave = {
...data?.settings,
env: {
...data?.settings?.env,
...localEdits,
},
};
}
const res = await fetch(`/api/settings/${profileName}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
settings: settingsToSave,
expectedMtime: data?.mtime,
}),
});
if (res.status === 409) {
throw new Error('CONFLICT');
}
if (!res.ok) {
throw new Error('Failed to save');
}
return res.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['settings', profileName] });
queryClient.invalidateQueries({ queryKey: ['profiles'] });
setLocalEdits({});
setRawJsonEdits(null);
toast.success('Settings saved');
},
onError: (error: Error) => {
if (error.message === 'CONFLICT') {
setConflictDialog(true);
} else {
toast.error(error.message);
}
},
});
const handleSave = () => {
saveMutation.mutate();
};
const handleConflictResolve = async (overwrite: boolean) => {
setConflictDialog(false);
if (overwrite) {
await refetch();
saveMutation.mutate();
} else {
setLocalEdits({});
setRawJsonEdits(null);
}
};
const isSensitiveKey = (key: string): boolean => {
const sensitivePatterns = [
/^ANTHROPIC_AUTH_TOKEN$/,
/_API_KEY$/,
/_AUTH_TOKEN$/,
/^API_KEY$/,
/^AUTH_TOKEN$/,
/_SECRET$/,
/^SECRET$/,
];
return sensitivePatterns.some((pattern) => pattern.test(key));
};
// Reset state when profile changes
const profileKey = profileName;
// Render Left Column Content (Environment + Info + Usage)
const renderFriendlyUI = () => (
<div className="h-full flex flex-col">
<Tabs defaultValue="env" className="h-full flex flex-col">
<div className="px-4 pt-4 shrink-0">
<TabsList className="w-full">
<TabsTrigger value="env" className="flex-1">
Environment Variables
</TabsTrigger>
<TabsTrigger value="info" className="flex-1">
Info & Usage
</TabsTrigger>
</TabsList>
</div>
<div className="flex-1 overflow-hidden flex flex-col">
<TabsContent
value="env"
className="flex-1 mt-0 border-0 p-0 data-[state=inactive]:hidden flex flex-col overflow-hidden"
>
{/* Scrollable Environment Variables List */}
<ScrollArea className="flex-1">
<div className="p-4 space-y-4">
{currentSettings?.env && Object.keys(currentSettings.env).length > 0 ? (
<>
{Object.entries(currentSettings.env).map(([key, value]) => (
<div key={key} className="space-y-1.5">
<Label className="text-xs font-medium flex items-center gap-2 text-muted-foreground">
{key}
{isSensitiveKey(key) && (
<Badge variant="secondary" className="text-[10px] px-1 py-0 h-4">
sensitive
</Badge>
)}
</Label>
{isSensitiveKey(key) ? (
<MaskedInput
value={value}
onChange={(e) => updateEnvValue(key, e.target.value)}
className="font-mono text-sm h-8"
/>
) : (
<Input
value={value}
onChange={(e) => updateEnvValue(key, e.target.value)}
className="font-mono text-sm h-8"
/>
)}
</div>
))}
</>
) : (
<div className="py-8 text-center text-muted-foreground bg-muted/30 rounded-lg border border-dashed text-sm">
<p>No environment variables configured.</p>
<p className="text-xs mt-1 opacity-70">
Add variables using the input below or edit the JSON directly.
</p>
</div>
)}
</div>
</ScrollArea>
{/* Fixed Add Input at Bottom */}
<div className="p-4 border-t bg-background shrink-0">
<Label className="text-xs font-medium text-muted-foreground">
Add Environment Variable
</Label>
<div className="flex gap-2 mt-2">
<Input
placeholder="VARIABLE_NAME"
value={newEnvKey}
onChange={(e) => setNewEnvKey(e.target.value.toUpperCase())}
className="font-mono text-sm h-8"
onKeyDown={(e) => e.key === 'Enter' && addNewEnvVar()}
/>
<Button
variant="outline"
size="sm"
className="h-8"
onClick={addNewEnvVar}
disabled={!newEnvKey.trim()}
>
<Plus className="w-4 h-4" />
</Button>
</div>
</div>
</TabsContent>
<TabsContent
value="info"
className="h-full mt-0 border-0 p-0 data-[state=inactive]:hidden"
>
<ScrollArea className="h-full">
<div className="p-4 space-y-6">
{/* Profile Information */}
<div>
<h3 className="text-sm font-medium flex items-center gap-2 mb-3">
<Info className="w-4 h-4" />
Profile Information
</h3>
<div className="space-y-3 bg-card rounded-lg border p-4 shadow-sm">
{data && (
<>
<div className="grid grid-cols-[100px_1fr] gap-2 text-sm items-center">
<span className="font-medium text-muted-foreground">Profile Name</span>
<span className="font-mono">{data.profile}</span>
</div>
<div className="grid grid-cols-[100px_1fr] gap-2 text-sm items-center">
<span className="font-medium text-muted-foreground">File Path</span>
<div className="flex items-center gap-2 min-w-0">
<code className="bg-muted px-1.5 py-0.5 rounded text-xs break-all">
{data.path}
</code>
<CopyButton value={data.path} size="icon" className="h-5 w-5" />
</div>
</div>
<div className="grid grid-cols-[100px_1fr] gap-2 text-sm items-center">
<span className="font-medium text-muted-foreground">Last Modified</span>
<span className="text-xs">{new Date(data.mtime).toLocaleString()}</span>
</div>
</>
)}
</div>
</div>
{/* Usage */}
<div>
<h3 className="text-sm font-medium mb-3">Quick Usage</h3>
<div className="space-y-3 bg-card rounded-lg border p-4 shadow-sm">
<div>
<Label className="text-xs text-muted-foreground">Run with profile</Label>
<div className="mt-1 flex gap-2">
<code className="flex-1 px-2 py-1.5 bg-muted rounded text-xs font-mono truncate">
ccs {profileName} "prompt"
</code>
<CopyButton
value={`ccs ${profileName} "prompt"`}
size="icon"
className="h-6 w-6"
/>
</div>
</div>
<div>
<Label className="text-xs text-muted-foreground">Set as default</Label>
<div className="mt-1 flex gap-2">
<code className="flex-1 px-2 py-1.5 bg-muted rounded text-xs font-mono truncate">
ccs default {profileName}
</code>
<CopyButton
value={`ccs default ${profileName}`}
size="icon"
className="h-6 w-6"
/>
</div>
</div>
</div>
</div>
</div>
</ScrollArea>
</TabsContent>
</div>
</Tabs>
</div>
);
// Render Right Column Content (Raw JSON Editor)
const renderRawEditor = () => (
<Suspense
fallback={
<div className="flex items-center justify-center h-full">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
<span className="ml-2 text-muted-foreground">Loading editor...</span>
</div>
}
>
<div className="h-full flex flex-col">
{!isRawJsonValid && rawJsonEdits !== null && (
<div className="mb-2 px-3 py-2 bg-destructive/10 text-destructive text-sm rounded-md flex items-center gap-2 mx-6 mt-4 shrink-0">
<X className="w-4 h-4" />
Invalid JSON syntax
</div>
)}
<div className="flex-1 overflow-hidden px-6 pb-6 pt-4">
<div className="h-full border rounded-md overflow-hidden bg-background">
<CodeEditor
value={rawJsonContent}
onChange={handleRawJsonChange}
language="json"
minHeight="100%"
/>
</div>
</div>
</div>
</Suspense>
);
return (
<div key={profileKey} className="flex-1 flex flex-col overflow-hidden">
{/* Header */}
<div className="px-6 py-4 border-b bg-background flex items-center justify-between shrink-0">
<div>
<div className="flex items-center gap-2">
<h2 className="text-lg font-semibold">{profileName}</h2>
{data && (
<Badge variant="outline" className="text-xs">
{data.path.replace(/^.*\//, '')}
</Badge>
)}
</div>
{data && (
<p className="text-xs text-muted-foreground mt-0.5">
Last modified: {new Date(data.mtime).toLocaleString()}
</p>
)}
</div>
<div className="flex items-center gap-2">
<Button variant="ghost" size="sm" onClick={() => refetch()} disabled={isLoading}>
<RefreshCw className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`} />
</Button>
{onDelete && (
<Button variant="ghost" size="sm" onClick={onDelete}>
<Trash2 className="w-4 h-4 text-destructive" />
</Button>
)}
<Button
size="sm"
onClick={handleSave}
disabled={saveMutation.isPending || !hasChanges || !isRawJsonValid}
>
{saveMutation.isPending ? (
<>
<Loader2 className="w-4 h-4 mr-1 animate-spin" />
Saving...
</>
) : (
<>
<Save className="w-4 h-4 mr-1" />
Save
</>
)}
</Button>
</div>
</div>
{isLoading ? (
<div className="flex-1 flex items-center justify-center">
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
<span className="ml-3 text-muted-foreground">Loading settings...</span>
</div>
) : (
// Split Layout (40% Left / 60% Right)
<div className="flex-1 grid grid-cols-[40%_60%] divide-x overflow-hidden">
{/* Left Column: Friendly UI */}
<div className="flex flex-col overflow-hidden bg-muted/5">{renderFriendlyUI()}</div>
{/* Right Column: Raw Editor */}
<div className="flex flex-col overflow-hidden">
<div className="px-6 py-2 bg-muted/30 border-b flex items-center gap-2 shrink-0 h-[45px]">
<Code2 className="w-4 h-4 text-muted-foreground" />
<span className="text-sm font-medium text-muted-foreground">
Raw Configuration (JSON)
</span>
</div>
{renderRawEditor()}
</div>
</div>
)}
<ConfirmDialog
open={conflictDialog}
title="File Modified Externally"
description="This settings file was modified by another process. Overwrite with your changes or discard?"
confirmText="Overwrite"
variant="destructive"
onConfirm={() => handleConflictResolve(true)}
onCancel={() => handleConflictResolve(false)}
/>
</div>
);
}
+91 -12
View File
@@ -1,10 +1,10 @@
/**
* Settings Dialog Component
* Reusable dialog for editing profile environment variables
* Features: masked inputs for sensitive keys, conflict detection, save/cancel
* Features: masked inputs for sensitive keys, conflict detection, save/cancel, raw JSON editor
*/
import { useState, useMemo, useCallback } from 'react';
import { useState, useMemo, useCallback, lazy, Suspense } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
Dialog,
@@ -18,9 +18,14 @@ import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { MaskedInput } from '@/components/ui/masked-input';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { Save, X, Loader2 } from 'lucide-react';
import { Save, X, Loader2, Code2 } from 'lucide-react';
import { toast } from 'sonner';
// Lazy load CodeEditor to reduce initial bundle size
const CodeEditor = lazy(() =>
import('@/components/code-editor').then((m) => ({ default: m.CodeEditor }))
);
interface Settings {
env?: Record<string, string>;
}
@@ -55,6 +60,8 @@ function SettingsDialogContent({
}) {
const [localEdits, setLocalEdits] = useState<Record<string, string>>({});
const [conflictDialog, setConflictDialog] = useState(false);
const [rawJsonEdits, setRawJsonEdits] = useState<string | null>(null);
const [activeTab, setActiveTab] = useState('env');
const queryClient = useQueryClient();
// Fetch settings for selected profile
@@ -63,6 +70,23 @@ function SettingsDialogContent({
queryFn: () => fetch(`/api/settings/${profileName}/raw`).then((r) => r.json()),
});
// Derive raw JSON content: use edits if available, otherwise serialize from data
const settings = data?.settings;
const rawJsonContent = useMemo(() => {
if (rawJsonEdits !== null) {
return rawJsonEdits;
}
if (settings) {
return JSON.stringify(settings, null, 2);
}
return '';
}, [rawJsonEdits, settings]);
// Update raw JSON when user edits
const handleRawJsonChange = useCallback((value: string) => {
setRawJsonEdits(value);
}, []);
// Derive current settings by merging original data with local edits
const currentSettings = useMemo((): Settings | undefined => {
const settings = data?.settings;
@@ -76,16 +100,39 @@ function SettingsDialogContent({
};
}, [data?.settings, localEdits]);
// Check if raw JSON is valid
const isRawJsonValid = useMemo(() => {
try {
JSON.parse(rawJsonContent);
return true;
} catch {
return false;
}
}, [rawJsonContent]);
// Save mutation
const saveMutation = useMutation({
mutationFn: async () => {
const settingsToSave: Settings = {
...data?.settings,
env: {
...data?.settings?.env,
...localEdits,
},
};
let settingsToSave: Settings;
// Determine what to save based on active tab
if (activeTab === 'raw') {
// Parse raw JSON content
try {
settingsToSave = JSON.parse(rawJsonContent);
} catch {
throw new Error('Invalid JSON');
}
} else {
// Use form-based edits
settingsToSave = {
...data?.settings,
env: {
...data?.settings?.env,
...localEdits,
},
};
}
const res = await fetch(`/api/settings/${profileName}`, {
method: 'PUT',
@@ -174,7 +221,11 @@ function SettingsDialogContent({
</div>
) : (
<div className="flex flex-col h-[60vh]">
<Tabs defaultValue="env" className="flex-1 flex flex-col overflow-hidden">
<Tabs
value={activeTab}
onValueChange={setActiveTab}
className="flex-1 flex flex-col overflow-hidden"
>
<TabsList className="w-full justify-start border-b rounded-none p-0 h-auto bg-transparent">
<TabsTrigger
value="env"
@@ -182,6 +233,13 @@ function SettingsDialogContent({
>
Environment
</TabsTrigger>
<TabsTrigger
value="raw"
className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent px-4 py-2"
>
<Code2 className="w-4 h-4 mr-1" />
Raw JSON
</TabsTrigger>
<TabsTrigger
value="general"
className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent px-4 py-2"
@@ -222,6 +280,24 @@ function SettingsDialogContent({
</ScrollArea>
</TabsContent>
<TabsContent value="raw" className="flex-1 overflow-hidden p-4 pt-4 m-0">
<Suspense
fallback={
<div className="flex items-center justify-center h-full">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
<span className="ml-2 text-muted-foreground">Loading editor...</span>
</div>
}
>
<CodeEditor
value={rawJsonContent}
onChange={handleRawJsonChange}
language="json"
minHeight="calc(60vh - 120px)"
/>
</Suspense>
</TabsContent>
<TabsContent value="general" className="p-4 m-0">
<Card>
<CardHeader>
@@ -252,7 +328,10 @@ function SettingsDialogContent({
<Button type="button" variant="outline" onClick={onClose}>
<X className="w-4 h-4 mr-2" /> Cancel
</Button>
<Button onClick={handleSave} disabled={saveMutation.isPending}>
<Button
onClick={handleSave}
disabled={saveMutation.isPending || (activeTab === 'raw' && !isRawJsonValid)}
>
{saveMutation.isPending ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" /> Saving...
+60
View File
@@ -0,0 +1,60 @@
import { Check, Copy } from 'lucide-react';
import { useState } from 'react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
interface CopyButtonProps {
value: string;
className?: string;
variant?: 'default' | 'outline' | 'ghost' | 'secondary';
size?: 'default' | 'sm' | 'lg' | 'icon';
label?: string;
}
export function CopyButton({
value,
className,
variant = 'ghost',
size = 'icon',
label = 'Copy to clipboard',
}: CopyButtonProps) {
const [hasCopied, setHasCopied] = useState(false);
const onCopy = () => {
navigator.clipboard.writeText(value);
setHasCopied(true);
setTimeout(() => setHasCopied(false), 2000);
};
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
size={size}
variant={variant}
className={cn(
'h-6 w-6 relative z-10 text-foreground/70 hover:text-foreground',
className
)}
onClick={(e) => {
e.stopPropagation();
onCopy();
}}
>
{hasCopied ? (
<Check className="h-3 w-3 text-green-500" />
) : (
<Copy className="h-3 w-3" />
)}
<span className="sr-only">{label}</span>
</Button>
</TooltipTrigger>
<TooltipContent>
<p>{hasCopied ? 'Copied!' : label}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
);
}
+150
View File
@@ -0,0 +1,150 @@
import * as React from 'react';
import * as SelectPrimitive from '@radix-ui/react-select';
import { Check, ChevronDown, ChevronUp } from 'lucide-react';
import { cn } from '@/lib/utils';
const Select = SelectPrimitive.Root;
const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
'flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1',
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
));
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
className={cn('flex cursor-default items-center justify-center py-1', className)}
{...props}
>
<ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
));
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
className={cn('flex cursor-default items-center justify-center py-1', className)}
{...props}
>
<ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton>
));
SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName;
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = 'popper', ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
'relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
position === 'popper' &&
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
className
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
'p-1',
position === 'popper' &&
'h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]'
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
));
SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
className={cn('px-2 py-1.5 text-sm font-semibold', className)}
{...props}
/>
));
SelectLabel.displayName = SelectPrimitive.Label.displayName;
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
'relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className
)}
{...props}
>
<span className="absolute right-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
));
SelectItem.displayName = SelectPrimitive.Item.displayName;
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
className={cn('-mx-1 my-1 h-px bg-muted', className)}
{...props}
/>
));
SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
};
+6
View File
@@ -31,12 +31,18 @@ export interface CreateProfile {
baseUrl: string;
apiKey: string;
model?: string;
opusModel?: string;
sonnetModel?: string;
haikuModel?: string;
}
export interface UpdateProfile {
baseUrl?: string;
apiKey?: string;
model?: string;
opusModel?: string;
sonnetModel?: string;
haikuModel?: string;
}
export interface Variant {
+35
View File
@@ -0,0 +1,35 @@
/**
* Sensitive Key Detection Utilities (UI)
*
* Re-exports from main package for use in UI components.
* Patterns detect API keys, tokens, passwords, etc.
*/
/**
* Patterns that match sensitive keys (API keys, tokens, passwords).
* More specific than substring matching to avoid false positives.
*/
export const SENSITIVE_KEY_PATTERNS = [
/^ANTHROPIC_AUTH_TOKEN$/, // Exact match for Anthropic auth token
/_API_KEY$/, // Keys ending with _API_KEY
/_AUTH_TOKEN$/, // Keys ending with _AUTH_TOKEN
/_SECRET$/, // Keys ending with _SECRET
/_SECRET_KEY$/, // Keys ending with _SECRET_KEY
/^API_KEY$/, // Exact match for API_KEY
/^AUTH_TOKEN$/, // Exact match for AUTH_TOKEN
/^SECRET$/, // Exact match for SECRET
/_PASSWORD$/, // Keys ending with _PASSWORD
/^PASSWORD$/, // Exact match for PASSWORD
/_CREDENTIAL$/, // Keys ending with _CREDENTIAL
/_PRIVATE_KEY$/, // Keys ending with _PRIVATE_KEY
];
/**
* Check if a key name contains a secret/sensitive value.
*
* @param key - Environment variable key name
* @returns true if the key likely contains sensitive data
*/
export function isSensitiveKey(key: string): boolean {
return SENSITIVE_KEY_PATTERNS.some((pattern) => pattern.test(key));
}
+210 -212
View File
@@ -96,230 +96,228 @@ export function AnalyticsPage() {
}, []);
return (
<div className="flex flex-col h-[calc(100vh-3rem)] overflow-hidden">
<div className="flex-1 flex flex-col min-h-0 overflow-hidden p-4 pb-14 space-y-4">
{/* Header */}
<div className="flex items-center justify-between shrink-0">
<div>
<h1 className="text-xl font-semibold">Analytics</h1>
<p className="text-sm text-muted-foreground">Track usage & insights</p>
</div>
<div className="flex items-center gap-2">
<DateRangeFilter
value={dateRange}
onChange={setDateRange}
presets={[
{ label: '7D', range: { from: subDays(new Date(), 7), to: new Date() } },
{ label: '30D', range: { from: subDays(new Date(), 30), to: new Date() } },
{ label: 'Month', range: { from: startOfMonth(new Date()), to: new Date() } },
{ label: 'All Time', range: { from: undefined, to: new Date() } },
]}
/>
{lastUpdatedText && (
<span className="text-xs text-muted-foreground whitespace-nowrap">
Updated {lastUpdatedText}
</span>
)}
<Button
variant="outline"
size="sm"
className="gap-2 h-8"
onClick={handleRefresh}
disabled={isRefreshing}
>
<RefreshCw className={`w-3.5 h-3.5 ${isRefreshing ? 'animate-spin' : ''}`} />
</Button>
</div>
<div className="flex flex-col h-[calc(100vh-5.5rem)] overflow-hidden p-4 gap-3">
{/* Header */}
<div className="flex items-center justify-between shrink-0">
<div>
<h1 className="text-xl font-semibold">Analytics</h1>
<p className="text-sm text-muted-foreground">Track usage & insights</p>
</div>
<div className="flex items-center gap-2">
<DateRangeFilter
value={dateRange}
onChange={setDateRange}
presets={[
{ label: '7D', range: { from: subDays(new Date(), 7), to: new Date() } },
{ label: '30D', range: { from: subDays(new Date(), 30), to: new Date() } },
{ label: 'Month', range: { from: startOfMonth(new Date()), to: new Date() } },
{ label: 'All Time', range: { from: undefined, to: new Date() } },
]}
/>
{lastUpdatedText && (
<span className="text-xs text-muted-foreground whitespace-nowrap">
Updated {lastUpdatedText}
</span>
)}
<Button
variant="outline"
size="sm"
className="gap-2 h-8"
onClick={handleRefresh}
disabled={isRefreshing}
>
<RefreshCw className={`w-3.5 h-3.5 ${isRefreshing ? 'animate-spin' : ''}`} />
</Button>
</div>
</div>
{/* Summary Cards */}
<UsageSummaryCards data={summary} isLoading={isSummaryLoading} />
{/* Summary Cards */}
<UsageSummaryCards data={summary} isLoading={isSummaryLoading} />
{/* Main Content */}
<div className="flex-1 flex flex-col min-h-0 gap-3">
{/* Usage Trend Chart - Full Width */}
<Card className="flex flex-col flex-1 min-h-0 shadow-sm">
{/* Main Content */}
<div className="flex-1 flex flex-col min-h-0 gap-3">
{/* Usage Trend Chart - Full Width */}
<Card className="flex flex-col flex-1 min-h-0 shadow-sm">
<CardHeader className="px-3 py-2">
<CardTitle className="text-base font-semibold flex items-center gap-2">
<TrendingUp className="w-4 h-4" />
Usage Trends
</CardTitle>
</CardHeader>
<CardContent className="px-3 pb-3 pt-0 flex-1 min-h-0 flex items-center justify-center">
<UsageTrendChart data={trends || []} isLoading={isTrendsLoading} className="h-full" />
</CardContent>
</Card>
{/* Bottom Row - Cost by Model (4) + Model Usage (2) + Session Stats (4) */}
<div className="grid grid-cols-1 lg:grid-cols-10 gap-3 flex-1 min-h-0">
{/* Cost by Model - 4/10 width with breakdown */}
<Card className="flex flex-col h-full min-h-0 shadow-sm lg:col-span-4">
<CardHeader className="px-3 py-2">
<CardTitle className="text-base font-semibold flex items-center gap-2">
<TrendingUp className="w-4 h-4" />
Usage Trends
<DollarSign className="w-4 h-4" />
Cost by Model
</CardTitle>
</CardHeader>
<CardContent className="px-3 pb-3 pt-0 flex-1 min-h-0 flex items-center justify-center">
<UsageTrendChart data={trends || []} isLoading={isTrendsLoading} className="h-full" />
<CardContent className="px-2 pb-2 pt-0 flex-1 min-h-0 overflow-y-auto">
{isModelsLoading ? (
<Skeleton className="h-full w-full" />
) : (
<div className="space-y-0.5">
{[...(models || [])]
.sort((a, b) => b.cost - a.cost)
.map((model) => (
<button
key={model.model}
className="group flex items-center text-xs w-full hover:bg-muted/50 rounded px-2 py-1.5 transition-colors cursor-pointer gap-3"
onClick={(e) => handleModelClick(model, e)}
title="Click for details"
>
{/* Model name */}
<div className="flex items-center gap-2 min-w-0 w-[180px] shrink-0">
<div
className="w-2 h-2 rounded-full shrink-0"
style={{ backgroundColor: getModelColor(model.model) }}
/>
<span className="font-medium truncate group-hover:underline underline-offset-2">
{model.model}
</span>
</div>
{/* Cost breakdown mini-bar */}
<div className="flex-1 flex items-center gap-1 min-w-0">
<div className="flex-1 h-2 bg-muted rounded-full overflow-hidden flex">
<div
className="h-full"
style={{
backgroundColor: '#335c67',
width: `${model.cost > 0 ? (model.costBreakdown.input.cost / model.cost) * 100 : 0}%`,
}}
title={`Input: $${model.costBreakdown.input.cost.toFixed(2)}`}
/>
<div
className="h-full"
style={{
backgroundColor: '#fff3b0',
width: `${model.cost > 0 ? (model.costBreakdown.output.cost / model.cost) * 100 : 0}%`,
}}
title={`Output: $${model.costBreakdown.output.cost.toFixed(2)}`}
/>
<div
className="h-full"
style={{
backgroundColor: '#e09f3e',
width: `${model.cost > 0 ? (model.costBreakdown.cacheCreation.cost / model.cost) * 100 : 0}%`,
}}
title={`Cache Write: $${model.costBreakdown.cacheCreation.cost.toFixed(2)}`}
/>
<div
className="h-full"
style={{
backgroundColor: '#9e2a2b',
width: `${model.cost > 0 ? (model.costBreakdown.cacheRead.cost / model.cost) * 100 : 0}%`,
}}
title={`Cache Read: $${model.costBreakdown.cacheRead.cost.toFixed(2)}`}
/>
</div>
</div>
{/* Token count */}
<span className="text-[10px] text-muted-foreground w-14 text-right shrink-0">
{formatTokens(model.tokens)}
</span>
{/* Total cost */}
<span className="font-mono font-medium w-16 text-right shrink-0">
${model.cost.toFixed(2)}
</span>
<ChevronRight className="w-3 h-3 opacity-0 group-hover:opacity-50 transition-opacity shrink-0" />
</button>
))}
{/* Legend */}
<div className="flex items-center gap-3 pt-2 px-2 text-[10px] text-muted-foreground border-t mt-2">
<span className="flex items-center gap-1">
<div
className="w-2 h-2 rounded-full"
style={{ backgroundColor: '#335c67' }}
/>
Input
</span>
<span className="flex items-center gap-1">
<div
className="w-2 h-2 rounded-full border border-muted-foreground/30"
style={{ backgroundColor: '#fff3b0' }}
/>
Output
</span>
<span className="flex items-center gap-1">
<div
className="w-2 h-2 rounded-full"
style={{ backgroundColor: '#e09f3e' }}
/>
Cache Write
</span>
<span className="flex items-center gap-1">
<div
className="w-2 h-2 rounded-full"
style={{ backgroundColor: '#9e2a2b' }}
/>
Cache Read
</span>
</div>
</div>
)}
</CardContent>
</Card>
{/* Bottom Row - Cost by Model (4) + Model Usage (2) + Session Stats (4) */}
<div className="grid grid-cols-1 lg:grid-cols-10 gap-3 flex-1 min-h-0">
{/* Cost by Model - 4/10 width with breakdown */}
<Card className="flex flex-col h-full min-h-0 shadow-sm lg:col-span-4">
<CardHeader className="px-3 py-2">
<CardTitle className="text-base font-semibold flex items-center gap-2">
<DollarSign className="w-4 h-4" />
Cost by Model
</CardTitle>
</CardHeader>
<CardContent className="px-2 pb-2 pt-0 flex-1 min-h-0 overflow-y-auto">
{isModelsLoading ? (
<Skeleton className="h-full w-full" />
) : (
<div className="space-y-0.5">
{[...(models || [])]
.sort((a, b) => b.cost - a.cost)
.map((model) => (
<button
key={model.model}
className="group flex items-center text-xs w-full hover:bg-muted/50 rounded px-2 py-1.5 transition-colors cursor-pointer gap-3"
onClick={(e) => handleModelClick(model, e)}
title="Click for details"
>
{/* Model name */}
<div className="flex items-center gap-2 min-w-0 w-[180px] shrink-0">
<div
className="w-2 h-2 rounded-full shrink-0"
style={{ backgroundColor: getModelColor(model.model) }}
/>
<span className="font-medium truncate group-hover:underline underline-offset-2">
{model.model}
</span>
</div>
{/* Cost breakdown mini-bar */}
<div className="flex-1 flex items-center gap-1 min-w-0">
<div className="flex-1 h-2 bg-muted rounded-full overflow-hidden flex">
<div
className="h-full"
style={{
backgroundColor: '#335c67',
width: `${model.cost > 0 ? (model.costBreakdown.input.cost / model.cost) * 100 : 0}%`,
}}
title={`Input: $${model.costBreakdown.input.cost.toFixed(2)}`}
/>
<div
className="h-full"
style={{
backgroundColor: '#fff3b0',
width: `${model.cost > 0 ? (model.costBreakdown.output.cost / model.cost) * 100 : 0}%`,
}}
title={`Output: $${model.costBreakdown.output.cost.toFixed(2)}`}
/>
<div
className="h-full"
style={{
backgroundColor: '#e09f3e',
width: `${model.cost > 0 ? (model.costBreakdown.cacheCreation.cost / model.cost) * 100 : 0}%`,
}}
title={`Cache Write: $${model.costBreakdown.cacheCreation.cost.toFixed(2)}`}
/>
<div
className="h-full"
style={{
backgroundColor: '#9e2a2b',
width: `${model.cost > 0 ? (model.costBreakdown.cacheRead.cost / model.cost) * 100 : 0}%`,
}}
title={`Cache Read: $${model.costBreakdown.cacheRead.cost.toFixed(2)}`}
/>
</div>
</div>
{/* Token count */}
<span className="text-[10px] text-muted-foreground w-14 text-right shrink-0">
{formatTokens(model.tokens)}
</span>
{/* Total cost */}
<span className="font-mono font-medium w-16 text-right shrink-0">
${model.cost.toFixed(2)}
</span>
<ChevronRight className="w-3 h-3 opacity-0 group-hover:opacity-50 transition-opacity shrink-0" />
</button>
))}
{/* Legend */}
<div className="flex items-center gap-3 pt-2 px-2 text-[10px] text-muted-foreground border-t mt-2">
<span className="flex items-center gap-1">
<div
className="w-2 h-2 rounded-full"
style={{ backgroundColor: '#335c67' }}
/>
Input
</span>
<span className="flex items-center gap-1">
<div
className="w-2 h-2 rounded-full border border-muted-foreground/30"
style={{ backgroundColor: '#fff3b0' }}
/>
Output
</span>
<span className="flex items-center gap-1">
<div
className="w-2 h-2 rounded-full"
style={{ backgroundColor: '#e09f3e' }}
/>
Cache Write
</span>
<span className="flex items-center gap-1">
<div
className="w-2 h-2 rounded-full"
style={{ backgroundColor: '#9e2a2b' }}
/>
Cache Read
</span>
</div>
</div>
)}
</CardContent>
</Card>
{/* Model Distribution - 2/10 width */}
<Card className="flex flex-col h-full min-h-0 shadow-sm lg:col-span-2">
<CardHeader className="px-3 py-2">
<CardTitle className="text-base font-semibold flex items-center gap-2">
<PieChart className="w-4 h-4" />
Model Usage
</CardTitle>
</CardHeader>
<CardContent className="px-2 pb-2 pt-0 flex-1 min-h-0 flex items-center justify-center">
<ModelBreakdownChart
data={models || []}
isLoading={isModelsLoading}
className="h-full w-full"
/>
</CardContent>
</Card>
{/* Session Stats - 2/10 width */}
<SessionStatsCard
data={sessions}
isLoading={isSessionsLoading}
className="lg:col-span-2"
/>
{/* Usage Insights - 2/10 width */}
<UsageInsightsCard
anomalies={insights?.anomalies}
summary={insights?.summary}
isLoading={isInsightsLoading}
className="lg:col-span-2"
/>
</div>
{/* Model Details Popover - positioned at cursor */}
<Popover open={!!selectedModel} onOpenChange={(open) => !open && handlePopoverClose()}>
<PopoverAnchor asChild>
<div
ref={popoverAnchorRef}
className="fixed pointer-events-none"
style={{
left: popoverPosition?.x ?? 0,
top: popoverPosition?.y ?? 0,
width: 1,
height: 1,
}}
{/* Model Distribution - 2/10 width */}
<Card className="flex flex-col h-full min-h-0 shadow-sm lg:col-span-2">
<CardHeader className="px-3 py-2">
<CardTitle className="text-base font-semibold flex items-center gap-2">
<PieChart className="w-4 h-4" />
Model Usage
</CardTitle>
</CardHeader>
<CardContent className="px-2 pb-2 pt-0 flex-1 min-h-0 flex items-center justify-center">
<ModelBreakdownChart
data={models || []}
isLoading={isModelsLoading}
className="h-full w-full"
/>
</PopoverAnchor>
<PopoverContent className="w-80 p-3" side="top" align="center">
{selectedModel && <ModelDetailsContent model={selectedModel} />}
</PopoverContent>
</Popover>
</CardContent>
</Card>
{/* Session Stats - 2/10 width */}
<SessionStatsCard
data={sessions}
isLoading={isSessionsLoading}
className="lg:col-span-2"
/>
{/* Usage Insights - 2/10 width */}
<UsageInsightsCard
anomalies={insights?.anomalies}
summary={insights?.summary}
isLoading={isInsightsLoading}
className="lg:col-span-2"
/>
</div>
{/* Model Details Popover - positioned at cursor */}
<Popover open={!!selectedModel} onOpenChange={(open) => !open && handlePopoverClose()}>
<PopoverAnchor asChild>
<div
ref={popoverAnchorRef}
className="fixed pointer-events-none"
style={{
left: popoverPosition?.x ?? 0,
top: popoverPosition?.y ?? 0,
width: 1,
height: 1,
}}
/>
</PopoverAnchor>
<PopoverContent className="w-80 p-3" side="top" align="center">
{selectedModel && <ModelDetailsContent model={selectedModel} />}
</PopoverContent>
</Popover>
</div>
</div>
);
+310 -43
View File
@@ -1,66 +1,333 @@
/**
* API Profiles Page
* Phase 03: REST API Routes & CRUD
* API Profiles Page - Master-Detail Layout
* Comprehensive profile management with inline editing
*/
import { useState } from 'react';
import { useState, useMemo } from 'react';
import { Button } from '@/components/ui/button';
import { Plus } from 'lucide-react';
import { ProfilesTable } from '@/components/profiles-table';
import { ProfileDialog } from '@/components/profile-dialog';
import { SettingsDialog } from '@/components/settings-dialog';
import { useProfiles } from '@/hooks/use-profiles';
import { Input } from '@/components/ui/input';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import {
Plus,
Search,
Settings2,
Trash2,
CheckCircle2,
AlertCircle,
Server,
ExternalLink,
FileJson,
} from 'lucide-react';
import { ProfileEditor } from '@/components/profile-editor';
import { ProfileCreateDialog } from '@/components/profile-create-dialog';
import { useProfiles, useDeleteProfile } from '@/hooks/use-profiles';
import { ConfirmDialog } from '@/components/confirm-dialog';
import type { Profile } from '@/lib/api-client';
import { cn } from '@/lib/utils';
import { CopyButton } from '@/components/ui/copy-button';
export function ApiPage() {
const [dialogOpen, setDialogOpen] = useState(false);
const [editingProfile, setEditingProfile] = useState<Profile | null>(null);
const [settingsDialogOpen, setSettingsDialogOpen] = useState(false);
const [settingsProfileName, setSettingsProfileName] = useState<string | null>(null);
const { data, isLoading } = useProfiles();
const deleteMutation = useDeleteProfile();
const [selectedProfile, setSelectedProfile] = useState<string | null>(null);
const [searchQuery, setSearchQuery] = useState('');
const [isCreateDialogOpen, setCreateDialogOpen] = useState(false);
const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);
const handleEditSettings = (profile: Profile) => {
setSettingsProfileName(profile.name);
setSettingsDialogOpen(true);
// Memoize profiles to maintain stable reference
const profiles = useMemo(() => data?.profiles || [], [data?.profiles]);
// Filter profiles by search
const filteredProfiles = useMemo(
() => profiles.filter((p) => p.name.toLowerCase().includes(searchQuery.toLowerCase())),
[profiles, searchQuery]
);
// Compute effective selected profile (auto-select first if none selected)
const effectiveSelectedProfile = useMemo(() => {
if (selectedProfile && profiles.some((p) => p.name === selectedProfile)) {
return selectedProfile;
}
return profiles.length > 0 ? profiles[0].name : null;
}, [selectedProfile, profiles]);
// Handle profile deletion
const handleDelete = (name: string) => {
deleteMutation.mutate(name, {
onSuccess: () => {
if (selectedProfile === name) {
setSelectedProfile(null);
}
setDeleteConfirm(null);
},
});
};
const handleCloseDialog = () => {
setDialogOpen(false);
setEditingProfile(null);
// Handle create success
const handleCreateSuccess = (name: string) => {
setCreateDialogOpen(false);
setSelectedProfile(name);
};
const handleCloseSettingsDialog = () => {
setSettingsDialogOpen(false);
setSettingsProfileName(null);
};
const selectedProfileData = profiles.find((p) => p.name === effectiveSelectedProfile);
return (
<div className="p-6 max-w-6xl mx-auto space-y-8">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold">API Profiles</h1>
<p className="text-sm text-muted-foreground mt-1">
Manage custom API profiles for Claude CLI
</p>
<div className="h-[calc(100vh-100px)] flex">
{/* Left Panel - Profiles List */}
<div className="w-80 border-r flex flex-col bg-muted/30">
{/* Header */}
<div className="p-4 border-b bg-background">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-2">
<Server className="w-5 h-5 text-primary" />
<h1 className="font-semibold">API Profiles</h1>
</div>
<Button
size="sm"
onClick={() => {
setCreateDialogOpen(true);
}}
>
<Plus className="w-4 h-4 mr-1" />
New
</Button>
</div>
{/* Search */}
<div className="relative">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search profiles..."
className="pl-8 h-9"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
</div>
</div>
<Button onClick={() => setDialogOpen(true)}>
<Plus className="w-4 h-4 mr-2" />
Create Profile
</Button>
{/* Profile List */}
<ScrollArea className="flex-1">
{isLoading ? (
<div className="p-4 text-sm text-muted-foreground">Loading profiles...</div>
) : filteredProfiles.length === 0 ? (
<div className="p-4 text-center">
{profiles.length === 0 ? (
<div className="space-y-3 py-8">
<FileJson className="w-12 h-12 mx-auto text-muted-foreground/50" />
<div>
<p className="text-sm font-medium">No API profiles yet</p>
<p className="text-xs text-muted-foreground mt-1">
Create your first profile to connect to custom API endpoints
</p>
</div>
<Button
size="sm"
variant="outline"
onClick={() => {
setCreateDialogOpen(true);
}}
>
<Plus className="w-4 h-4 mr-1" />
Create Profile
</Button>
</div>
) : (
<p className="text-sm text-muted-foreground py-4">
No profiles match "{searchQuery}"
</p>
)}
</div>
) : (
<div className="p-2 space-y-1">
{filteredProfiles.map((profile) => (
<ProfileListItem
key={profile.name}
profile={profile}
isSelected={effectiveSelectedProfile === profile.name}
onSelect={() => {
setSelectedProfile(profile.name);
}}
onDelete={() => setDeleteConfirm(profile.name)}
/>
))}
</div>
)}
</ScrollArea>
{/* Footer Stats */}
{profiles.length > 0 && (
<div className="p-3 border-t bg-background text-xs text-muted-foreground">
<div className="flex items-center justify-between">
<span>
{profiles.length} profile{profiles.length !== 1 ? 's' : ''}
</span>
<span className="flex items-center gap-1">
<CheckCircle2 className="w-3 h-3 text-green-600" />
{profiles.filter((p) => p.configured).length} configured
</span>
</div>
</div>
)}
</div>
{isLoading ? (
<div className="text-muted-foreground">Loading profiles...</div>
) : (
<ProfilesTable data={data?.profiles || []} onEditSettings={handleEditSettings} />
)}
{/* Right Panel - Editor */}
<div className="flex-1 flex flex-col min-w-0">
{selectedProfileData ? (
<ProfileEditor
profileName={selectedProfileData.name}
onDelete={() => setDeleteConfirm(selectedProfileData.name)}
/>
) : (
<EmptyState
onCreateClick={() => {
setCreateDialogOpen(true);
}}
/>
)}
</div>
<ProfileDialog open={dialogOpen} onClose={handleCloseDialog} profile={editingProfile} />
<SettingsDialog
open={settingsDialogOpen}
onClose={handleCloseSettingsDialog}
profileName={settingsProfileName}
{/* Create Dialog */}
<ProfileCreateDialog
open={isCreateDialogOpen}
onOpenChange={setCreateDialogOpen}
onSuccess={handleCreateSuccess}
/>
{/* Delete Confirmation */}
<ConfirmDialog
open={!!deleteConfirm}
title="Delete Profile"
description={`Are you sure you want to delete "${deleteConfirm}"? This will remove the settings file and cannot be undone.`}
confirmText="Delete"
variant="destructive"
onConfirm={() => deleteConfirm && handleDelete(deleteConfirm)}
onCancel={() => setDeleteConfirm(null)}
/>
</div>
);
}
/** Profile list item component */
function ProfileListItem({
profile,
isSelected,
onSelect,
onDelete,
}: {
profile: Profile;
isSelected: boolean;
onSelect: () => void;
onDelete: () => void;
}) {
return (
<div
className={cn(
'group flex items-center gap-2 px-3 py-2.5 rounded-md cursor-pointer transition-colors',
isSelected
? 'bg-primary/10 border border-primary/20'
: 'hover:bg-muted border border-transparent'
)}
onClick={onSelect}
>
{/* Status indicator */}
{profile.configured ? (
<CheckCircle2 className="w-4 h-4 text-green-600 shrink-0" />
) : (
<AlertCircle className="w-4 h-4 text-yellow-600 shrink-0" />
)}
{/* Profile info */}
<div className="flex-1 min-w-0">
<div className="font-medium text-sm truncate">{profile.name}</div>
<div className="flex items-center gap-1.5 min-w-0">
<div className="text-xs text-muted-foreground truncate flex-1">
{profile.settingsPath}
</div>
<CopyButton
value={profile.settingsPath}
size="icon"
className="h-5 w-5 opacity-0 group-hover:opacity-100 transition-opacity"
/>
</div>
</div>
{/* Actions */}
<Button
variant="ghost"
size="icon"
className="h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity"
onClick={(e) => {
e.stopPropagation();
onDelete();
}}
>
<Trash2 className="w-3.5 h-3.5 text-destructive" />
</Button>
</div>
);
}
/** Empty state when no profile is selected */
function EmptyState({ onCreateClick }: { onCreateClick: () => void }) {
return (
<div className="flex-1 flex items-center justify-center bg-muted/20">
<div className="text-center max-w-md px-8">
<Settings2 className="w-16 h-16 mx-auto text-muted-foreground/30 mb-6" />
<h2 className="text-xl font-semibold mb-2">API Profile Manager</h2>
<p className="text-muted-foreground mb-6">
Configure custom API endpoints for Claude CLI. Connect to proxy services like copilot-api,
OpenRouter, or your own API backend.
</p>
<div className="space-y-3">
<Button onClick={onCreateClick} className="w-full">
<Plus className="w-4 h-4 mr-2" />
Create Your First Profile
</Button>
<Separator className="my-4" />
<div className="text-left space-y-2">
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
What you can configure:
</p>
<ul className="text-sm text-muted-foreground space-y-1.5">
<li className="flex items-start gap-2">
<Badge variant="outline" className="text-xs shrink-0 mt-0.5">
URL
</Badge>
<span>Custom API base URL endpoint</span>
</li>
<li className="flex items-start gap-2">
<Badge variant="outline" className="text-xs shrink-0 mt-0.5">
Auth
</Badge>
<span>API key or authentication token</span>
</li>
<li className="flex items-start gap-2">
<Badge variant="outline" className="text-xs shrink-0 mt-0.5">
Models
</Badge>
<span>Model mapping for Opus/Sonnet/Haiku</span>
</li>
</ul>
</div>
<div className="pt-4">
<a
href="https://github.com/kaitranntt/ccs#api-profiles"
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center text-xs text-primary hover:underline"
>
Learn more about API profiles
<ExternalLink className="w-3 h-3 ml-1" />
</a>
</div>
</div>
</div>
</div>
);
}