Spaces:
Running
Running
feat(webui): add configuration presets for Claude CLI
Browse files- Add backend storage logic in `src/utils/claude-config.js` to save/load/delete presets
- Add API endpoints (`GET`, `POST`, `DELETE`) for presets in `src/webui/index.js`
- Update `public/views/settings.html` with new Presets UI card and modals
- Update `public/js/components/claude-config.js` with auto-load logic and unsaved changes protection
- Add translations (EN/ZH) for new UI elements in `public/js/store.js`
- Add integration tests in `tests/frontend/test-frontend-settings.cjs`
- Update compiled CSS
Co-Authored-By: Claude <noreply@anthropic.com>
Files changed (7)
11 unmodified lines1213141516177 unmodified lines252627282930313233343536134 unmodified lines17117217317417511 unmodified linesrestoring: false,gemini1mSuffix: false,// Model fields that may contain Gemini model namesgeminiModelFields: ['ANTHROPIC_MODEL',7 unmodified lines// Only fetch config if this is the active sub-tabif (this.activeTab === 'claude') {this.fetchConfig();}// Watch local activeTab (from parent settings scope, skip initial trigger)this.$watch('activeTab', (tab, oldTab) => {if (tab === 'claude' && oldTab !== undefined) {this.fetchConfig();}});134 unmodified lines} finally {this.restoring = false;}}});11 unmodified lines121314151617181920212223247 unmodified lines3233343536373839404142434445134 unmodified lines18018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541611 unmodified linesrestoring: false,gemini1mSuffix: false,// Presets statepresets: [],selectedPresetName: '',savingPreset: false,deletingPreset: false,pendingPresetName: '', // For unsaved changes confirmation// Model fields that may contain Gemini model namesgeminiModelFields: ['ANTHROPIC_MODEL',7 unmodified lines// Only fetch config if this is the active sub-tabif (this.activeTab === 'claude') {this.fetchConfig();this.fetchPresets();}// Watch local activeTab (from parent settings scope, skip initial trigger)this.$watch('activeTab', (tab, oldTab) => {if (tab === 'claude' && oldTab !== undefined) {this.fetchConfig();this.fetchPresets();}});134 unmodified lines} finally {this.restoring = false;}},// ==========================================// Presets Management// ==========================================/*** Fetch all saved presets from the server*/async fetchPresets() {const password = Alpine.store('global').webuiPassword;try {const { response, newPassword } = await window.utils.request('/api/claude/presets', {}, password);if (newPassword) Alpine.store('global').webuiPassword = newPassword;if (!response.ok) throw new Error(`HTTP ${response.status}`);const data = await response.json();if (data.status === 'ok') {this.presets = data.presets || [];// Auto-select first preset if none selectedif (this.presets.length > 0 && !this.selectedPresetName) {this.selectedPresetName = this.presets[0].name;}}} catch (e) {console.error('Failed to fetch presets:', e);}},/*** Load the selected preset into the form (does not save to Claude CLI)*/loadSelectedPreset() {const preset = this.presets.find(p => p.name === this.selectedPresetName);if (!preset) {return;}// Merge preset config into current config.envthis.config.env = { ...this.config.env, ...preset.config };// Update Gemini 1M toggle based on merged config (not just preset)this.gemini1mSuffix = this.detectGemini1mSuffix();Alpine.store('global').showToast(Alpine.store('global').t('presetLoaded') || `Preset "${preset.name}" loaded. Click "Apply to Claude CLI" to save.`,'success');},/*** Check if current config matches any saved preset* @returns {boolean} True if current config matches a preset*/currentConfigMatchesPreset() {const relevantKeys = ['ANTHROPIC_BASE_URL','ANTHROPIC_AUTH_TOKEN','ANTHROPIC_MODEL','CLAUDE_CODE_SUBAGENT_MODEL','ANTHROPIC_DEFAULT_OPUS_MODEL','ANTHROPIC_DEFAULT_SONNET_MODEL','ANTHROPIC_DEFAULT_HAIKU_MODEL','ENABLE_EXPERIMENTAL_MCP_CLI'];for (const preset of this.presets) {let matches = true;for (const key of relevantKeys) {const currentVal = this.config.env[key] || '';const presetVal = preset.config[key] || '';if (currentVal !== presetVal) {matches = false;break;}}if (matches) return true;}return false;},/*** Handle preset selection change - auto-load with unsaved changes warning* @param {string} newPresetName - The newly selected preset name*/async onPresetSelect(newPresetName) {if (!newPresetName || newPresetName === this.selectedPresetName) return;// Check if current config has unsaved changes (doesn't match any preset)const hasUnsavedChanges = !this.currentConfigMatchesPreset();if (hasUnsavedChanges) {// Store pending preset and show confirmation modalthis.pendingPresetName = newPresetName;document.getElementById('unsaved_changes_modal').showModal();return;}this.selectedPresetName = newPresetName;this.loadSelectedPreset();},/*** Confirm loading preset despite unsaved changes*/confirmLoadPreset() {document.getElementById('unsaved_changes_modal').close();this.selectedPresetName = this.pendingPresetName;this.pendingPresetName = '';this.loadSelectedPreset();},/*** Cancel loading preset - revert dropdown selection*/cancelLoadPreset() {document.getElementById('unsaved_changes_modal').close();// Revert the dropdown to current selectionconst select = document.querySelector('[aria-label="Select preset"]');if (select) select.value = this.selectedPresetName;this.pendingPresetName = '';},/*** Save the current config as a new preset*/async saveCurrentAsPreset() {// Show the save preset modaldocument.getElementById('save_preset_modal').showModal();},/*** Execute preset save after user enters name*/async executeSavePreset(name) {if (!name || !name.trim()) {Alpine.store('global').showToast('Preset name is required', 'error');return;}this.savingPreset = true;const password = Alpine.store('global').webuiPassword;try {// Save only relevant env varsconst relevantKeys = ['ANTHROPIC_BASE_URL','ANTHROPIC_AUTH_TOKEN','ANTHROPIC_MODEL','CLAUDE_CODE_SUBAGENT_MODEL','ANTHROPIC_DEFAULT_OPUS_MODEL','ANTHROPIC_DEFAULT_SONNET_MODEL','ANTHROPIC_DEFAULT_HAIKU_MODEL','ENABLE_EXPERIMENTAL_MCP_CLI'];const presetConfig = {};relevantKeys.forEach(k => {if (this.config.env[k]) {presetConfig[k] = this.config.env[k];}});const { response, newPassword } = await window.utils.request('/api/claude/presets', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ name: name.trim(), config: presetConfig })}, password);if (newPassword) Alpine.store('global').webuiPassword = newPassword;if (!response.ok) throw new Error(`HTTP ${response.status}`);const data = await response.json();if (data.status === 'ok') {this.presets = data.presets || [];this.selectedPresetName = name.trim();Alpine.store('global').showToast(Alpine.store('global').t('presetSaved') || `Preset "${name}" saved`,'success');document.getElementById('save_preset_modal').close();} else {throw new Error(data.error || 'Save failed');}} catch (e) {Alpine.store('global').showToast('Failed to save preset: ' + e.message, 'error');} finally {this.savingPreset = false;}},/*** Delete the selected preset*/async deleteSelectedPreset() {if (!this.selectedPresetName) {Alpine.store('global').showToast('No preset selected', 'warning');return;}// Confirm deletionif (!confirm(`Delete preset "${this.selectedPresetName}"?`)) {return;}this.deletingPreset = true;const password = Alpine.store('global').webuiPassword;try {const { response, newPassword } = await window.utils.request(`/api/claude/presets/${encodeURIComponent(this.selectedPresetName)}`,{ method: 'DELETE' },password);if (newPassword) Alpine.store('global').webuiPassword = newPassword;if (!response.ok) throw new Error(`HTTP ${response.status}`);const data = await response.json();if (data.status === 'ok') {this.presets = data.presets || [];// Select first available preset or clear selectionthis.selectedPresetName = this.presets.length > 0 ? this.presets[0].name : '';Alpine.store('global').showToast(Alpine.store('global').t('presetDeleted') || 'Preset deleted','success');} else {throw new Error(data.error || 'Delete failed');}} catch (e) {Alpine.store('global').showToast('Failed to delete preset: ' + e.message, 'error');} finally {this.deletingPreset = false;}}});
130 unmodified lines131132133134135136252 unmodified lines389390391392393394130 unmodified linesclaudeSettingsAlertPrefix: "Settings below directly modify",claudeSettingsAlertSuffix: "Restart Claude CLI to apply.",applyToClaude: "Apply to Claude CLI",// Settings - Serverport: "Port",uiVersion: "UI Version",252 unmodified linesclaudeSettingsAlertPrefix: "以下设置直接修改",claudeSettingsAlertSuffix: "重启 Claude CLI 生效。",applyToClaude: "应用到 Claude CLI",// Settings - Serverport: "端口",uiVersion: "UI 版本",130 unmodified lines131132133134135136137138139140141142143144145146147148149150151152153154252 unmodified lines407408409410411412413414415416417418419420421422423424425426427428429430130 unmodified linesclaudeSettingsAlertPrefix: "Settings below directly modify",claudeSettingsAlertSuffix: "Restart Claude CLI to apply.",applyToClaude: "Apply to Claude CLI",// PresetsconfigPresets: "Configuration Presets",saveAsPreset: "Save as Preset",deletePreset: "Delete Preset",loadPreset: "Load preset into form",load: "Load",presetHint: "Select a preset to load it. Click \"Apply to Claude CLI\" to save changes.",presetLoaded: "Preset loaded. Click \"Apply to Claude CLI\" to save.",presetSaved: "Preset saved",presetDeleted: "Preset deleted",unsavedChangesTitle: "Unsaved Changes",unsavedChangesMessage: "Your current configuration doesn't match any saved preset. If you switch, your current unsaved settings will be lost.",loadAnyway: "Load Anyway",savePresetTitle: "Save Preset",savePresetDesc: "Save the current configuration as a reusable preset.",presetName: "Preset Name",presetNamePlaceholder: "e.g., My Work Setup",savePreset: "Save Preset",// Settings - Serverport: "Port",uiVersion: "UI Version",252 unmodified linesclaudeSettingsAlertPrefix: "以下设置直接修改",claudeSettingsAlertSuffix: "重启 Claude CLI 生效。",applyToClaude: "应用到 Claude CLI",// PresetsconfigPresets: "配置预设",saveAsPreset: "另存为预设",deletePreset: "删除预设",loadPreset: "加载预设到表单",load: "加载",presetHint: "选择预设以加载。点击“应用到 Claude CLI”以保存更改。",presetLoaded: "预设已加载。点击“应用到 Claude CLI”以保存。",presetSaved: "预设已保存",presetDeleted: "预设已删除",unsavedChangesTitle: "未保存的更改",unsavedChangesMessage: "当前配置与任何已保存的预设都不匹配。如果切换预设,当前未保存的设置将会丢失。",loadAnyway: "仍然加载",savePresetTitle: "保存预设",savePresetDesc: "将当前配置保存为可重复使用的预设。",presetName: "预设名称",presetNamePlaceholder: "例如:工作配置",savePreset: "保存预设",// Settings - Serverport: "端口",uiVersion: "UI 版本",
203 unmodified lines204205206207208209360 unmodified lines570571572573574575203 unmodified lines</span></div><!-- Base URL --><div class="card bg-space-900/30 border border-space-border/50 p-5"><label class="label text-xs uppercase text-gray-500 font-semibold mb-2"360 unmodified lines<button>close</button></form></dialog></div><!-- Tab 3: Models Configuration -->203 unmodified lines204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255360 unmodified lines616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687203 unmodified lines</span></div><!-- Configuration Presets --><div class="card bg-space-900/30 border border-neon-cyan/30 p-5"><div class="flex items-center justify-between mb-4"><div class="flex items-center gap-2"><svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-neon-cyan" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" /></svg><label class="text-xs uppercase text-neon-cyan font-semibold" x-text="$store.global.t('configPresets') || 'Configuration Presets'">Configuration Presets</label></div><button class="btn btn-xs btn-ghost text-neon-cyan hover:bg-neon-cyan/10 gap-1"@click="saveCurrentAsPreset()":disabled="savingPreset"><svg x-show="!savingPreset" xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" /></svg><span x-show="!savingPreset" x-text="$store.global.t('saveAsPreset') || 'Save as Preset'">Save as Preset</span><span x-show="savingPreset" class="loading loading-spinner loading-xs"></span></button></div><div class="flex gap-2"><selectclass="select select-sm bg-space-800 border-space-border text-white flex-1 font-mono text-xs":disabled="presets.length === 0":value="selectedPresetName"@change="onPresetSelect($event.target.value)"aria-label="Select preset"><option value="" disabled x-show="presets.length === 0">No presets available</option><template x-for="preset in presets" :key="preset.name"><option :value="preset.name" x-text="preset.name" :selected="preset.name === selectedPresetName"></option></template></select><button class="btn btn-sm btn-ghost text-red-400 hover:bg-red-500/10"@click="deleteSelectedPreset()":disabled="!selectedPresetName || presets.length === 0 || deletingPreset":title="$store.global.t('deletePreset') || 'Delete preset'"><span x-show="!deletingPreset"><svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg></span><span x-show="deletingPreset" class="loading loading-spinner loading-xs"></span></button></div><p class="text-[10px] text-gray-600 mt-2" x-text="$store.global.t('presetHint') || 'Select a preset to load it. Click \"Apply to Claude CLI\" to save changes.'">Select a preset to load it. Click "Apply to Claude CLI" to save changes.</p></div><!-- Base URL --><div class="card bg-space-900/30 border border-space-border/50 p-5"><label class="label text-xs uppercase text-gray-500 font-semibold mb-2"360 unmodified lines<button>close</button></form></dialog><!-- Unsaved Changes Confirmation Modal --><dialog id="unsaved_changes_modal" class="modal"><div class="modal-box bg-space-900 border-2 border-yellow-500/50"><h3 class="font-bold text-lg text-yellow-400 flex items-center gap-2"><svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" /></svg><span x-text="$store.global.t('unsavedChangesTitle') || 'Unsaved Changes'">Unsaved Changes</span></h3><p class="py-4 text-gray-300"><span x-text="$store.global.t('unsavedChangesMessage') || 'Your current configuration doesn\'t match any saved preset.'">Your current configuration doesn't match any saved preset.</span><br><br><span class="text-yellow-400/80" x-text="'Load \"' + pendingPresetName + '\" and lose current changes?'"></span></p><div class="modal-action"><button class="btn btn-ghost text-gray-400" @click="cancelLoadPreset()"x-text="$store.global.t('cancel')">Cancel</button><button class="btn bg-yellow-500 hover:bg-yellow-600 border-none text-black" @click="confirmLoadPreset()"><span x-text="$store.global.t('loadAnyway') || 'Load Anyway'">Load Anyway</span></button></div></div><form method="dialog" class="modal-backdrop"><button @click="cancelLoadPreset()">close</button></form></dialog><!-- Save Preset Modal --><dialog id="save_preset_modal" class="modal" x-data="{ presetName: '' }"><div class="modal-box bg-space-900 border-2 border-neon-cyan/50"><h3 class="font-bold text-lg text-neon-cyan flex items-center gap-2"><svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" /></svg><span x-text="$store.global.t('savePresetTitle') || 'Save Preset'">Save Preset</span></h3><p class="py-2 text-gray-400 text-sm" x-text="$store.global.t('savePresetDesc') || 'Save the current configuration as a reusable preset.'">Save the current configuration as a reusable preset.</p><div class="form-control mt-4"><label class="label"><span class="label-text text-gray-300" x-text="$store.global.t('presetName') || 'Preset Name'">Preset Name</span></label><input type="text" x-model="presetName"class="input input-sm input-bordered bg-space-800 border-space-border text-white w-full":placeholder="$store.global.t('presetNamePlaceholder') || 'e.g., My Work Setup'"@keydown.enter="$root.executeSavePreset(presetName); presetName = ''"x-init="$watch('$el.closest(\'dialog\').open', open => { if (open) { presetName = ''; $nextTick(() => $el.focus()) } })"aria-label="Preset name"></div><div class="modal-action"><button class="btn btn-ghost text-gray-400" @click="presetName = ''; document.getElementById('save_preset_modal').close()"x-text="$store.global.t('cancel')">Cancel</button><button class="btn bg-neon-cyan hover:bg-cyan-600 border-none text-black"@click="$root.executeSavePreset(presetName); presetName = ''":disabled="!presetName.trim() || $root.savingPreset":class="{ 'loading': $root.savingPreset }"><span x-show="!$root.savingPreset" x-text="$store.global.t('savePreset') || 'Save Preset'">Save Preset</span></button></div></div><form method="dialog" class="modal-backdrop"><button @click="presetName = ''">close</button></form></dialog></div><!-- Tab 3: Models Configuration -->
137 unmodified lines138139140137 unmodified linesfunction isObject(item) {return (item && typeof item === 'object' && !Array.isArray(item));}137 unmodified lines138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276137 unmodified linesfunction isObject(item) {return (item && typeof item === 'object' && !Array.isArray(item));}// ==========================================// Claude CLI Presets// ==========================================/*** Default presets based on README examples*/const DEFAULT_PRESETS = [{name: 'Claude Thinking',config: {ANTHROPIC_AUTH_TOKEN: 'test',ANTHROPIC_BASE_URL: 'http://localhost:8080',ANTHROPIC_MODEL: 'claude-opus-4-5-thinking',ANTHROPIC_DEFAULT_OPUS_MODEL: 'claude-opus-4-5-thinking',ANTHROPIC_DEFAULT_SONNET_MODEL: 'claude-sonnet-4-5-thinking',ANTHROPIC_DEFAULT_HAIKU_MODEL: 'gemini-2.5-flash-lite[1m]',CLAUDE_CODE_SUBAGENT_MODEL: 'claude-sonnet-4-5-thinking',ENABLE_EXPERIMENTAL_MCP_CLI: 'true'}},{name: 'Gemini 1M',config: {ANTHROPIC_AUTH_TOKEN: 'test',ANTHROPIC_BASE_URL: 'http://localhost:8080',ANTHROPIC_MODEL: 'gemini-3-pro-high[1m]',ANTHROPIC_DEFAULT_OPUS_MODEL: 'gemini-3-pro-high[1m]',ANTHROPIC_DEFAULT_SONNET_MODEL: 'gemini-3-flash[1m]',ANTHROPIC_DEFAULT_HAIKU_MODEL: 'gemini-2.5-flash-lite[1m]',CLAUDE_CODE_SUBAGENT_MODEL: 'gemini-3-flash[1m]',ENABLE_EXPERIMENTAL_MCP_CLI: 'true'}}];/*** Get the path to the presets file* @returns {string} Absolute path to claude-presets.json*/export function getPresetsPath() {return path.join(os.homedir(), '.config', 'antigravity-proxy', 'claude-presets.json');}/*** Read all Claude CLI presets* Creates the file with default presets if it doesn't exist.* @returns {Promise<Array>} Array of preset objects*/export async function readPresets() {const presetsPath = getPresetsPath();try {const content = await fs.readFile(presetsPath, 'utf8');if (!content.trim()) return DEFAULT_PRESETS;return JSON.parse(content);} catch (error) {if (error.code === 'ENOENT') {// Create with defaultstry {await fs.mkdir(path.dirname(presetsPath), { recursive: true });await fs.writeFile(presetsPath, JSON.stringify(DEFAULT_PRESETS, null, 2), 'utf8');logger.info(`[ClaudePresets] Created presets file with defaults at ${presetsPath}`);} catch (writeError) {logger.warn(`[ClaudePresets] Could not create presets file: ${writeError.message}`);}return DEFAULT_PRESETS;}if (error instanceof SyntaxError) {logger.error(`[ClaudePresets] Invalid JSON in presets at ${presetsPath}. Returning defaults.`);return DEFAULT_PRESETS;}logger.error(`[ClaudePresets] Failed to read presets at ${presetsPath}:`, error.message);throw error;}}/*** Save a preset (add or update)* @param {string} name - Preset name* @param {Object} config - Environment variables to save* @returns {Promise<Array>} Updated array of presets*/export async function savePreset(name, config) {const presetsPath = getPresetsPath();let presets = await readPresets();const existingIndex = presets.findIndex(p => p.name === name);const newPreset = { name, config: { ...config } };if (existingIndex >= 0) {presets[existingIndex] = newPreset;logger.info(`[ClaudePresets] Updated preset: ${name}`);} else {presets.push(newPreset);logger.info(`[ClaudePresets] Created preset: ${name}`);}try {await fs.mkdir(path.dirname(presetsPath), { recursive: true });await fs.writeFile(presetsPath, JSON.stringify(presets, null, 2), 'utf8');} catch (error) {logger.error(`[ClaudePresets] Failed to save preset:`, error.message);throw error;}return presets;}/*** Delete a preset by name* @param {string} name - Preset name to delete* @returns {Promise<Array>} Updated array of presets*/export async function deletePreset(name) {const presetsPath = getPresetsPath();let presets = await readPresets();const originalLength = presets.length;presets = presets.filter(p => p.name !== name);if (presets.length === originalLength) {logger.warn(`[ClaudePresets] Preset not found: ${name}`);return presets;}try {await fs.writeFile(presetsPath, JSON.stringify(presets, null, 2), 'utf8');logger.info(`[ClaudePresets] Deleted preset: ${name}`);} catch (error) {logger.error(`[ClaudePresets] Failed to delete preset:`, error.message);throw error;}return presets;}
17 unmodified lines18192021222324459 unmodified lines48448548648748848917 unmodified linesimport express from 'express';import { getPublicConfig, saveConfig, config } from '../config.js';import { DEFAULT_PORT, ACCOUNT_CONFIG_PATH } from '../constants.js';import { readClaudeConfig, updateClaudeConfig, replaceClaudeConfig, getClaudeConfigPath } from '../utils/claude-config.js';import { logger } from '../utils/logger.js';import { getAuthorizationUrl, completeOAuthFlow, startCallbackServer } from '../auth/oauth.js';import { loadAccounts, saveAccounts } from '../account-manager/storage.js';459 unmodified lines}});/*** POST /api/models/config - Update model configuration (hidden/pinned/alias)*/17 unmodified lines18192021222324459 unmodified lines48448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154217 unmodified linesimport express from 'express';import { getPublicConfig, saveConfig, config } from '../config.js';import { DEFAULT_PORT, ACCOUNT_CONFIG_PATH } from '../constants.js';import { readClaudeConfig, updateClaudeConfig, replaceClaudeConfig, getClaudeConfigPath, readPresets, savePreset, deletePreset } from '../utils/claude-config.js';import { logger } from '../utils/logger.js';import { getAuthorizationUrl, completeOAuthFlow, startCallbackServer } from '../auth/oauth.js';import { loadAccounts, saveAccounts } from '../account-manager/storage.js';459 unmodified lines}});// ==========================================// Claude CLI Presets API// ==========================================/*** GET /api/claude/presets - Get all saved presets*/app.get('/api/claude/presets', async (req, res) => {try {const presets = await readPresets();res.json({ status: 'ok', presets });} catch (error) {res.status(500).json({ status: 'error', error: error.message });}});/*** POST /api/claude/presets - Save a new preset*/app.post('/api/claude/presets', async (req, res) => {try {const { name, config: presetConfig } = req.body;if (!name || typeof name !== 'string' || !name.trim()) {return res.status(400).json({ status: 'error', error: 'Preset name is required' });}if (!presetConfig || typeof presetConfig !== 'object') {return res.status(400).json({ status: 'error', error: 'Config object is required' });}const presets = await savePreset(name.trim(), presetConfig);res.json({ status: 'ok', presets, message: `Preset "${name}" saved` });} catch (error) {res.status(500).json({ status: 'error', error: error.message });}});/*** DELETE /api/claude/presets/:name - Delete a preset*/app.delete('/api/claude/presets/:name', async (req, res) => {try {const { name } = req.params;if (!name) {return res.status(400).json({ status: 'error', error: 'Preset name is required' });}const presets = await deletePreset(name);res.json({ status: 'ok', presets, message: `Preset "${name}" deleted` });} catch (error) {res.status(500).json({ status: 'error', error: error.message });}});/*** POST /api/models/config - Update model configuration (hidden/pinned/alias)*/
312 unmodified lines313314315316317318312 unmodified lines}return 'app.js loads with all required components';}}];312 unmodified lines313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415312 unmodified lines}return 'app.js loads with all required components';}},// ==================== PRESETS API TESTS ===================={name: 'Presets API GET returns presets array',async run() {const res = await request('/api/claude/presets');if (res.status !== 200) {throw new Error(`Expected 200, got ${res.status}`);}const data = JSON.parse(res.data);if (data.status !== 'ok') {throw new Error(`Expected status ok, got ${data.status}`);}if (!Array.isArray(data.presets)) {throw new Error('presets should be an array');}return `Presets API returns ${data.presets.length} preset(s)`;}},{name: 'Presets API POST creates new preset',async run() {const testPreset = {name: '__test_preset__',config: {ANTHROPIC_BASE_URL: 'http://localhost:8080',ANTHROPIC_MODEL: 'test-model'}};// Create presetconst postRes = await request('/api/claude/presets', {method: 'POST',body: testPreset});if (postRes.status !== 200) {throw new Error(`POST failed with status ${postRes.status}`);}const postData = JSON.parse(postRes.data);if (postData.status !== 'ok') {throw new Error(`POST returned error: ${postData.error}`);}// Verify it existsconst getRes = await request('/api/claude/presets');const getData = JSON.parse(getRes.data);const found = getData.presets.find(p => p.name === '__test_preset__');if (!found) {throw new Error('Created preset not found in list');}return 'Preset created and verified';}},{name: 'Presets API DELETE removes preset',async run() {// Delete the test preset created aboveconst deleteRes = await request('/api/claude/presets/__test_preset__', {method: 'DELETE'});if (deleteRes.status !== 200) {throw new Error(`DELETE failed with status ${deleteRes.status}`);}// Verify it's goneconst getRes = await request('/api/claude/presets');const getData = JSON.parse(getRes.data);const found = getData.presets.find(p => p.name === '__test_preset__');if (found) {throw new Error('Deleted preset still exists');}return 'Preset deleted and verified';}},{name: 'Settings view has presets UI elements',async run() {const res = await request('/views/settings.html');const html = res.data;const presetElements = ['selectedPresetName', // Preset dropdown binding'saveCurrentAsPreset', // Save button function'deleteSelectedPreset', // Delete button function'save_preset_modal', // Save modal'configPresets' // Translation key for section title];const missing = presetElements.filter(el => !html.includes(el));if (missing.length > 0) {throw new Error(`Missing preset UI elements: ${missing.join(', ')}`);}return 'All preset UI elements present';}}];
public/css/style.css
public/js/components/claude-config.js+241
public/js/store.js+36
public/views/settings.html+112
src/utils/claude-config.js+136
src/webui/index.js+54-1
tests/frontend/test-frontend-settings.cjs+97