Merge pull request #698 from kaitranntt/kai/feat/issue-697-profile-lifecycle-ux

feat: API profile lifecycle discover/copy/export/import parity
This commit is contained in:
Kai (Tam Nhu) Tran authored and GitHub committed 2026-03-07 01:25:53 -05:00
commit 248b6d11b8
13 files changed
+1881 -32

No files matched your search

@@ -0,0 +1,163 @@
import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import {
copyApiProfile,
discoverApiProfileOrphans,
exportApiProfile,
importApiProfileBundle,
registerApiProfileOrphans,
} from '../../../src/api/services/profile-lifecycle-service';
describe('profile lifecycle service', () => {
let tempHome = '';
let originalCcsHome: string | undefined;
beforeEach(() => {
tempHome = fs.mkdtempSync(path.join(os.tmpdir(), 'ccs-profile-lifecycle-'));
originalCcsHome = process.env.CCS_HOME;
process.env.CCS_HOME = tempHome;
});
afterEach(() => {
if (originalCcsHome === undefined) {
delete process.env.CCS_HOME;
} else {
process.env.CCS_HOME = originalCcsHome;
}
if (tempHome && fs.existsSync(tempHome)) {
fs.rmSync(tempHome, { recursive: true, force: true });
}
});
it('discovers only API profile orphans (skips registered and reserved names)', () => {
const ccsDir = path.join(tempHome, '.ccs');
fs.mkdirSync(ccsDir, { recursive: true });
fs.writeFileSync(
path.join(ccsDir, 'config.json'),
JSON.stringify({ profiles: { glm: '~/.ccs/glm.settings.json' } }, null, 2) + '\n'
);
fs.writeFileSync(
path.join(ccsDir, 'glm.settings.json'),
JSON.stringify({ env: { ANTHROPIC_BASE_URL: 'https://api.example.com', ANTHROPIC_AUTH_TOKEN: 'token' } }, null, 2) +
'\n'
);
fs.writeFileSync(
path.join(ccsDir, 'extra.settings.json'),
JSON.stringify({ env: { ANTHROPIC_BASE_URL: 'https://api.example.com', ANTHROPIC_AUTH_TOKEN: 'token' } }, null, 2) +
'\n'
);
fs.writeFileSync(
path.join(ccsDir, 'gemini.settings.json'),
JSON.stringify({ env: { ANTHROPIC_BASE_URL: 'https://api.example.com', ANTHROPIC_AUTH_TOKEN: 'token' } }, null, 2) +
'\n'
);
const result = discoverApiProfileOrphans();
expect(result.orphans.map((orphan) => orphan.name)).toEqual(['extra']);
});
it('treats explicit empty names list as no-op during orphan registration', () => {
const ccsDir = path.join(tempHome, '.ccs');
fs.mkdirSync(ccsDir, { recursive: true });
fs.writeFileSync(
path.join(ccsDir, 'lonely.settings.json'),
JSON.stringify({ env: { ANTHROPIC_BASE_URL: 'https://api.example.com', ANTHROPIC_AUTH_TOKEN: 'token' } }, null, 2) +
'\n'
);
fs.writeFileSync(path.join(ccsDir, 'config.json'), JSON.stringify({ profiles: {} }, null, 2) + '\n');
const result = registerApiProfileOrphans({ names: [] });
expect(result.registered).toEqual([]);
expect(result.skipped).toEqual([]);
});
it('redacts all sensitive env values during export when includeSecrets=false', () => {
const ccsDir = path.join(tempHome, '.ccs');
fs.mkdirSync(ccsDir, { recursive: true });
fs.writeFileSync(
path.join(ccsDir, 'config.json'),
JSON.stringify({ profiles: { glm: '~/.ccs/glm.settings.json' } }, null, 2) + '\n'
);
fs.writeFileSync(
path.join(ccsDir, 'glm.settings.json'),
JSON.stringify(
{
env: {
ANTHROPIC_BASE_URL: 'https://api.example.com',
ANTHROPIC_AUTH_TOKEN: 'token-1',
OPENROUTER_API_KEY: 'token-2',
},
},
null,
2
) + '\n'
);
const result = exportApiProfile('glm', false);
expect(result.success).toBe(true);
expect(result.bundle?.settings).toBeDefined();
const env = (result.bundle?.settings.env as Record<string, unknown>) || {};
expect(env.ANTHROPIC_AUTH_TOKEN).toBe('__CCS_REDACTED__');
expect(env.OPENROUTER_API_KEY).toBe('__CCS_REDACTED__');
});
it('rejects invalid source profile names in copy flow', () => {
const result = copyApiProfile('../escape', 'safe-name');
expect(result.success).toBe(false);
expect(result.error).toContain('Invalid source profile name');
});
it('rejects import bundle with invalid profile target', () => {
const result = importApiProfileBundle({
schemaVersion: 1,
exportedAt: new Date().toISOString(),
profile: { name: 'glm', target: 'invalid-target' },
settings: {
env: {
ANTHROPIC_BASE_URL: 'https://api.example.com',
ANTHROPIC_AUTH_TOKEN: 'token',
},
},
});
expect(result.success).toBe(false);
expect(result.error).toContain('Invalid bundle profile target');
});
it('clears and warns for all redacted sensitive env keys on import', () => {
const ccsDir = path.join(tempHome, '.ccs');
fs.mkdirSync(ccsDir, { recursive: true });
fs.writeFileSync(path.join(ccsDir, 'config.json'), JSON.stringify({ profiles: {} }, null, 2) + '\n');
const result = importApiProfileBundle({
schemaVersion: 1,
exportedAt: new Date().toISOString(),
profile: { name: 'redacted-import', target: 'claude' },
settings: {
env: {
ANTHROPIC_BASE_URL: 'https://api.example.com',
ANTHROPIC_AUTH_TOKEN: '__CCS_REDACTED__',
OPENROUTER_API_KEY: '__CCS_REDACTED__',
},
},
});
expect(result.success).toBe(true);
expect(result.warnings?.length).toBeGreaterThan(0);
const settingsPath = path.join(ccsDir, 'redacted-import.settings.json');
const parsed = JSON.parse(fs.readFileSync(settingsPath, 'utf8')) as {
env: Record<string, string>;
};
expect(parsed.env.ANTHROPIC_AUTH_TOKEN).toBe('');
expect(parsed.env.OPENROUTER_API_KEY).toBe('');
});
});
@@ -0,0 +1,145 @@
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'bun:test';
import express from 'express';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import type { Server } from 'http';
import profileRoutes from '../../../src/web-server/routes/profile-routes';
describe('profile-routes lifecycle endpoints', () => {
let server: Server;
let baseUrl = '';
let tempHome = '';
let originalCcsHome: string | undefined;
beforeAll(async () => {
const app = express();
app.use(express.json());
app.use('/api/profiles', profileRoutes);
await new Promise<void>((resolve, reject) => {
server = app.listen(0, '127.0.0.1');
const onError = (error: Error) => reject(error);
server.once('error', onError);
server.once('listening', () => {
server.off('error', onError);
resolve();
});
});
const address = server.address();
if (!address || typeof address === 'string') {
throw new Error('Unable to resolve test server port');
}
baseUrl = `http://127.0.0.1:${address.port}`;
});
afterAll(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
});
beforeEach(() => {
tempHome = fs.mkdtempSync(path.join(os.tmpdir(), 'ccs-profile-routes-lifecycle-'));
originalCcsHome = process.env.CCS_HOME;
process.env.CCS_HOME = tempHome;
});
afterEach(() => {
if (originalCcsHome !== undefined) {
process.env.CCS_HOME = originalCcsHome;
} else {
delete process.env.CCS_HOME;
}
if (tempHome && fs.existsSync(tempHome)) {
fs.rmSync(tempHome, { recursive: true, force: true });
}
});
it('rejects unknown fields on profile create payload', async () => {
const response = await fetch(`${baseUrl}/api/profiles`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: 'demo',
baseUrl: 'https://api.example.com',
apiKey: 'token',
unknownField: true,
}),
});
expect(response.status).toBe(400);
const body = (await response.json()) as { error: string };
expect(body.error).toContain('Unknown profile field(s)');
});
it('does not register all orphans when names=[] is explicitly passed', async () => {
const ccsDir = path.join(tempHome, '.ccs');
fs.mkdirSync(ccsDir, { recursive: true });
fs.writeFileSync(path.join(ccsDir, 'config.json'), JSON.stringify({ profiles: {} }, null, 2) + '\n');
fs.writeFileSync(
path.join(ccsDir, 'lonely.settings.json'),
JSON.stringify({ env: { ANTHROPIC_BASE_URL: 'https://api.example.com', ANTHROPIC_AUTH_TOKEN: 'token' } }, null, 2) +
'\n'
);
const response = await fetch(`${baseUrl}/api/profiles/orphans/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ names: [] }),
});
expect(response.status).toBe(200);
const body = (await response.json()) as { registered: string[]; skipped: Array<unknown> };
expect(body.registered).toEqual([]);
expect(body.skipped).toEqual([]);
});
it('rejects malformed names payload for orphan registration', async () => {
const response = await fetch(`${baseUrl}/api/profiles/orphans/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ names: 'lonely' }),
});
expect(response.status).toBe(400);
const body = (await response.json()) as { error: string };
expect(body.error).toContain('names must be an array');
});
it('rejects import bundle with invalid profile target', async () => {
const response = await fetch(`${baseUrl}/api/profiles/import`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
bundle: {
schemaVersion: 1,
exportedAt: new Date().toISOString(),
profile: { name: 'demo', target: 'invalid' },
settings: {
env: {
ANTHROPIC_BASE_URL: 'https://api.example.com',
ANTHROPIC_AUTH_TOKEN: 'token',
},
},
},
}),
});
expect(response.status).toBe(400);
const body = (await response.json()) as { error: string };
expect(body.error).toContain('Invalid bundle profile target');
});
it('validates source profile name on export endpoint', async () => {
const response = await fetch(`${baseUrl}/api/profiles/1invalid/export`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
});
expect(response.status).toBe(400);
const body = (await response.json()) as { error: string };
expect(body.error).toContain('API name must start with letter');
});
});